summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorKeong Lim <keong.lim@huawei.com>2019-03-21 15:33:44 +1100
committerKeong Lim <keong.lim@huawei.com>2019-04-11 13:43:41 +1000
commitbf628be4bffca6195dde1926e90211e3c5dc54b6 (patch)
tree49f7145fafc976bfd437a8077198729e82591312
parent9d57926991512a9e5510ca0b08217fe7c1a7ea76 (diff)
AAI-1523 Batch reformat aai-core
Use maven plugins from AAI-2198 to do batch reformat of aai-core to consistent code style. Change-Id: If43889a61778f3a766c3663098064cdcc8e507bf Issue-ID: AAI-1523 Signed-off-by: Keong Lim <keong.lim@huawei.com>
-rw-r--r--aai-core/src/main/java/org/onap/aai/audit/ListEndpoints.java535
-rw-r--r--aai-core/src/main/java/org/onap/aai/auth/AAIAuthCore.java630
-rw-r--r--aai-core/src/main/java/org/onap/aai/auth/AAIUser.java1
-rw-r--r--aai-core/src/main/java/org/onap/aai/auth/exceptions/AAIUnrecognizedFunctionException.java6
-rw-r--r--aai-core/src/main/java/org/onap/aai/concurrent/AaiCallable.java35
-rw-r--r--aai-core/src/main/java/org/onap/aai/config/AuthorizationConfiguration.java3
-rw-r--r--aai-core/src/main/java/org/onap/aai/config/IntrospectionConfig.java20
-rw-r--r--aai-core/src/main/java/org/onap/aai/config/RestBeanConfig.java9
-rw-r--r--aai-core/src/main/java/org/onap/aai/config/SchemaConfiguration.java43
-rw-r--r--aai-core/src/main/java/org/onap/aai/config/SpringContextAware.java27
-rw-r--r--aai-core/src/main/java/org/onap/aai/db/DbMethHelper.java229
-rw-r--r--aai-core/src/main/java/org/onap/aai/db/props/AAIProperties.java5
-rw-r--r--aai-core/src/main/java/org/onap/aai/dbgen/GraphSONPartialIO.java30
-rw-r--r--aai-core/src/main/java/org/onap/aai/dbgen/GraphSONPartialReader.java282
-rw-r--r--aai-core/src/main/java/org/onap/aai/dbgen/PropertyLimitDesc.java5
-rw-r--r--aai-core/src/main/java/org/onap/aai/dbgen/SchemaGenerator.java287
-rw-r--r--aai-core/src/main/java/org/onap/aai/dbmap/AAIGraph.java51
-rw-r--r--aai-core/src/main/java/org/onap/aai/dbmap/AAIGraphConfig.java102
-rw-r--r--aai-core/src/main/java/org/onap/aai/dbmap/DBConnectionType.java4
-rw-r--r--aai-core/src/main/java/org/onap/aai/dbmap/InMemoryGraph.java220
-rw-r--r--aai-core/src/main/java/org/onap/aai/dmaap/AAIDmaapEventJMSConsumer.java18
-rw-r--r--aai-core/src/main/java/org/onap/aai/dmaap/AAIDmaapEventJMSProducer.java8
-rw-r--r--aai-core/src/main/java/org/onap/aai/dmaap/MessageProducer.java1
-rw-r--r--aai-core/src/main/java/org/onap/aai/domain/model/AAIResource.java1294
-rw-r--r--aai-core/src/main/java/org/onap/aai/domain/model/AAIResourceKey.java155
-rw-r--r--aai-core/src/main/java/org/onap/aai/domain/model/AAIResourceKeys.java25
-rw-r--r--aai-core/src/main/java/org/onap/aai/domain/model/AAIResources.java114
-rw-r--r--aai-core/src/main/java/org/onap/aai/domain/notificationEvent/NotificationEvent.java241
-rw-r--r--aai-core/src/main/java/org/onap/aai/domain/notificationEvent/ObjectFactory.java27
-rw-r--r--aai-core/src/main/java/org/onap/aai/domain/responseMessage/AAIResponseMessage.java164
-rw-r--r--aai-core/src/main/java/org/onap/aai/domain/responseMessage/AAIResponseMessageData.java7
-rw-r--r--aai-core/src/main/java/org/onap/aai/domain/responseMessage/AAIResponseMessageDatum.java80
-rw-r--r--aai-core/src/main/java/org/onap/aai/domain/responseMessage/AAIResponseMessages.java65
-rw-r--r--aai-core/src/main/java/org/onap/aai/domain/responseMessage/package-info.java15
-rw-r--r--aai-core/src/main/java/org/onap/aai/domain/restPolicyException/Fault.java111
-rw-r--r--aai-core/src/main/java/org/onap/aai/domain/restPolicyException/ObjectFactory.java27
-rw-r--r--aai-core/src/main/java/org/onap/aai/domain/restPolicyException/PolicyException.java31
-rw-r--r--aai-core/src/main/java/org/onap/aai/domain/restPolicyException/RESTResponse.java17
-rw-r--r--aai-core/src/main/java/org/onap/aai/domain/restPolicyException/RequestError.java18
-rw-r--r--aai-core/src/main/java/org/onap/aai/domain/restResponseInfo/Info.java102
-rw-r--r--aai-core/src/main/java/org/onap/aai/domain/restResponseInfo/ObjectFactory.java27
-rw-r--r--aai-core/src/main/java/org/onap/aai/domain/restServiceException/Fault.java111
-rw-r--r--aai-core/src/main/java/org/onap/aai/domain/restServiceException/ObjectFactory.java27
-rw-r--r--aai-core/src/main/java/org/onap/aai/domain/restServiceException/RESTResponse.java17
-rw-r--r--aai-core/src/main/java/org/onap/aai/domain/restServiceException/RequestError.java17
-rw-r--r--aai-core/src/main/java/org/onap/aai/domain/restServiceException/ServiceException.java31
-rw-r--r--aai-core/src/main/java/org/onap/aai/domain/translog/TransactionLogEntries.java15
-rw-r--r--aai-core/src/main/java/org/onap/aai/domain/translog/TransactionLogEntry.java791
-rw-r--r--aai-core/src/main/java/org/onap/aai/exceptions/AAIException.java33
-rw-r--r--aai-core/src/main/java/org/onap/aai/exceptions/AAIExceptionWithInfo.java204
-rw-r--r--aai-core/src/main/java/org/onap/aai/extensions/AAIExtensionMap.java1587
-rw-r--r--aai-core/src/main/java/org/onap/aai/extensions/ExtensionController.java222
-rw-r--r--aai-core/src/main/java/org/onap/aai/extensions/OrphanLInterfaceHandler.java145
-rw-r--r--aai-core/src/main/java/org/onap/aai/ingestModel/CreateWidgetModels.java224
-rw-r--r--aai-core/src/main/java/org/onap/aai/introspection/Introspector.java1198
-rw-r--r--aai-core/src/main/java/org/onap/aai/introspection/IntrospectorFactory.java69
-rw-r--r--aai-core/src/main/java/org/onap/aai/introspection/IntrospectorWalker.java326
-rw-r--r--aai-core/src/main/java/org/onap/aai/introspection/JSONStrategy.java663
-rw-r--r--aai-core/src/main/java/org/onap/aai/introspection/Loader.java149
-rw-r--r--aai-core/src/main/java/org/onap/aai/introspection/LoaderFactory.java69
-rw-r--r--aai-core/src/main/java/org/onap/aai/introspection/LoaderUtil.java5
-rw-r--r--aai-core/src/main/java/org/onap/aai/introspection/MarshallerProperties.java225
-rw-r--r--aai-core/src/main/java/org/onap/aai/introspection/ModelType.java3
-rw-r--r--aai-core/src/main/java/org/onap/aai/introspection/MoxyLoader.java318
-rw-r--r--aai-core/src/main/java/org/onap/aai/introspection/MoxyStrategy.java590
-rw-r--r--aai-core/src/main/java/org/onap/aai/introspection/PropertyPredicate.java1
-rw-r--r--aai-core/src/main/java/org/onap/aai/introspection/PropertyPredicates.java99
-rw-r--r--aai-core/src/main/java/org/onap/aai/introspection/Visibility.java6
-rw-r--r--aai-core/src/main/java/org/onap/aai/introspection/Wanderer.java114
-rw-r--r--aai-core/src/main/java/org/onap/aai/introspection/exceptions/AAIUnknownObjectException.java24
-rw-r--r--aai-core/src/main/java/org/onap/aai/introspection/exceptions/AAIUnmarshallingException.java24
-rw-r--r--aai-core/src/main/java/org/onap/aai/introspection/generator/CreateExample.java276
-rw-r--r--aai-core/src/main/java/org/onap/aai/introspection/sideeffect/DataCopy.java104
-rw-r--r--aai-core/src/main/java/org/onap/aai/introspection/sideeffect/DataLinkReader.java121
-rw-r--r--aai-core/src/main/java/org/onap/aai/introspection/sideeffect/DataLinkWriter.java143
-rw-r--r--aai-core/src/main/java/org/onap/aai/introspection/sideeffect/PrivateEdge.java83
-rw-r--r--aai-core/src/main/java/org/onap/aai/introspection/sideeffect/SideEffect.java214
-rw-r--r--aai-core/src/main/java/org/onap/aai/introspection/sideeffect/SideEffectRunner.java138
-rw-r--r--aai-core/src/main/java/org/onap/aai/introspection/sideeffect/SideEffectRunnerHelper.java109
-rw-r--r--aai-core/src/main/java/org/onap/aai/introspection/sideeffect/exceptions/AAIMissingRequiredPropertyException.java26
-rw-r--r--aai-core/src/main/java/org/onap/aai/introspection/sideeffect/exceptions/AAIMultiplePropertiesException.java27
-rw-r--r--aai-core/src/main/java/org/onap/aai/introspection/tools/CreateUUID.java56
-rw-r--r--aai-core/src/main/java/org/onap/aai/introspection/tools/DefaultFields.java39
-rw-r--r--aai-core/src/main/java/org/onap/aai/introspection/tools/InjectKeysFromURI.java79
-rw-r--r--aai-core/src/main/java/org/onap/aai/introspection/tools/IntrospectorValidator.java573
-rw-r--r--aai-core/src/main/java/org/onap/aai/introspection/tools/Issue.java234
-rw-r--r--aai-core/src/main/java/org/onap/aai/introspection/tools/IssueResolver.java16
-rw-r--r--aai-core/src/main/java/org/onap/aai/introspection/tools/IssueType.java3
-rw-r--r--aai-core/src/main/java/org/onap/aai/introspection/tools/RemoveNonVisibleProperty.java19
-rw-r--r--aai-core/src/main/java/org/onap/aai/introspection/tools/Severity.java5
-rw-r--r--aai-core/src/main/java/org/onap/aai/logging/CNName.java101
-rw-r--r--aai-core/src/main/java/org/onap/aai/logging/CustomLogPatternLayout.java9
-rw-r--r--aai-core/src/main/java/org/onap/aai/logging/CustomLogPatternLayoutEncoder.java25
-rw-r--r--aai-core/src/main/java/org/onap/aai/logging/DME2RestFlag.java49
-rw-r--r--aai-core/src/main/java/org/onap/aai/logging/EcompElapsedTime.java60
-rw-r--r--aai-core/src/main/java/org/onap/aai/logging/EcompEncoder.java1
-rw-r--r--aai-core/src/main/java/org/onap/aai/logging/EcompErrorCategory.java30
-rw-r--r--aai-core/src/main/java/org/onap/aai/logging/EcompPatternLayout.java21
-rw-r--r--aai-core/src/main/java/org/onap/aai/logging/EcompResponseCode.java21
-rw-r--r--aai-core/src/main/java/org/onap/aai/logging/EcompResponseDescription.java36
-rw-r--r--aai-core/src/main/java/org/onap/aai/logging/EcompServiceName.java3
-rw-r--r--aai-core/src/main/java/org/onap/aai/logging/EcompStartTime.java19
-rw-r--r--aai-core/src/main/java/org/onap/aai/logging/EcompStatusCode.java5
-rw-r--r--aai-core/src/main/java/org/onap/aai/logging/EelfClassOfCaller.java9
-rw-r--r--aai-core/src/main/java/org/onap/aai/logging/ErrorLogHelper.java1143
-rw-r--r--aai-core/src/main/java/org/onap/aai/logging/ErrorObject.java648
-rw-r--r--aai-core/src/main/java/org/onap/aai/logging/ErrorObjectFormatException.java9
-rw-r--r--aai-core/src/main/java/org/onap/aai/logging/ErrorObjectNotFoundException.java53
-rw-r--r--aai-core/src/main/java/org/onap/aai/logging/LogFormatTools.java176
-rw-r--r--aai-core/src/main/java/org/onap/aai/logging/LoggingContext.java762
-rw-r--r--aai-core/src/main/java/org/onap/aai/logging/LoggingContextNotExistsException.java3
-rw-r--r--aai-core/src/main/java/org/onap/aai/logging/StopWatch.java55
-rw-r--r--aai-core/src/main/java/org/onap/aai/logging/StopWatchNotStartedException.java27
-rw-r--r--aai-core/src/main/java/org/onap/aai/parsers/exceptions/AAIIdentityMapParseException.java23
-rw-r--r--aai-core/src/main/java/org/onap/aai/parsers/exceptions/AmbiguousMapAAIException.java29
-rw-r--r--aai-core/src/main/java/org/onap/aai/parsers/exceptions/DoesNotStartWithValidNamespaceException.java24
-rw-r--r--aai-core/src/main/java/org/onap/aai/parsers/query/LegacyQueryParser.java390
-rw-r--r--aai-core/src/main/java/org/onap/aai/parsers/query/ObjectNameQueryParser.java11
-rw-r--r--aai-core/src/main/java/org/onap/aai/parsers/query/QueryParser.java227
-rw-r--r--aai-core/src/main/java/org/onap/aai/parsers/query/QueryParserStrategy.java118
-rw-r--r--aai-core/src/main/java/org/onap/aai/parsers/query/RelationshipQueryParser.java77
-rw-r--r--aai-core/src/main/java/org/onap/aai/parsers/query/TraversalStrategy.java88
-rw-r--r--aai-core/src/main/java/org/onap/aai/parsers/query/UniqueRelationshipQueryParser.java45
-rw-r--r--aai-core/src/main/java/org/onap/aai/parsers/query/UniqueStrategy.java91
-rw-r--r--aai-core/src/main/java/org/onap/aai/parsers/query/UniqueURIQueryParser.java257
-rw-r--r--aai-core/src/main/java/org/onap/aai/parsers/relationship/RelationshipToURI.java484
-rw-r--r--aai-core/src/main/java/org/onap/aai/parsers/uri/Parsable.java81
-rw-r--r--aai-core/src/main/java/org/onap/aai/parsers/uri/URIParser.java475
-rw-r--r--aai-core/src/main/java/org/onap/aai/parsers/uri/URIToDBKey.java143
-rw-r--r--aai-core/src/main/java/org/onap/aai/parsers/uri/URIToExtensionInformation.java274
-rw-r--r--aai-core/src/main/java/org/onap/aai/parsers/uri/URIToObject.java366
-rw-r--r--aai-core/src/main/java/org/onap/aai/parsers/uri/URIToRelationshipObject.java256
-rw-r--r--aai-core/src/main/java/org/onap/aai/parsers/uri/URIValidate.java69
-rw-r--r--aai-core/src/main/java/org/onap/aai/query/builder/GraphTraversalBuilder.java1580
-rw-r--r--aai-core/src/main/java/org/onap/aai/query/builder/GremlinQueryBuilder.java148
-rw-r--r--aai-core/src/main/java/org/onap/aai/query/builder/GremlinTraversal.java198
-rw-r--r--aai-core/src/main/java/org/onap/aai/query/builder/GremlinUnique.java198
-rw-r--r--aai-core/src/main/java/org/onap/aai/query/builder/MissingOptionalParameter.java18
-rw-r--r--aai-core/src/main/java/org/onap/aai/query/builder/QueryBuilder.java1157
-rw-r--r--aai-core/src/main/java/org/onap/aai/query/builder/TraversalQuery.java242
-rw-r--r--aai-core/src/main/java/org/onap/aai/query/builder/TraversalURIOptimizedQuery.java235
-rw-r--r--aai-core/src/main/java/org/onap/aai/rest/RestHandlerService.java6
-rw-r--r--aai-core/src/main/java/org/onap/aai/rest/RestTokens.java19
-rw-r--r--aai-core/src/main/java/org/onap/aai/rest/db/DBRequest.java425
-rw-r--r--aai-core/src/main/java/org/onap/aai/rest/db/HttpEntry.java2302
-rw-r--r--aai-core/src/main/java/org/onap/aai/rest/ueb/NotificationEvent.java126
-rw-r--r--aai-core/src/main/java/org/onap/aai/rest/ueb/UEBNotification.java294
-rw-r--r--aai-core/src/main/java/org/onap/aai/restcore/CustomJacksonJaxBJsonProvider.java61
-rw-r--r--aai-core/src/main/java/org/onap/aai/restcore/HttpMethod.java9
-rw-r--r--aai-core/src/main/java/org/onap/aai/restcore/JettyObfuscationConversionCommandLineUtil.java93
-rw-r--r--aai-core/src/main/java/org/onap/aai/restcore/MediaType.java32
-rw-r--r--aai-core/src/main/java/org/onap/aai/restcore/RESTAPI.java666
-rw-r--r--aai-core/src/main/java/org/onap/aai/restcore/search/AAIAbstractGroovyShell.java79
-rw-r--r--aai-core/src/main/java/org/onap/aai/restcore/search/GremlinGroovyShell.java50
-rw-r--r--aai-core/src/main/java/org/onap/aai/restcore/search/GroovyQueryBuilder.java59
-rw-r--r--aai-core/src/main/java/org/onap/aai/restcore/util/URITools.java147
-rw-r--r--aai-core/src/main/java/org/onap/aai/serialization/db/DBSerializer.java734
-rw-r--r--aai-core/src/main/java/org/onap/aai/serialization/db/DeleteSemantic.java23
-rw-r--r--aai-core/src/main/java/org/onap/aai/serialization/db/EdgeProperties.java27
-rw-r--r--aai-core/src/main/java/org/onap/aai/serialization/db/EdgePropertyMap.java60
-rw-r--r--aai-core/src/main/java/org/onap/aai/serialization/db/EdgeSerializer.java455
-rw-r--r--aai-core/src/main/java/org/onap/aai/serialization/db/GetAllPool.java37
-rw-r--r--aai-core/src/main/java/org/onap/aai/serialization/db/GraphSingleton.java77
-rw-r--r--aai-core/src/main/java/org/onap/aai/serialization/db/InMemoryGraphSingleton.java64
-rw-r--r--aai-core/src/main/java/org/onap/aai/serialization/db/JanusGraphSingleton.java25
-rw-r--r--aai-core/src/main/java/org/onap/aai/serialization/db/exceptions/EdgeMultiplicityException.java21
-rw-r--r--aai-core/src/main/java/org/onap/aai/serialization/db/exceptions/MultipleEdgeRuleFoundException.java21
-rw-r--r--aai-core/src/main/java/org/onap/aai/serialization/db/exceptions/NoEdgeRuleFoundException.java23
-rw-r--r--aai-core/src/main/java/org/onap/aai/serialization/engines/InMemoryDBEngine.java335
-rw-r--r--aai-core/src/main/java/org/onap/aai/serialization/engines/JanusGraphDBEngine.java133
-rw-r--r--aai-core/src/main/java/org/onap/aai/serialization/engines/QueryStyle.java3
-rw-r--r--aai-core/src/main/java/org/onap/aai/serialization/engines/TransactionalGraphEngine.java427
-rw-r--r--aai-core/src/main/java/org/onap/aai/serialization/engines/query/GraphTraversalQueryEngine.java332
-rw-r--r--aai-core/src/main/java/org/onap/aai/serialization/engines/query/GremlinPipelineQueryEngine.java365
-rw-r--r--aai-core/src/main/java/org/onap/aai/serialization/engines/query/GremlinQueryEngine.java345
-rw-r--r--aai-core/src/main/java/org/onap/aai/serialization/engines/query/QueryEngine.java242
-rw-r--r--aai-core/src/main/java/org/onap/aai/serialization/queryformats/Console.java30
-rw-r--r--aai-core/src/main/java/org/onap/aai/serialization/queryformats/Count.java93
-rw-r--r--aai-core/src/main/java/org/onap/aai/serialization/queryformats/Format.java27
-rw-r--r--aai-core/src/main/java/org/onap/aai/serialization/queryformats/FormatFactory.java131
-rw-r--r--aai-core/src/main/java/org/onap/aai/serialization/queryformats/FormatMapper.java12
-rw-r--r--aai-core/src/main/java/org/onap/aai/serialization/queryformats/Formatter.java123
-rw-r--r--aai-core/src/main/java/org/onap/aai/serialization/queryformats/GraphSON.java187
-rw-r--r--aai-core/src/main/java/org/onap/aai/serialization/queryformats/IdURL.java61
-rw-r--r--aai-core/src/main/java/org/onap/aai/serialization/queryformats/MultiFormatMapper.java152
-rw-r--r--aai-core/src/main/java/org/onap/aai/serialization/queryformats/PathedURL.java60
-rw-r--r--aai-core/src/main/java/org/onap/aai/serialization/queryformats/RawFormat.java348
-rw-r--r--aai-core/src/main/java/org/onap/aai/serialization/queryformats/Resource.java267
-rw-r--r--aai-core/src/main/java/org/onap/aai/serialization/queryformats/ResourceWithSoT.java19
-rw-r--r--aai-core/src/main/java/org/onap/aai/serialization/queryformats/SimpleFormat.java109
-rw-r--r--aai-core/src/main/java/org/onap/aai/serialization/queryformats/SubGraphStyle.java5
-rw-r--r--aai-core/src/main/java/org/onap/aai/serialization/queryformats/exceptions/AAIFormatQueryResultFormatNotSupported.java24
-rw-r--r--aai-core/src/main/java/org/onap/aai/serialization/queryformats/exceptions/AAIFormatVertexException.java24
-rw-r--r--aai-core/src/main/java/org/onap/aai/serialization/queryformats/exceptions/QueryParamInjectionException.java21
-rw-r--r--aai-core/src/main/java/org/onap/aai/serialization/queryformats/params/Depth.java5
-rw-r--r--aai-core/src/main/java/org/onap/aai/serialization/queryformats/params/Inject.java12
-rw-r--r--aai-core/src/main/java/org/onap/aai/serialization/queryformats/params/NodesOnly.java5
-rw-r--r--aai-core/src/main/java/org/onap/aai/serialization/queryformats/params/Setter.java1
-rw-r--r--aai-core/src/main/java/org/onap/aai/serialization/queryformats/utils/QueryParamInjector.java94
-rw-r--r--aai-core/src/main/java/org/onap/aai/serialization/queryformats/utils/UrlBuilder.java129
-rw-r--r--aai-core/src/main/java/org/onap/aai/serialization/tinkerpop/TreeBackedEdge.java78
-rw-r--r--aai-core/src/main/java/org/onap/aai/serialization/tinkerpop/TreeBackedVertex.java245
-rw-r--r--aai-core/src/main/java/org/onap/aai/service/NodeValidationService.java15
-rw-r--r--aai-core/src/main/java/org/onap/aai/tasks/ScheduledTasks.java109
-rw-r--r--aai-core/src/main/java/org/onap/aai/util/AAIConfig.java205
-rw-r--r--aai-core/src/main/java/org/onap/aai/util/AAIConfigCommandLinePropGetter.java58
-rw-r--r--aai-core/src/main/java/org/onap/aai/util/AAIConstants.java20
-rw-r--r--aai-core/src/main/java/org/onap/aai/util/AAISystemExitUtil.java19
-rw-r--r--aai-core/src/main/java/org/onap/aai/util/AAIUtils.java5
-rw-r--r--aai-core/src/main/java/org/onap/aai/util/Entity.java44
-rw-r--r--aai-core/src/main/java/org/onap/aai/util/EntityList.java25
-rw-r--r--aai-core/src/main/java/org/onap/aai/util/FileWatcher.java60
-rw-r--r--aai-core/src/main/java/org/onap/aai/util/FormatDate.java36
-rw-r--r--aai-core/src/main/java/org/onap/aai/util/HbaseSaltPrefixer.java60
-rw-r--r--aai-core/src/main/java/org/onap/aai/util/HttpsAuthClient.java201
-rw-r--r--aai-core/src/main/java/org/onap/aai/util/HttpsAuthExternalClient.java150
-rw-r--r--aai-core/src/main/java/org/onap/aai/util/JettyObfuscationConversionCommandLineUtil.java83
-rw-r--r--aai-core/src/main/java/org/onap/aai/util/KeyValueList.java26
-rw-r--r--aai-core/src/main/java/org/onap/aai/util/MapperUtil.java6
-rw-r--r--aai-core/src/main/java/org/onap/aai/util/PojoUtils.java626
-rw-r--r--aai-core/src/main/java/org/onap/aai/util/Request.java242
-rw-r--r--aai-core/src/main/java/org/onap/aai/util/RestController.java1098
-rw-r--r--aai-core/src/main/java/org/onap/aai/util/RestControllerInterface.java14
-rw-r--r--aai-core/src/main/java/org/onap/aai/util/RestObject.java22
-rw-r--r--aai-core/src/main/java/org/onap/aai/util/RestURLEncoder.java25
-rw-r--r--aai-core/src/main/java/org/onap/aai/util/StoreNotificationEvent.java623
-rw-r--r--aai-core/src/main/java/org/onap/aai/web/DmaapConfig.java19
-rw-r--r--aai-core/src/main/java/org/onap/aai/web/EventClientPublisher.java21
-rw-r--r--aai-core/src/main/java/org/onap/aai/workarounds/NamingExceptions.java109
-rw-r--r--aai-core/src/test/java/org/onap/aai/AAIJunitRunner.java11
-rw-r--r--aai-core/src/test/java/org/onap/aai/AAISetup.java65
-rw-r--r--aai-core/src/test/java/org/onap/aai/AAISetupForSwagger.java25
-rw-r--r--aai-core/src/test/java/org/onap/aai/AbstractConfigTranslator.java34
-rw-r--r--aai-core/src/test/java/org/onap/aai/DataLinkSetup.java91
-rw-r--r--aai-core/src/test/java/org/onap/aai/HttpTestUtil.java161
-rw-r--r--aai-core/src/test/java/org/onap/aai/PayloadUtil.java26
-rw-r--r--aai-core/src/test/java/org/onap/aai/auth/AAIAuthCoreTest.java92
-rw-r--r--aai-core/src/test/java/org/onap/aai/auth/AAIUserTest.java13
-rw-r--r--aai-core/src/test/java/org/onap/aai/concurrent/AaiCallableTest.java12
-rw-r--r--aai-core/src/test/java/org/onap/aai/dbmap/AAIGraphTest.java122
-rw-r--r--aai-core/src/test/java/org/onap/aai/domain/restPolicyException/PolicyExceptionTest.java11
-rw-r--r--aai-core/src/test/java/org/onap/aai/domain/restPolicyException/RequestErrorTest.java5
-rw-r--r--aai-core/src/test/java/org/onap/aai/exceptions/AAIExceptionTest.java19
-rw-r--r--aai-core/src/test/java/org/onap/aai/exceptions/AAIExceptionWithInfoTest.java14
-rw-r--r--aai-core/src/test/java/org/onap/aai/introspection/IntrospectorTestSpec.java34
-rw-r--r--aai-core/src/test/java/org/onap/aai/introspection/JSONStrategyTest.java28
-rw-r--r--aai-core/src/test/java/org/onap/aai/introspection/MoxyEngineTest.java15
-rw-r--r--aai-core/src/test/java/org/onap/aai/introspection/PropertyPredicatesTest.java32
-rw-r--r--aai-core/src/test/java/org/onap/aai/introspection/generator/CreateExampleTest.java39
-rw-r--r--aai-core/src/test/java/org/onap/aai/introspection/sideeffect/DataCopyTest.java180
-rw-r--r--aai-core/src/test/java/org/onap/aai/introspection/sideeffect/DataLinkTest.java334
-rw-r--r--aai-core/src/test/java/org/onap/aai/introspection/sideeffect/PrivateEdgeTest.java124
-rw-r--r--aai-core/src/test/java/org/onap/aai/introspection/tools/CreateUUIDTest.java9
-rw-r--r--aai-core/src/test/java/org/onap/aai/introspection/tools/DefaultFieldsTest.java15
-rw-r--r--aai-core/src/test/java/org/onap/aai/introspection/tools/InjectKeysFromURITest.java31
-rw-r--r--aai-core/src/test/java/org/onap/aai/introspection/tools/IntrospectorValidatorTest.java56
-rw-r--r--aai-core/src/test/java/org/onap/aai/introspection/tools/RemoveNonVisiblePropertyTest.java12
-rw-r--r--aai-core/src/test/java/org/onap/aai/introspection/validation/IntrospectorValidationTest.java17
-rw-r--r--aai-core/src/test/java/org/onap/aai/logging/CustomLogPatternLayoutTest.java15
-rw-r--r--aai-core/src/test/java/org/onap/aai/logging/DME2RestFlagTest.java33
-rw-r--r--aai-core/src/test/java/org/onap/aai/logging/EcompErrorCategoryTest.java8
-rw-r--r--aai-core/src/test/java/org/onap/aai/logging/EcompResponseCodeTest.java8
-rw-r--r--aai-core/src/test/java/org/onap/aai/logging/EcompResponseDescriptionTest.java10
-rw-r--r--aai-core/src/test/java/org/onap/aai/logging/EelfClassOfCallerTest.java28
-rw-r--r--aai-core/src/test/java/org/onap/aai/logging/ErrorObjectTest.java127
-rw-r--r--aai-core/src/test/java/org/onap/aai/logging/LoggingContextTest.java28
-rw-r--r--aai-core/src/test/java/org/onap/aai/parsers/query/GraphTraversalTest.java683
-rw-r--r--aai-core/src/test/java/org/onap/aai/parsers/query/LegacyQueryTest.java111
-rw-r--r--aai-core/src/test/java/org/onap/aai/parsers/query/RelationshipGremlinQueryTest.java482
-rw-r--r--aai-core/src/test/java/org/onap/aai/parsers/query/RelationshipQueryTest.java188
-rw-r--r--aai-core/src/test/java/org/onap/aai/parsers/query/UniqueRelationshipQueryTest.java163
-rw-r--r--aai-core/src/test/java/org/onap/aai/parsers/query/UniqueURIQueryTest.java64
-rw-r--r--aai-core/src/test/java/org/onap/aai/parsers/relationship/RelationshipToURITest.java110
-rw-r--r--aai-core/src/test/java/org/onap/aai/parsers/uri/URIParserTest.java64
-rw-r--r--aai-core/src/test/java/org/onap/aai/parsers/uri/URIToDBKeyTest.java114
-rw-r--r--aai-core/src/test/java/org/onap/aai/parsers/uri/URIToExtensionInformationTest.java55
-rw-r--r--aai-core/src/test/java/org/onap/aai/parsers/uri/URIToObjectTest.java93
-rw-r--r--aai-core/src/test/java/org/onap/aai/parsers/uri/URIToRelationshipObjectTest.java105
-rw-r--r--aai-core/src/test/java/org/onap/aai/query/builder/ExcludeQueryTest.java111
-rw-r--r--aai-core/src/test/java/org/onap/aai/query/builder/GremlinTraversalTest.java13
-rw-r--r--aai-core/src/test/java/org/onap/aai/query/builder/QueryBuilderTestAbstraction.java263
-rw-r--r--aai-core/src/test/java/org/onap/aai/query/builder/QueryTestsConfigTranslator.java8
-rw-r--r--aai-core/src/test/java/org/onap/aai/query/builder/SimplePathTest.java64
-rw-r--r--aai-core/src/test/java/org/onap/aai/query/builder/TraversalQueryTest.java177
-rw-r--r--aai-core/src/test/java/org/onap/aai/query/builder/TraversalURIOptimizedQueryTest.java3
-rw-r--r--aai-core/src/test/java/org/onap/aai/query/builder/UntilTest.java50
-rw-r--r--aai-core/src/test/java/org/onap/aai/query/builder/optimization/AbstractGraphTraversalBuilderOptmizationTest.java85
-rw-r--r--aai-core/src/test/java/org/onap/aai/query/builder/optimization/AbstractGraphTraversalBuilderTestQueryiesToRun.java54
-rw-r--r--aai-core/src/test/java/org/onap/aai/query/builder/optimization/OptimizeEnum.java3
-rw-r--r--aai-core/src/test/java/org/onap/aai/query/builder/optimization/tests/AOneTenantOneVserversPerTenantTest.java3
-rw-r--r--aai-core/src/test/java/org/onap/aai/query/builder/optimization/tests/BTenTenantTenVserversPerTenantTest.java3
-rw-r--r--aai-core/src/test/java/org/onap/aai/rest/CloudRegionTest.java29
-rw-r--r--aai-core/src/test/java/org/onap/aai/rest/EdgeNotValidAnymoreTest.java47
-rw-r--r--aai-core/src/test/java/org/onap/aai/rest/EntitlementTest.java27
-rw-r--r--aai-core/src/test/java/org/onap/aai/rest/GenericVnfLInterfaceTest.java27
-rw-r--r--aai-core/src/test/java/org/onap/aai/rest/HPACapabilityTest.java27
-rw-r--r--aai-core/src/test/java/org/onap/aai/rest/ModelElementTest.java30
-rw-r--r--aai-core/src/test/java/org/onap/aai/rest/PrivateEdgeIntegrationOldClientTest.java51
-rw-r--r--aai-core/src/test/java/org/onap/aai/rest/PrivateEdgeIntegrationTest.java267
-rw-r--r--aai-core/src/test/java/org/onap/aai/rest/PserverDuplicateTest.java92
-rw-r--r--aai-core/src/test/java/org/onap/aai/rest/PserverTest.java37
-rw-r--r--aai-core/src/test/java/org/onap/aai/rest/RestHandlerTest.java11
-rw-r--r--aai-core/src/test/java/org/onap/aai/rest/TenantTest.java36
-rw-r--r--aai-core/src/test/java/org/onap/aai/rest/VipAddressListTest.java30
-rw-r--r--aai-core/src/test/java/org/onap/aai/rest/db/HttpEntryTest.java260
-rw-r--r--aai-core/src/test/java/org/onap/aai/serialization/db/AAICoreFakeEdgesConfigTranslator.java41
-rw-r--r--aai-core/src/test/java/org/onap/aai/serialization/db/AAICorePrivateEdgeTestConfigTranslator.java45
-rw-r--r--aai-core/src/test/java/org/onap/aai/serialization/db/DbAliasTest.java207
-rw-r--r--aai-core/src/test/java/org/onap/aai/serialization/db/DbSerializerTest.java1396
-rw-r--r--aai-core/src/test/java/org/onap/aai/serialization/db/DbSerializer_needsFakeRulesTest.java1262
-rw-r--r--aai-core/src/test/java/org/onap/aai/serialization/db/EdgePropertyMapTest.java29
-rw-r--r--aai-core/src/test/java/org/onap/aai/serialization/db/EdgeRulesTest.java90
-rw-r--r--aai-core/src/test/java/org/onap/aai/serialization/db/EdgeSerializerTest.java134
-rw-r--r--aai-core/src/test/java/org/onap/aai/serialization/engines/query/GraphTraversalQueryEngineTest.java575
-rw-r--r--aai-core/src/test/java/org/onap/aai/serialization/engines/query/GraphTraversalQueryEngine_needsFakeEdgeRulesTest.java76
-rw-r--r--aai-core/src/test/java/org/onap/aai/serialization/queryformats/ConsoleTest.java99
-rw-r--r--aai-core/src/test/java/org/onap/aai/serialization/queryformats/CountQuerySupportTest.java227
-rw-r--r--aai-core/src/test/java/org/onap/aai/serialization/queryformats/FormatTest.java33
-rw-r--r--aai-core/src/test/java/org/onap/aai/serialization/queryformats/GraphSONTest.java923
-rw-r--r--aai-core/src/test/java/org/onap/aai/serialization/queryformats/MultiFormatTest.java241
-rw-r--r--aai-core/src/test/java/org/onap/aai/serialization/queryformats/QueryFormatTestHelper.java74
-rw-r--r--aai-core/src/test/java/org/onap/aai/serialization/queryformats/RawFormatTest.java183
-rw-r--r--aai-core/src/test/java/org/onap/aai/serialization/queryformats/ResourceFormatTest.java169
-rw-r--r--aai-core/src/test/java/org/onap/aai/serialization/queryformats/ResourceWithSoTTest.java51
-rw-r--r--aai-core/src/test/java/org/onap/aai/serialization/queryformats/SimpleFormatTest.java220
-rw-r--r--aai-core/src/test/java/org/onap/aai/serialization/queryformats/utils/QueryParamInjectorTest.java51
-rw-r--r--aai-core/src/test/java/org/onap/aai/serialization/queryformats/utils/UrlBuilderTest.java127
-rw-r--r--aai-core/src/test/java/org/onap/aai/serialization/tinkerpop/TreeBackedVertexTest.java236
-rw-r--r--aai-core/src/test/java/org/onap/aai/testutils/TestUtilConfigTranslatorforBusiness.java72
-rw-r--r--aai-core/src/test/java/org/onap/aai/testutils/TestUtilConfigTranslatorforDataLink.java54
-rw-r--r--aai-core/src/test/java/org/onap/aai/testutils/TestUtilConfigTranslatorforEdges.java76
-rw-r--r--aai-core/src/test/java/org/onap/aai/util/AAIConfigCommandLinePropGetterTest.java128
-rw-r--r--aai-core/src/test/java/org/onap/aai/util/AAIConfigTest.java175
-rw-r--r--aai-core/src/test/java/org/onap/aai/util/AAIUtilsTest.java72
-rw-r--r--aai-core/src/test/java/org/onap/aai/util/FileWatcherTest.java85
-rw-r--r--aai-core/src/test/java/org/onap/aai/util/FormatDateTest.java77
-rw-r--r--aai-core/src/test/java/org/onap/aai/util/JettyObfuscationConversionCommandLineUtilTest.java21
-rw-r--r--aai-core/src/test/java/org/onap/aai/util/KeyValueListTest.java4
-rw-r--r--aai-core/src/test/java/org/onap/aai/util/MapperUtilTest.java39
-rw-r--r--aai-core/src/test/java/org/onap/aai/util/PojoUtilsTest.java564
-rw-r--r--aai-core/src/test/java/org/onap/aai/util/RestURLEncoderTest.java49
-rw-r--r--aai-core/src/test/java/org/onap/aai/util/StoreNotificationEventTest.java360
342 files changed, 26873 insertions, 26828 deletions
diff --git a/aai-core/src/main/java/org/onap/aai/audit/ListEndpoints.java b/aai-core/src/main/java/org/onap/aai/audit/ListEndpoints.java
index fc383581..aed61e7a 100644
--- a/aai-core/src/main/java/org/onap/aai/audit/ListEndpoints.java
+++ b/aai-core/src/main/java/org/onap/aai/audit/ListEndpoints.java
@@ -19,8 +19,13 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.audit;
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
+import com.google.common.base.CaseFormat;
+
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
@@ -38,13 +43,9 @@ import org.onap.aai.introspection.Introspector;
import org.onap.aai.introspection.Loader;
import org.onap.aai.introspection.LoaderFactory;
import org.onap.aai.introspection.ModelType;
-import org.onap.aai.setup.SchemaVersion;
import org.onap.aai.introspection.exceptions.AAIUnknownObjectException;
import org.onap.aai.logging.LogFormatTools;
-
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
-import com.google.common.base.CaseFormat;
+import org.onap.aai.setup.SchemaVersion;
import org.onap.aai.setup.SchemaVersions;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
@@ -53,270 +54,264 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext
*/
public class ListEndpoints {
- private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(ListEndpoints.class);
-
- private final String start = "inventory";
- private final String[] blacklist = { "search", "aai-internal" };
-
- private List<String> endpoints = new ArrayList<>();
- private Map<String, String> endpointToLogicalName = new HashMap<String, String>();
-
- /**
- * The main method.
- *
- * @param args the arguments
- */
- public static void main(String[] args) {
-
- AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
- "org.onap.aai.config",
- "org.onap.aai.setup"
- );
-
- String schemaUriBasePath = context.getEnvironment().getProperty("schema.uri.base.path");
-
- if(schemaUriBasePath == null){
- String errorMsg = "Unable to find the property schema.uri.base.path,"
- +" please check if specified in system property or in schema-ingest.properties";
- System.err.println(errorMsg);
- LOGGER.error(errorMsg);
- }
-
- SchemaVersions schemaVersions = context.getBean(SchemaVersions.class);
- ListEndpoints endPoints = new ListEndpoints(schemaUriBasePath, schemaVersions.getDefaultVersion());
-
- LOGGER.info(endPoints.toString("relationship-list"));
- }
-
- /**
- * Instantiates a new list endpoints.
- *
- * @param version the version
- */
- public ListEndpoints(String basePath, SchemaVersion version) {
-
- Loader loader = SpringContextAware.getBean(LoaderFactory.class).createLoaderForVersion(ModelType.MOXY, version);
-
- try {
- final Introspector start = loader.introspectorFromName(this.start);
- Set<String> startMap = new HashSet<>();
- beginAudit(start, basePath + "/" + version, startMap);
- } catch (AAIUnknownObjectException e) {
- throw new RuntimeException("Failed to find object " + this.start + ", cannot run ListEndpoints audit");
- }
- }
-
- /**
- * Begin audit.
- *
- * @param obj the obj
- * @param uri the uri
- */
- private void beginAudit(Introspector obj, String uri, Set<String> visited) {
-
- String currentUri = "";
-
- if (!obj.getDbName().equals("inventory")) {
- currentUri = uri + obj.getGenericURI();
- } else {
- currentUri = uri;
- }
- if (obj.getName().equals("relationship-data") || obj.getName().equals("related-to-property")) {
- return;
- }
- if (!obj.isContainer()) {
- endpoints.add(currentUri);
- }
-
- String dbName = obj.getDbName();
-
- populateLogicalName(obj, uri, currentUri);
-
- Set<String> properties = obj.getProperties();
- Set<String> props = new LinkedHashSet<>(properties);
- if (obj.isContainer()) {
- for (String key : visited) {
- if (props.remove(key)) {
- try {
- endpoints.add(currentUri + obj.getLoader().introspectorFromName(key).getGenericURI());
- } catch (AAIUnknownObjectException e) {
- LOGGER.warn("Skipping endpoint for " + key + " (Unknown object) " + LogFormatTools.getStackTop(e));
- }
- }
- }
- }
-
- outer: for (String propName : props) {
-
- for (String item : blacklist) {
- if (propName.equals(item)) {
- continue outer;
- }
- }
- if (obj.isListType(propName)) {
- if (obj.isComplexGenericType(propName)) {
- try {
- final Introspector nestedObj = obj.newIntrospectorInstanceOfNestedProperty(propName);
- Set<String> newVisited = new HashSet<>();
- newVisited.addAll(visited);
- newVisited.add(nestedObj.getDbName());
- beginAudit(
- nestedObj,
- currentUri,
- newVisited
- );
- } catch (AAIUnknownObjectException e) {
- LOGGER.warn("Skipping nested endpoint for " + propName + " (Unknown Object) " + LogFormatTools.getStackTop(e));
- }
- }
- } else if (obj.isComplexType(propName)) {
- try {
- final Introspector nestedObj = obj.newIntrospectorInstanceOfProperty(propName);
- Set<String> newVisited = new HashSet<>();
- newVisited.addAll(visited);
- newVisited.add(nestedObj.getDbName());
- beginAudit(nestedObj,
- currentUri,
- visited
- );
- } catch (AAIUnknownObjectException e) {
- LOGGER.warn("Skipping nested enpoint for " + propName + " (Unknown Object) "+ LogFormatTools.getStackTop(e));
- }
- }
- }
-
- }
-
- /**
- * Populate logical name.
- *
- * @param obj the obj
- * @param uri the uri
- * @param currentUri the current uri
- */
- private void populateLogicalName(Introspector obj, String uri, String currentUri) {
-
- if (obj.getDbName().equals("inventory") || currentUri.split("/").length <= 4 || currentUri.endsWith("relationship-list")) {
- return;
- }
-
- if (uri.endsWith("/relationship-list")) {
- uri = uri.substring(0, uri.lastIndexOf("/"));
- }
-
- String logicalName = "";
- String keys = "";
-
-
- if (!obj.getAllKeys().isEmpty()) {
-
- Pattern p = Pattern.compile("/\\{[\\w\\d\\-]+\\}/\\{[\\w\\d\\-]+\\}+$");
- Matcher m = p.matcher(currentUri);
-
- if (m.find()) {
- keys = StringUtils.join(obj.getAllKeys(), "-and-");
- } else {
- keys = StringUtils.join(obj.getAllKeys(), "-or-");
- }
- keys = CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, keys);
- if (!keys.isEmpty()) {
- keys = "With" + keys;
- }
- }
-
- logicalName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, obj.getDbName()) + keys;
-
- if (endpointToLogicalName.containsKey(uri) && uri.endsWith("}")) {
- logicalName = logicalName + "From" + endpointToLogicalName.get(uri);
- } else if (endpointToLogicalName.containsKey(uri.substring(0, uri.lastIndexOf("/")))) {
- logicalName = logicalName + "From" + endpointToLogicalName.get(uri.substring(0, uri.lastIndexOf("/")));
- }
-
- endpointToLogicalName.put(currentUri, logicalName);
-
- }
-
- /**
- * Gets the logical names.
- *
- * @return the logical names
- */
- public Map<String, String> getLogicalNames() {
-
- return endpointToLogicalName;
-
- }
-
- /**
- * Gets the endpoints.
- *
- * @return the endpoints
- */
- public List<String> getEndpoints() {
-
- return this.getEndpoints("");
-
- }
-
- /**
- * Gets the endpoints.
- *
- * @param filterOut the filter out
- * @return the endpoints
- */
- public List<String> getEndpoints(String filterOut) {
- List<String> result = new ArrayList<>();
- Pattern p = null;
- Matcher m = null;
- if (!filterOut.equals("")) {
- p = Pattern.compile(filterOut);
- m = null;
- }
- for (String s : endpoints) {
- if (p != null) {
- m = p.matcher(s);
- if (m.find()) {
- continue;
- }
- }
-
- result.add(s);
- }
-
- return result;
-
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public String toString() {
- StringBuilder sb = new StringBuilder();
- for (String s : endpoints) {
- sb.append(s + "\n");
- }
- return sb.toString();
-
- }
-
- /**
- * To string.
- *
- * @param filterOut the filter out
- * @return the string
- */
- public String toString(String filterOut) {
- StringBuilder sb = new StringBuilder();
- Pattern p = Pattern.compile(filterOut);
- Matcher m = null;
- for (String s : endpoints) {
- m = p.matcher(s);
- if (!m.find()) {
- sb.append(s + "\n");
- }
- }
- return sb.toString();
- }
+ private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(ListEndpoints.class);
+
+ private final String start = "inventory";
+ private final String[] blacklist = {"search", "aai-internal"};
+
+ private List<String> endpoints = new ArrayList<>();
+ private Map<String, String> endpointToLogicalName = new HashMap<String, String>();
+
+ /**
+ * The main method.
+ *
+ * @param args the arguments
+ */
+ public static void main(String[] args) {
+
+ AnnotationConfigApplicationContext context =
+ new AnnotationConfigApplicationContext("org.onap.aai.config", "org.onap.aai.setup");
+
+ String schemaUriBasePath = context.getEnvironment().getProperty("schema.uri.base.path");
+
+ if (schemaUriBasePath == null) {
+ String errorMsg = "Unable to find the property schema.uri.base.path,"
+ + " please check if specified in system property or in schema-ingest.properties";
+ System.err.println(errorMsg);
+ LOGGER.error(errorMsg);
+ }
+
+ SchemaVersions schemaVersions = context.getBean(SchemaVersions.class);
+ ListEndpoints endPoints = new ListEndpoints(schemaUriBasePath, schemaVersions.getDefaultVersion());
+
+ LOGGER.info(endPoints.toString("relationship-list"));
+ }
+
+ /**
+ * Instantiates a new list endpoints.
+ *
+ * @param version the version
+ */
+ public ListEndpoints(String basePath, SchemaVersion version) {
+
+ Loader loader = SpringContextAware.getBean(LoaderFactory.class).createLoaderForVersion(ModelType.MOXY, version);
+
+ try {
+ final Introspector start = loader.introspectorFromName(this.start);
+ Set<String> startMap = new HashSet<>();
+ beginAudit(start, basePath + "/" + version, startMap);
+ } catch (AAIUnknownObjectException e) {
+ throw new RuntimeException("Failed to find object " + this.start + ", cannot run ListEndpoints audit");
+ }
+ }
+
+ /**
+ * Begin audit.
+ *
+ * @param obj the obj
+ * @param uri the uri
+ */
+ private void beginAudit(Introspector obj, String uri, Set<String> visited) {
+
+ String currentUri = "";
+
+ if (!obj.getDbName().equals("inventory")) {
+ currentUri = uri + obj.getGenericURI();
+ } else {
+ currentUri = uri;
+ }
+ if (obj.getName().equals("relationship-data") || obj.getName().equals("related-to-property")) {
+ return;
+ }
+ if (!obj.isContainer()) {
+ endpoints.add(currentUri);
+ }
+
+ String dbName = obj.getDbName();
+
+ populateLogicalName(obj, uri, currentUri);
+
+ Set<String> properties = obj.getProperties();
+ Set<String> props = new LinkedHashSet<>(properties);
+ if (obj.isContainer()) {
+ for (String key : visited) {
+ if (props.remove(key)) {
+ try {
+ endpoints.add(currentUri + obj.getLoader().introspectorFromName(key).getGenericURI());
+ } catch (AAIUnknownObjectException e) {
+ LOGGER.warn(
+ "Skipping endpoint for " + key + " (Unknown object) " + LogFormatTools.getStackTop(e));
+ }
+ }
+ }
+ }
+
+ outer: for (String propName : props) {
+
+ for (String item : blacklist) {
+ if (propName.equals(item)) {
+ continue outer;
+ }
+ }
+ if (obj.isListType(propName)) {
+ if (obj.isComplexGenericType(propName)) {
+ try {
+ final Introspector nestedObj = obj.newIntrospectorInstanceOfNestedProperty(propName);
+ Set<String> newVisited = new HashSet<>();
+ newVisited.addAll(visited);
+ newVisited.add(nestedObj.getDbName());
+ beginAudit(nestedObj, currentUri, newVisited);
+ } catch (AAIUnknownObjectException e) {
+ LOGGER.warn("Skipping nested endpoint for " + propName + " (Unknown Object) "
+ + LogFormatTools.getStackTop(e));
+ }
+ }
+ } else if (obj.isComplexType(propName)) {
+ try {
+ final Introspector nestedObj = obj.newIntrospectorInstanceOfProperty(propName);
+ Set<String> newVisited = new HashSet<>();
+ newVisited.addAll(visited);
+ newVisited.add(nestedObj.getDbName());
+ beginAudit(nestedObj, currentUri, visited);
+ } catch (AAIUnknownObjectException e) {
+ LOGGER.warn("Skipping nested enpoint for " + propName + " (Unknown Object) "
+ + LogFormatTools.getStackTop(e));
+ }
+ }
+ }
+
+ }
+
+ /**
+ * Populate logical name.
+ *
+ * @param obj the obj
+ * @param uri the uri
+ * @param currentUri the current uri
+ */
+ private void populateLogicalName(Introspector obj, String uri, String currentUri) {
+
+ if (obj.getDbName().equals("inventory") || currentUri.split("/").length <= 4
+ || currentUri.endsWith("relationship-list")) {
+ return;
+ }
+
+ if (uri.endsWith("/relationship-list")) {
+ uri = uri.substring(0, uri.lastIndexOf("/"));
+ }
+
+ String logicalName = "";
+ String keys = "";
+
+ if (!obj.getAllKeys().isEmpty()) {
+
+ Pattern p = Pattern.compile("/\\{[\\w\\d\\-]+\\}/\\{[\\w\\d\\-]+\\}+$");
+ Matcher m = p.matcher(currentUri);
+
+ if (m.find()) {
+ keys = StringUtils.join(obj.getAllKeys(), "-and-");
+ } else {
+ keys = StringUtils.join(obj.getAllKeys(), "-or-");
+ }
+ keys = CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, keys);
+ if (!keys.isEmpty()) {
+ keys = "With" + keys;
+ }
+ }
+
+ logicalName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, obj.getDbName()) + keys;
+
+ if (endpointToLogicalName.containsKey(uri) && uri.endsWith("}")) {
+ logicalName = logicalName + "From" + endpointToLogicalName.get(uri);
+ } else if (endpointToLogicalName.containsKey(uri.substring(0, uri.lastIndexOf("/")))) {
+ logicalName = logicalName + "From" + endpointToLogicalName.get(uri.substring(0, uri.lastIndexOf("/")));
+ }
+
+ endpointToLogicalName.put(currentUri, logicalName);
+
+ }
+
+ /**
+ * Gets the logical names.
+ *
+ * @return the logical names
+ */
+ public Map<String, String> getLogicalNames() {
+
+ return endpointToLogicalName;
+
+ }
+
+ /**
+ * Gets the endpoints.
+ *
+ * @return the endpoints
+ */
+ public List<String> getEndpoints() {
+
+ return this.getEndpoints("");
+
+ }
+
+ /**
+ * Gets the endpoints.
+ *
+ * @param filterOut the filter out
+ * @return the endpoints
+ */
+ public List<String> getEndpoints(String filterOut) {
+ List<String> result = new ArrayList<>();
+ Pattern p = null;
+ Matcher m = null;
+ if (!filterOut.equals("")) {
+ p = Pattern.compile(filterOut);
+ m = null;
+ }
+ for (String s : endpoints) {
+ if (p != null) {
+ m = p.matcher(s);
+ if (m.find()) {
+ continue;
+ }
+ }
+
+ result.add(s);
+ }
+
+ return result;
+
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public String toString() {
+ StringBuilder sb = new StringBuilder();
+ for (String s : endpoints) {
+ sb.append(s + "\n");
+ }
+ return sb.toString();
+
+ }
+
+ /**
+ * To string.
+ *
+ * @param filterOut the filter out
+ * @return the string
+ */
+ public String toString(String filterOut) {
+ StringBuilder sb = new StringBuilder();
+ Pattern p = Pattern.compile(filterOut);
+ Matcher m = null;
+ for (String s : endpoints) {
+ m = p.matcher(s);
+ if (!m.find()) {
+ sb.append(s + "\n");
+ }
+ }
+ return sb.toString();
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/auth/AAIAuthCore.java b/aai-core/src/main/java/org/onap/aai/auth/AAIAuthCore.java
index 6673c08a..cde2faa3 100644
--- a/aai-core/src/main/java/org/onap/aai/auth/AAIAuthCore.java
+++ b/aai-core/src/main/java/org/onap/aai/auth/AAIAuthCore.java
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.auth;
import com.att.eelf.configuration.EELFLogger;
@@ -26,15 +27,6 @@ import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
-import org.eclipse.jetty.util.security.Password;
-import org.eclipse.persistence.internal.oxm.conversion.Base64;
-import org.onap.aai.auth.exceptions.AAIUnrecognizedFunctionException;
-import org.onap.aai.logging.ErrorLogHelper;
-import org.onap.aai.logging.LoggingContext;
-import org.onap.aai.logging.LoggingContext.StatusCode;
-import org.onap.aai.util.AAIConfig;
-import org.onap.aai.util.AAIConstants;
-import org.onap.aai.util.FileWatcher;
import java.io.File;
import java.io.FileNotFoundException;
@@ -46,311 +38,335 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
+import org.eclipse.jetty.util.security.Password;
+import org.eclipse.persistence.internal.oxm.conversion.Base64;
+import org.onap.aai.auth.exceptions.AAIUnrecognizedFunctionException;
+import org.onap.aai.logging.ErrorLogHelper;
+import org.onap.aai.logging.LoggingContext;
+import org.onap.aai.logging.LoggingContext.StatusCode;
+import org.onap.aai.util.AAIConfig;
+import org.onap.aai.util.AAIConstants;
+import org.onap.aai.util.FileWatcher;
+
/**
* The Class AAIAuthCore.
*/
public final class AAIAuthCore {
- private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(AAIAuthCore.class);
-
- private static final String ERROR_CODE_AAI_4001 = "AAI_4001";
-
- private String globalAuthFileName = AAIConstants.AAI_AUTH_CONFIG_FILENAME;
-
- private final Pattern AUTH_POLICY_PATTERN;
- private final Set<String> validFunctions = new HashSet<>();
- private Map<String, AAIUser> users;
- private boolean timerSet = false;
- private Timer timer = null;
-
- private String basePath;
- /**
- * Instantiates a new AAI auth core.
- */
- public AAIAuthCore(String basePath) {
- this.basePath = basePath;
- AUTH_POLICY_PATTERN = Pattern.compile("^" + this.basePath +"/v\\d+/([\\w\\-]*)");
- init();
- }
-
- /**
- * Inits the.
- */
- private synchronized void init() {
-
- LOGGER.debug("Initializing Auth Policy Config");
-
- reloadUsers();
-
- /*
- * this timer code is setting up a recurring task that checks if the
- * auth config file has been updated and reloads the users if so to get
- * the most up to date info (that update check logic is within
- * FileWatcher)
- *
- * the timing this method uses is coarser than the frequency of requests
- * AI&I gets so we're looking at better ways of doing this (TODO)
- */
- TimerTask task = new FileWatcher(new File(globalAuthFileName)) {
- @Override
- protected void onChange(File file) {
- reloadUsers();
- }
- };
-
- if (!timerSet) {
- timerSet = true;
- timer = new Timer();
-
- // repeat the check every second
- timer.schedule(task, new Date(), 10000);
- }
- LOGGER.debug("Static Initializiation complete");
- }
-
- /**
- * Cleanup.
- */
- // just ends the auth config file update checking timer
- public void cleanup() {
- timer.cancel();
- }
-
- /**
- * Reload users.
- */
- /*
- * this essentially takes the data file, which is organized role-first with
- * users under each role and converts it to data organized user-first with
- * each user containing their role with its associated allowed functions
- * this data stored in the class field users
- */
- private synchronized void reloadUsers() {
-
- Map<String, AAIUser> tempUsers = new HashMap<>();
-
- try {
- LOGGER.debug("Reading from " + globalAuthFileName);
- String authFile = new String(Files.readAllBytes(Paths.get(globalAuthFileName)));
-
- JsonParser parser = new JsonParser();
- JsonObject authObject = parser.parse(authFile).getAsJsonObject();
- if (authObject.has("roles")) {
- JsonArray roles = authObject.getAsJsonArray("roles");
- for (JsonElement role : roles) {
- if (role.isJsonObject()) {
- JsonObject roleObject = role.getAsJsonObject();
- String roleName = roleObject.get("name").getAsString();
- Map<String, Boolean> usrs = this.getUsernamesFromRole(roleObject);
- List<String> aaiFunctions = this.getAAIFunctions(roleObject);
-
- usrs.forEach((key, value) -> {
- final AAIUser au = tempUsers.getOrDefault(key, new AAIUser(key, value));
- au.addRole(roleName);
- aaiFunctions.forEach(f -> {
- List<String> httpMethods = this.getRoleHttpMethods(f, roleObject);
- httpMethods.forEach(hm -> au.setUserAccess(f, hm));
- this.validFunctions.add(f);
- });
-
- tempUsers.put(key, au);
-
- });
- }
- }
- if (!tempUsers.isEmpty()) {
- users = tempUsers;
- }
- }
- } catch (FileNotFoundException e) {
- ErrorLogHelper.logError(ERROR_CODE_AAI_4001, globalAuthFileName + ". Exception: " + e);
- } catch (JsonProcessingException e) {
- ErrorLogHelper.logError(ERROR_CODE_AAI_4001, globalAuthFileName + ". Not valid JSON: " + e);
- } catch (Exception e) {
- ErrorLogHelper.logError(ERROR_CODE_AAI_4001, globalAuthFileName + ". Exception caught: " + e);
- }
- }
-
- private List<String> getRoleHttpMethods(String aaiFunctionName, JsonObject roleObject) {
- List<String> httpMethods = new ArrayList<>();
-
- JsonArray ja = roleObject.getAsJsonArray("functions");
- for (JsonElement je : ja) {
- if (je.isJsonObject() && je.getAsJsonObject().has("name") && je.getAsJsonObject().get("name").getAsString().equals(aaiFunctionName)) {
- JsonArray jaMeth = je.getAsJsonObject().getAsJsonArray("methods");
- for (JsonElement jeMeth : jaMeth) {
- if (jeMeth.isJsonObject() && jeMeth.getAsJsonObject().has("name")) {
- httpMethods.add(jeMeth.getAsJsonObject().get("name").getAsString());
- }
- }
- }
- }
-
- return httpMethods;
- }
-
- private List<String> getAAIFunctions(JsonObject roleObject) {
- List<String> aaiFunctions = new ArrayList<>();
-
- JsonArray ja = roleObject.getAsJsonArray("functions");
- for (JsonElement je : ja) {
- if (je.isJsonObject() && je.getAsJsonObject().has("name")) {
- aaiFunctions.add(je.getAsJsonObject().get("name").getAsString());
- }
- }
-
- return aaiFunctions;
- }
-
- private Map<String, Boolean> getUsernamesFromRole(JsonObject roleObject) throws UnsupportedEncodingException {
- Map<String, Boolean> usernames = new HashMap<>();
-
- JsonArray uja = roleObject.getAsJsonArray("users");
- for (JsonElement je : uja) {
- if (je.isJsonObject()) {
- if (je.getAsJsonObject().has("username")) {
- if (je.getAsJsonObject().has("is-wildcard-id")) {
- usernames.put(je.getAsJsonObject().get("username").getAsString().toLowerCase(), je.getAsJsonObject().get("is-wildcard-id").getAsBoolean());
- } else {
- usernames.put(je.getAsJsonObject().get("username").getAsString().toLowerCase(), false);
- }
- } else if (je.getAsJsonObject().has("user")) {
- String auth = je.getAsJsonObject().get("user").getAsString() + ":" + Password.deobfuscate(je.getAsJsonObject().get("pass").getAsString());
- String authorizationCode = new String(Base64.base64Encode(auth.getBytes("utf-8")));
- usernames.put(authorizationCode, false);
- }
- }
- }
-
- return usernames;
- }
-
- public String getAuthPolicyFunctName(String uri) {
- String authPolicyFunctionName = "";
- if (uri.startsWith(basePath + "/search")) {
- authPolicyFunctionName = "search";
+ private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(AAIAuthCore.class);
+
+ private static final String ERROR_CODE_AAI_4001 = "AAI_4001";
+
+ private String globalAuthFileName = AAIConstants.AAI_AUTH_CONFIG_FILENAME;
+
+ private final Pattern AUTH_POLICY_PATTERN;
+ private final Set<String> validFunctions = new HashSet<>();
+ private Map<String, AAIUser> users;
+ private boolean timerSet = false;
+ private Timer timer = null;
+
+ private String basePath;
+
+ /**
+ * Instantiates a new AAI auth core.
+ */
+ public AAIAuthCore(String basePath) {
+ this.basePath = basePath;
+ AUTH_POLICY_PATTERN = Pattern.compile("^" + this.basePath + "/v\\d+/([\\w\\-]*)");
+ init();
+ }
+
+ /**
+ * Inits the.
+ */
+ private synchronized void init() {
+
+ LOGGER.debug("Initializing Auth Policy Config");
+
+ reloadUsers();
+
+ /*
+ * this timer code is setting up a recurring task that checks if the
+ * auth config file has been updated and reloads the users if so to get
+ * the most up to date info (that update check logic is within
+ * FileWatcher)
+ *
+ * the timing this method uses is coarser than the frequency of requests
+ * AI&I gets so we're looking at better ways of doing this (TODO)
+ */
+ TimerTask task = new FileWatcher(new File(globalAuthFileName)) {
+ @Override
+ protected void onChange(File file) {
+ reloadUsers();
+ }
+ };
+
+ if (!timerSet) {
+ timerSet = true;
+ timer = new Timer();
+
+ // repeat the check every second
+ timer.schedule(task, new Date(), 10000);
+ }
+ LOGGER.debug("Static Initializiation complete");
+ }
+
+ /**
+ * Cleanup.
+ */
+ // just ends the auth config file update checking timer
+ public void cleanup() {
+ timer.cancel();
+ }
+
+ /**
+ * Reload users.
+ */
+ /*
+ * this essentially takes the data file, which is organized role-first with
+ * users under each role and converts it to data organized user-first with
+ * each user containing their role with its associated allowed functions
+ * this data stored in the class field users
+ */
+ private synchronized void reloadUsers() {
+
+ Map<String, AAIUser> tempUsers = new HashMap<>();
+
+ try {
+ LOGGER.debug("Reading from " + globalAuthFileName);
+ String authFile = new String(Files.readAllBytes(Paths.get(globalAuthFileName)));
+
+ JsonParser parser = new JsonParser();
+ JsonObject authObject = parser.parse(authFile).getAsJsonObject();
+ if (authObject.has("roles")) {
+ JsonArray roles = authObject.getAsJsonArray("roles");
+ for (JsonElement role : roles) {
+ if (role.isJsonObject()) {
+ JsonObject roleObject = role.getAsJsonObject();
+ String roleName = roleObject.get("name").getAsString();
+ Map<String, Boolean> usrs = this.getUsernamesFromRole(roleObject);
+ List<String> aaiFunctions = this.getAAIFunctions(roleObject);
+
+ usrs.forEach((key, value) -> {
+ final AAIUser au = tempUsers.getOrDefault(key, new AAIUser(key, value));
+ au.addRole(roleName);
+ aaiFunctions.forEach(f -> {
+ List<String> httpMethods = this.getRoleHttpMethods(f, roleObject);
+ httpMethods.forEach(hm -> au.setUserAccess(f, hm));
+ this.validFunctions.add(f);
+ });
+
+ tempUsers.put(key, au);
+
+ });
+ }
+ }
+ if (!tempUsers.isEmpty()) {
+ users = tempUsers;
+ }
+ }
+ } catch (FileNotFoundException e) {
+ ErrorLogHelper.logError(ERROR_CODE_AAI_4001, globalAuthFileName + ". Exception: " + e);
+ } catch (JsonProcessingException e) {
+ ErrorLogHelper.logError(ERROR_CODE_AAI_4001, globalAuthFileName + ". Not valid JSON: " + e);
+ } catch (Exception e) {
+ ErrorLogHelper.logError(ERROR_CODE_AAI_4001, globalAuthFileName + ". Exception caught: " + e);
+ }
+ }
+
+ private List<String> getRoleHttpMethods(String aaiFunctionName, JsonObject roleObject) {
+ List<String> httpMethods = new ArrayList<>();
+
+ JsonArray ja = roleObject.getAsJsonArray("functions");
+ for (JsonElement je : ja) {
+ if (je.isJsonObject() && je.getAsJsonObject().has("name")
+ && je.getAsJsonObject().get("name").getAsString().equals(aaiFunctionName)) {
+ JsonArray jaMeth = je.getAsJsonObject().getAsJsonArray("methods");
+ for (JsonElement jeMeth : jaMeth) {
+ if (jeMeth.isJsonObject() && jeMeth.getAsJsonObject().has("name")) {
+ httpMethods.add(jeMeth.getAsJsonObject().get("name").getAsString());
+ }
+ }
+ }
+ }
+
+ return httpMethods;
+ }
+
+ private List<String> getAAIFunctions(JsonObject roleObject) {
+ List<String> aaiFunctions = new ArrayList<>();
+
+ JsonArray ja = roleObject.getAsJsonArray("functions");
+ for (JsonElement je : ja) {
+ if (je.isJsonObject() && je.getAsJsonObject().has("name")) {
+ aaiFunctions.add(je.getAsJsonObject().get("name").getAsString());
+ }
+ }
+
+ return aaiFunctions;
+ }
+
+ private Map<String, Boolean> getUsernamesFromRole(JsonObject roleObject) throws UnsupportedEncodingException {
+ Map<String, Boolean> usernames = new HashMap<>();
+
+ JsonArray uja = roleObject.getAsJsonArray("users");
+ for (JsonElement je : uja) {
+ if (je.isJsonObject()) {
+ if (je.getAsJsonObject().has("username")) {
+ if (je.getAsJsonObject().has("is-wildcard-id")) {
+ usernames.put(je.getAsJsonObject().get("username").getAsString().toLowerCase(),
+ je.getAsJsonObject().get("is-wildcard-id").getAsBoolean());
+ } else {
+ usernames.put(je.getAsJsonObject().get("username").getAsString().toLowerCase(), false);
+ }
+ } else if (je.getAsJsonObject().has("user")) {
+ String auth = je.getAsJsonObject().get("user").getAsString() + ":"
+ + Password.deobfuscate(je.getAsJsonObject().get("pass").getAsString());
+ String authorizationCode = new String(Base64.base64Encode(auth.getBytes("utf-8")));
+ usernames.put(authorizationCode, false);
+ }
+ }
+ }
+
+ return usernames;
+ }
+
+ public String getAuthPolicyFunctName(String uri) {
+ String authPolicyFunctionName = "";
+ if (uri.startsWith(basePath + "/search")) {
+ authPolicyFunctionName = "search";
} else if (uri.startsWith(basePath + "/recents")) {
authPolicyFunctionName = "recents";
- }else if (uri.startsWith(basePath + "/cq2gremlin")) {
+ } else if (uri.startsWith(basePath + "/cq2gremlin")) {
authPolicyFunctionName = "cq2gremlin";
- }else if (uri.startsWith(basePath + "/cq2gremlintest")) {
+ } else if (uri.startsWith(basePath + "/cq2gremlintest")) {
authPolicyFunctionName = "cq2gremlintest";
- }else if (uri.startsWith(basePath + "/util/echo")) {
- authPolicyFunctionName = "util";
- } else if (uri.startsWith(basePath + "/tools")) {
- authPolicyFunctionName = "tools";
- } else {
- Matcher match = AUTH_POLICY_PATTERN.matcher(uri);
- if (match.find()) {
- authPolicyFunctionName = match.group(1);
- }
- }
- return authPolicyFunctionName;
- }
-
- /**
- * for backwards compatibility
- * @param username
- * @param uri
- * @param httpMethod
- * @param haProxyUser
- * @return
- * @throws AAIUnrecognizedFunctionException
- */
- public boolean authorize(String username, String uri, String httpMethod, String haProxyUser) throws AAIUnrecognizedFunctionException {
- return authorize(username, uri, httpMethod, haProxyUser, null);
- }
-
- /**
- *
- * @param username
- * @param uri
- * @param httpMethod
- * @param haProxyUser
- * @param issuer issuer of the cert
- * @return
- * @throws AAIUnrecognizedFunctionException
- */
- public boolean authorize(String username, String uri, String httpMethod, String haProxyUser, String issuer) throws AAIUnrecognizedFunctionException {
- String aaiMethod = this.getAuthPolicyFunctName(uri);
- if (!this.validFunctions.contains(aaiMethod)) {
- throw new AAIUnrecognizedFunctionException(aaiMethod);
- }
- boolean wildcardCheck = isWildcardIssuer(issuer);
- boolean authorized;
- LOGGER.debug("Authorizing the user for the request cert {}, haproxy header {}, aai method {}, httpMethod {}, cert issuer {}",
- username, haProxyUser, aaiMethod, httpMethod, issuer);
- Optional<AAIUser> oau = this.getUser(username, wildcardCheck);
- if (oau.isPresent()) {
- AAIUser au = oau.get();
- if (au.hasRole("HAProxy")) {
- LOGGER.debug("User has HAProxy role");
- if ("GET".equalsIgnoreCase(httpMethod) && "util".equalsIgnoreCase(aaiMethod) && haProxyUser.isEmpty()) {
- LOGGER.debug("Authorized user has HAProxy role with echo request");
- authorized = this.authorize(au, aaiMethod, httpMethod);
- } else {
- authorized = this.authorize(haProxyUser, uri, httpMethod, "", issuer);
- }
- } else {
- LOGGER.debug("User doesn't have HAProxy role so assuming its a regular client");
- authorized = this.authorize(au, aaiMethod, httpMethod);
- }
- } else {
- LOGGER.debug("User not found: " + username + " on function " + aaiMethod + " request type " + httpMethod);
- authorized = false;
- }
-
- return authorized;
- }
-
- private boolean isWildcardIssuer(String issuer) {
- if (issuer != null && !issuer.isEmpty()) {
- List<String> validIssuers = Arrays.asList(AAIConfig.get("aaf.valid.issuer.wildcard", UUID.randomUUID().toString()).split("\\|"));
- for (String validIssuer : validIssuers) {
- if (issuer.contains(validIssuer)) {
- return true;
- }
- }
- }
- return false;
- }
-
- /**
- * returns aai user either matching the username or containing the wildcard.
- * @param username
- * @return
- */
- public Optional<AAIUser> getUser(String username, boolean wildcardCheck) {
- if (users.containsKey(username)) {
- return Optional.of(users.get(username));
- } else if (wildcardCheck){
- List<AAIUser> laus = users.entrySet().stream().filter(e -> e.getValue().isWildcard() && username.contains(e.getKey())).map(Map.Entry::getValue).collect(Collectors.toList());
- if (!laus.isEmpty()) {
- return Optional.of(laus.get(0));
- }
- }
- return Optional.empty();
- }
-
- /**
- *
- * @param aaiUser
- * aai user with the username
- * @param aaiMethod
- * aai function the authorization is required on
- * @param httpMethod
- * http action user is attempting
- * @return true, if successful
- */
- private boolean authorize(AAIUser aaiUser, String aaiMethod, String httpMethod) {
- if (aaiUser.hasAccess(aaiMethod, httpMethod)) {
- LoggingContext.statusCode(StatusCode.COMPLETE);
- LOGGER.debug("AUTH ACCEPTED: " + aaiUser.getUsername() + " on function " + aaiMethod + " request type " + httpMethod);
- return true;
- } else {
- LoggingContext.statusCode(StatusCode.ERROR);
- LOGGER.debug("AUTH FAILED: " + aaiUser.getUsername() + " on function " + aaiMethod + " request type " + httpMethod);
- return false;
- }
- }
+ } else if (uri.startsWith(basePath + "/util/echo")) {
+ authPolicyFunctionName = "util";
+ } else if (uri.startsWith(basePath + "/tools")) {
+ authPolicyFunctionName = "tools";
+ } else {
+ Matcher match = AUTH_POLICY_PATTERN.matcher(uri);
+ if (match.find()) {
+ authPolicyFunctionName = match.group(1);
+ }
+ }
+ return authPolicyFunctionName;
+ }
+
+ /**
+ * for backwards compatibility
+ *
+ * @param username
+ * @param uri
+ * @param httpMethod
+ * @param haProxyUser
+ * @return
+ * @throws AAIUnrecognizedFunctionException
+ */
+ public boolean authorize(String username, String uri, String httpMethod, String haProxyUser)
+ throws AAIUnrecognizedFunctionException {
+ return authorize(username, uri, httpMethod, haProxyUser, null);
+ }
+
+ /**
+ *
+ * @param username
+ * @param uri
+ * @param httpMethod
+ * @param haProxyUser
+ * @param issuer issuer of the cert
+ * @return
+ * @throws AAIUnrecognizedFunctionException
+ */
+ public boolean authorize(String username, String uri, String httpMethod, String haProxyUser, String issuer)
+ throws AAIUnrecognizedFunctionException {
+ String aaiMethod = this.getAuthPolicyFunctName(uri);
+ if (!this.validFunctions.contains(aaiMethod)) {
+ throw new AAIUnrecognizedFunctionException(aaiMethod);
+ }
+ boolean wildcardCheck = isWildcardIssuer(issuer);
+ boolean authorized;
+ LOGGER.debug(
+ "Authorizing the user for the request cert {}, haproxy header {}, aai method {}, httpMethod {}, cert issuer {}",
+ username, haProxyUser, aaiMethod, httpMethod, issuer);
+ Optional<AAIUser> oau = this.getUser(username, wildcardCheck);
+ if (oau.isPresent()) {
+ AAIUser au = oau.get();
+ if (au.hasRole("HAProxy")) {
+ LOGGER.debug("User has HAProxy role");
+ if ("GET".equalsIgnoreCase(httpMethod) && "util".equalsIgnoreCase(aaiMethod) && haProxyUser.isEmpty()) {
+ LOGGER.debug("Authorized user has HAProxy role with echo request");
+ authorized = this.authorize(au, aaiMethod, httpMethod);
+ } else {
+ authorized = this.authorize(haProxyUser, uri, httpMethod, "", issuer);
+ }
+ } else {
+ LOGGER.debug("User doesn't have HAProxy role so assuming its a regular client");
+ authorized = this.authorize(au, aaiMethod, httpMethod);
+ }
+ } else {
+ LOGGER.debug("User not found: " + username + " on function " + aaiMethod + " request type " + httpMethod);
+ authorized = false;
+ }
+
+ return authorized;
+ }
+
+ private boolean isWildcardIssuer(String issuer) {
+ if (issuer != null && !issuer.isEmpty()) {
+ List<String> validIssuers = Arrays
+ .asList(AAIConfig.get("aaf.valid.issuer.wildcard", UUID.randomUUID().toString()).split("\\|"));
+ for (String validIssuer : validIssuers) {
+ if (issuer.contains(validIssuer)) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ /**
+ * returns aai user either matching the username or containing the wildcard.
+ *
+ * @param username
+ * @return
+ */
+ public Optional<AAIUser> getUser(String username, boolean wildcardCheck) {
+ if (users.containsKey(username)) {
+ return Optional.of(users.get(username));
+ } else if (wildcardCheck) {
+ List<AAIUser> laus =
+ users.entrySet().stream().filter(e -> e.getValue().isWildcard() && username.contains(e.getKey()))
+ .map(Map.Entry::getValue).collect(Collectors.toList());
+ if (!laus.isEmpty()) {
+ return Optional.of(laus.get(0));
+ }
+ }
+ return Optional.empty();
+ }
+
+ /**
+ *
+ * @param aaiUser
+ * aai user with the username
+ * @param aaiMethod
+ * aai function the authorization is required on
+ * @param httpMethod
+ * http action user is attempting
+ * @return true, if successful
+ */
+ private boolean authorize(AAIUser aaiUser, String aaiMethod, String httpMethod) {
+ if (aaiUser.hasAccess(aaiMethod, httpMethod)) {
+ LoggingContext.statusCode(StatusCode.COMPLETE);
+ LOGGER.debug("AUTH ACCEPTED: " + aaiUser.getUsername() + " on function " + aaiMethod + " request type "
+ + httpMethod);
+ return true;
+ } else {
+ LoggingContext.statusCode(StatusCode.ERROR);
+ LOGGER.debug("AUTH FAILED: " + aaiUser.getUsername() + " on function " + aaiMethod + " request type "
+ + httpMethod);
+ return false;
+ }
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/auth/AAIUser.java b/aai-core/src/main/java/org/onap/aai/auth/AAIUser.java
index 499c6858..f1e1b084 100644
--- a/aai-core/src/main/java/org/onap/aai/auth/AAIUser.java
+++ b/aai-core/src/main/java/org/onap/aai/auth/AAIUser.java
@@ -19,6 +19,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.auth;
import java.util.*;
diff --git a/aai-core/src/main/java/org/onap/aai/auth/exceptions/AAIUnrecognizedFunctionException.java b/aai-core/src/main/java/org/onap/aai/auth/exceptions/AAIUnrecognizedFunctionException.java
index 01be1c27..1410b445 100644
--- a/aai-core/src/main/java/org/onap/aai/auth/exceptions/AAIUnrecognizedFunctionException.java
+++ b/aai-core/src/main/java/org/onap/aai/auth/exceptions/AAIUnrecognizedFunctionException.java
@@ -19,6 +19,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.auth.exceptions;
import org.onap.aai.exceptions.AAIException;
@@ -28,14 +29,15 @@ public class AAIUnrecognizedFunctionException extends AAIException {
private static final String AAI_3012 = "AAI_3012";
private static final long serialVersionUID = 3297064867724071290L;
- public AAIUnrecognizedFunctionException() {}
+ public AAIUnrecognizedFunctionException() {
+ }
public AAIUnrecognizedFunctionException(String message) {
super(AAI_3012, message);
}
public AAIUnrecognizedFunctionException(Throwable cause) {
- super(AAI_3012,cause);
+ super(AAI_3012, cause);
}
public AAIUnrecognizedFunctionException(String message, Throwable cause) {
diff --git a/aai-core/src/main/java/org/onap/aai/concurrent/AaiCallable.java b/aai-core/src/main/java/org/onap/aai/concurrent/AaiCallable.java
index 0f3469e9..6ea67b90 100644
--- a/aai-core/src/main/java/org/onap/aai/concurrent/AaiCallable.java
+++ b/aai-core/src/main/java/org/onap/aai/concurrent/AaiCallable.java
@@ -17,32 +17,39 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.concurrent;
-import java.util.concurrent.Callable;
+
import java.util.Map;
+import java.util.concurrent.Callable;
+
import org.slf4j.MDC;
/**
- * The Class AaiCallable ensures that the Callable gets a copy of the MDC, so that any logging related fields are preserved
+ * The Class AaiCallable ensures that the Callable gets a copy of the MDC, so that any logging related fields are
+ * preserved
*/
public abstract class AaiCallable<T> implements Callable<T> {
- private Map<String,String> mdcCopy;
- /**
- * The constructor.
- */
- @SuppressWarnings("unchecked")
- public AaiCallable() {
+ private Map<String, String> mdcCopy;
+
+ /**
+ * The constructor.
+ */
+ @SuppressWarnings("unchecked")
+ public AaiCallable() {
mdcCopy = MDC.getCopyOfContextMap();
}
- /**
- * The call method
- */
+
+ /**
+ * The call method
+ */
public T call() throws Exception {
- MDC.setContextMap(mdcCopy);
+ MDC.setContextMap(mdcCopy);
return process();
}
+
/**
- * The process method
- */
+ * The process method
+ */
public abstract T process() throws Exception;
}
diff --git a/aai-core/src/main/java/org/onap/aai/config/AuthorizationConfiguration.java b/aai-core/src/main/java/org/onap/aai/config/AuthorizationConfiguration.java
index 0efe1475..9f8bbc45 100644
--- a/aai-core/src/main/java/org/onap/aai/config/AuthorizationConfiguration.java
+++ b/aai-core/src/main/java/org/onap/aai/config/AuthorizationConfiguration.java
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.config;
import org.onap.aai.auth.AAIAuthCore;
@@ -33,7 +34,7 @@ public class AuthorizationConfiguration {
private String basePath;
@Bean
- public AAIAuthCore aaiAuthCore(){
+ public AAIAuthCore aaiAuthCore() {
return new AAIAuthCore(basePath);
}
}
diff --git a/aai-core/src/main/java/org/onap/aai/config/IntrospectionConfig.java b/aai-core/src/main/java/org/onap/aai/config/IntrospectionConfig.java
index 750bc24f..2a4673c0 100644
--- a/aai-core/src/main/java/org/onap/aai/config/IntrospectionConfig.java
+++ b/aai-core/src/main/java/org/onap/aai/config/IntrospectionConfig.java
@@ -19,27 +19,29 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-package org.onap.aai.config;
-import org.onap.aai.setup.SchemaVersion;
-import org.onap.aai.setup.SchemaVersions;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
+package org.onap.aai.config;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import org.onap.aai.introspection.LoaderFactory;
import org.onap.aai.introspection.MoxyLoader;
+import org.onap.aai.setup.SchemaVersion;
+import org.onap.aai.setup.SchemaVersions;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
-@Import({ConfigConfiguration.class, SchemaServiceConfiguration.class, NodesConfiguration.class, EdgesConfiguration.class})
+
+@Import({ConfigConfiguration.class, SchemaServiceConfiguration.class, NodesConfiguration.class,
+ EdgesConfiguration.class})
@Configuration
public class IntrospectionConfig {
private Map<SchemaVersion, MoxyLoader> moxyInstanceMap = new ConcurrentHashMap<>();
-
+
@Autowired
NodesConfiguration nodesConfiguration;
@@ -50,7 +52,7 @@ public class IntrospectionConfig {
@Bean
public Map<SchemaVersion, MoxyLoader> moxyLoaderInstance(SchemaVersions schemaVersions) {
- for(SchemaVersion version : schemaVersions.getVersions()){
+ for (SchemaVersion version : schemaVersions.getVersions()) {
if (!moxyInstanceMap.containsKey(version)) {
moxyInstanceMap.put(version, new MoxyLoader(version, nodesConfiguration.nodeIngestor()));
}
diff --git a/aai-core/src/main/java/org/onap/aai/config/RestBeanConfig.java b/aai-core/src/main/java/org/onap/aai/config/RestBeanConfig.java
index 6c56ff69..4dc8860e 100644
--- a/aai-core/src/main/java/org/onap/aai/config/RestBeanConfig.java
+++ b/aai-core/src/main/java/org/onap/aai/config/RestBeanConfig.java
@@ -19,11 +19,10 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-package org.onap.aai.config;
+package org.onap.aai.config;
import org.onap.aai.introspection.ModelType;
-
import org.onap.aai.rest.db.HttpEntry;
import org.onap.aai.serialization.engines.QueryStyle;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
@@ -38,13 +37,11 @@ public class RestBeanConfig {
public HttpEntry traversalUriHttpEntry() {
return new HttpEntry(ModelType.MOXY, QueryStyle.TRAVERSAL_URI);
}
-
+
@Bean(name = "traversalHttpEntry")
@Scope(scopeName = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public HttpEntry traversalHttpEntry() {
return new HttpEntry(ModelType.MOXY, QueryStyle.TRAVERSAL);
}
-
-
-
+
}
diff --git a/aai-core/src/main/java/org/onap/aai/config/SchemaConfiguration.java b/aai-core/src/main/java/org/onap/aai/config/SchemaConfiguration.java
index c11d7a56..885790ce 100644
--- a/aai-core/src/main/java/org/onap/aai/config/SchemaConfiguration.java
+++ b/aai-core/src/main/java/org/onap/aai/config/SchemaConfiguration.java
@@ -19,15 +19,16 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.config;
import org.onap.aai.edges.EdgeIngestor;
import org.onap.aai.nodes.NodeIngestor;
+import org.onap.aai.serialization.db.EdgeSerializer;
import org.onap.aai.setup.AAIConfigTranslator;
import org.onap.aai.setup.ConfigTranslator;
-import org.onap.aai.setup.SchemaLocationsBean;
import org.onap.aai.setup.SchemaConfigVersions;
-import org.onap.aai.serialization.db.EdgeSerializer;
+import org.onap.aai.setup.SchemaLocationsBean;
import org.onap.aai.validation.CheckEverythingStrategy;
import org.onap.aai.validation.SchemaErrorStrategy;
import org.onap.aai.validation.nodes.DefaultDuplicateNodeDefinitionValidationModule;
@@ -36,13 +37,14 @@ import org.onap.aai.validation.nodes.NodeValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.*;
+
@Import({NodesConfiguration.class, EdgesConfiguration.class})
@Configuration
@PropertySource(value = "classpath:schema-ingest.properties", ignoreResourceNotFound = true)
@PropertySource(value = "file:${schema.ingest.file}", ignoreResourceNotFound = true)
public class SchemaConfiguration {
- //TODO : Inject this directly into nodeIngestor
+ // TODO : Inject this directly into nodeIngestor
@Autowired(required = false)
NodesConfiguration nodesConfiguration;
@@ -50,12 +52,12 @@ public class SchemaConfiguration {
EdgesConfiguration edgesConfiguration;
@Bean
- public EdgeIngestor edgeIngestor(){
+ public EdgeIngestor edgeIngestor() {
return edgesConfiguration.edgeIngestor();
}
@Bean
- public EdgeSerializer edgeSerializer(EdgeIngestor edgeIngestor){
+ public EdgeSerializer edgeSerializer(EdgeIngestor edgeIngestor) {
return new EdgeSerializer(edgeIngestor);
}
@@ -64,32 +66,29 @@ public class SchemaConfiguration {
return nodesConfiguration.nodeIngestor();
}
-
@Bean(name = "configTranslator")
@ConditionalOnProperty(name = "schema.translator.list", havingValue = "config", matchIfMissing = true)
- public ConfigTranslator configTranslator(SchemaLocationsBean schemaLocationsBean, SchemaConfigVersions schemaVersions) {
+ public ConfigTranslator configTranslator(SchemaLocationsBean schemaLocationsBean,
+ SchemaConfigVersions schemaVersions) {
return new AAIConfigTranslator(schemaLocationsBean, schemaVersions);
}
@Bean
@ConditionalOnProperty(name = "schema.translator.list", havingValue = "config", matchIfMissing = true)
- public SchemaErrorStrategy schemaErrorStrategy(){
+ public SchemaErrorStrategy schemaErrorStrategy() {
return new CheckEverythingStrategy();
- }
+ }
- @Bean
- @ConditionalOnProperty(name = "schema.translator.list", havingValue = "config", matchIfMissing = true)
- public DuplicateNodeDefinitionValidationModule duplicateNodeDefinitionValidationModule(){
- return new DefaultDuplicateNodeDefinitionValidationModule();
- }
+ @Bean
+ @ConditionalOnProperty(name = "schema.translator.list", havingValue = "config", matchIfMissing = true)
+ public DuplicateNodeDefinitionValidationModule duplicateNodeDefinitionValidationModule() {
+ return new DefaultDuplicateNodeDefinitionValidationModule();
+ }
- @Bean
- @ConditionalOnProperty(name = "schema.translator.list", havingValue = "config", matchIfMissing = true)
- public NodeValidator nodeValidator(
- ConfigTranslator configTranslator,
- SchemaErrorStrategy schemaErrorStrategy,
- DuplicateNodeDefinitionValidationModule duplicateNodeDefinitionValidationModule
- ){
+ @Bean
+ @ConditionalOnProperty(name = "schema.translator.list", havingValue = "config", matchIfMissing = true)
+ public NodeValidator nodeValidator(ConfigTranslator configTranslator, SchemaErrorStrategy schemaErrorStrategy,
+ DuplicateNodeDefinitionValidationModule duplicateNodeDefinitionValidationModule) {
return new NodeValidator(configTranslator, schemaErrorStrategy, duplicateNodeDefinitionValidationModule);
- }
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/config/SpringContextAware.java b/aai-core/src/main/java/org/onap/aai/config/SpringContextAware.java
index c58d57e9..b8694554 100644
--- a/aai-core/src/main/java/org/onap/aai/config/SpringContextAware.java
+++ b/aai-core/src/main/java/org/onap/aai/config/SpringContextAware.java
@@ -17,8 +17,8 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-package org.onap.aai.config;
+package org.onap.aai.config;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
@@ -31,31 +31,30 @@ public class SpringContextAware implements ApplicationContextAware {
private static ApplicationContext context = null;
public static ApplicationContext getApplicationContext() {
- return context;
+ return context;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
- context = applicationContext;
+ context = applicationContext;
}
-
-
- public static <T> T getBean(String beanName, Class<T> requiredType) {
- if(context != null){
- return context.getBean(beanName, requiredType);
- }
+
+ public static <T> T getBean(String beanName, Class<T> requiredType) {
+ if (context != null) {
+ return context.getBean(beanName, requiredType);
+ }
return null;
- }
+ }
- public static <T> T getBean(Class<T> clazz){
- if(context != null){
+ public static <T> T getBean(Class<T> clazz) {
+ if (context != null) {
return context.getBean(clazz);
}
return null;
}
- public static Object getBean(String bean){
- if(context != null){
+ public static Object getBean(String bean) {
+ if (context != null) {
return context.getBean(bean);
}
return null;
diff --git a/aai-core/src/main/java/org/onap/aai/db/DbMethHelper.java b/aai-core/src/main/java/org/onap/aai/db/DbMethHelper.java
index 9a73f0f0..5c955cb5 100644
--- a/aai-core/src/main/java/org/onap/aai/db/DbMethHelper.java
+++ b/aai-core/src/main/java/org/onap/aai/db/DbMethHelper.java
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.db;
import java.io.UnsupportedEncodingException;
@@ -30,7 +31,6 @@ import java.util.Optional;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.VertexProperty;
-
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.introspection.Introspector;
import org.onap.aai.introspection.Loader;
@@ -42,116 +42,119 @@ import org.onap.aai.serialization.engines.TransactionalGraphEngine;
public class DbMethHelper {
- private final Loader loader;
- private final TransactionalGraphEngine engine;
-
- protected DbMethHelper() {
- this.loader = null;
- this.engine = null;
- }
- public DbMethHelper(Loader loader, TransactionalGraphEngine engine) {
- this.loader = loader;
- this.engine = engine;
- }
- /**
- *
- * @param type
- * @param map - form [{type}.{propname}:{value}]
- * @return
- * @throws UnsupportedEncodingException
- * @throws AAIException
- */
- public Optional<Vertex> searchVertexByIdentityMap(String type, Map<String, Object> map) throws AAIException {
-
- Introspector relationship = constructRelationship(type, map);
- RelationshipToURI parser;
- URI uri;
- QueryParser queryParser;
- try {
- parser = new RelationshipToURI(loader, relationship);
- uri = parser.getUri();
- queryParser = this.engine.getQueryBuilder().createQueryFromURI(uri);
- } catch (UnsupportedEncodingException e) {
- throw new AAIException("AAI_3000");
- }
-
- List<Vertex> results = queryParser.getQueryBuilder().toList();
-
- return reduceToSingleVertex(results, map);
- }
-
- /**
- * @param type
- * @param map - form [{propname}:{value}]
- * @return
- * @throws AAIException
- */
- public Optional<Vertex> locateUniqueVertex(String type, Map<String, Object> map) throws AAIException {
-
- return reduceToSingleVertex(locateUniqueVertices(type, map), map);
- }
-
- public List<Vertex> locateUniqueVertices(String type, Map<String, Object> map) throws AAIException {
- Introspector obj = this.createIntrospectorFromMap(type, map);
- QueryBuilder builder = this.engine.getQueryBuilder().exactMatchQuery(obj);
-
- return builder.toList();
- }
- private Introspector constructRelationship(String type, Map<String, Object> map) throws AAIUnknownObjectException {
- final Introspector relationship = loader.introspectorFromName("relationship");
- relationship.setValue("related-to", type);
- final List<Object> data = relationship.getValue("relationship-data");
- for (Entry<String, Object> entry : map.entrySet()) {
- final Introspector dataObj = loader.introspectorFromName("relationship-data");
- dataObj.setValue("relationship-key", entry.getKey());
- dataObj.setValue("relationship-value", entry.getValue());
- data.add(dataObj.getUnderlyingObject());
- }
-
- return relationship;
- }
-
- private Introspector createIntrospectorFromMap(String targetNodeType, Map<String, Object> propHash) throws AAIUnknownObjectException {
- final Introspector result = loader.introspectorFromName(targetNodeType);
- for (Entry<String, Object> entry : propHash.entrySet()) {
- result.setValue(entry.getKey(), entry.getValue());
- }
- return result;
- }
-
- private Optional<Vertex> reduceToSingleVertex(List<Vertex> vertices, Map<String, Object> map) throws AAIException {
- if (vertices.isEmpty()){
- return Optional.empty();
- } else if (vertices.size() > 1) {
- throw new AAIException("AAI_6112", "More than one Node found by getUniqueNode for params: " + map);
- }
-
- return Optional.of(vertices.get(0));
- }
- public List<String> getVertexProperties(Vertex v) {
- List<String> retArr = new ArrayList<>();
- if( v == null ){
- retArr.add("null Node object passed to showPropertiesForNode()\n");
- }
- else {
- String nodeType;
- Object ob = v.<Object>property("aai-node-type").orElse(null);
- if( ob == null ){
- nodeType = "null";
- }
- else{
- nodeType = ob.toString();
- }
-
- retArr.add(" AAINodeType/VtxID for this Node = [" + nodeType + "/" + v.id() + "]");
- retArr.add(" Property Detail: ");
- Iterator<VertexProperty<Object>> pI = v.properties();
- while( pI.hasNext() ){
- VertexProperty<Object> tp = pI.next();
- Object val = tp.value();
- retArr.add("Prop: [" + tp.key() + "], val = [" + val + "] ");
- }
- }
- return retArr;
- }
+ private final Loader loader;
+ private final TransactionalGraphEngine engine;
+
+ protected DbMethHelper() {
+ this.loader = null;
+ this.engine = null;
+ }
+
+ public DbMethHelper(Loader loader, TransactionalGraphEngine engine) {
+ this.loader = loader;
+ this.engine = engine;
+ }
+
+ /**
+ *
+ * @param type
+ * @param map - form [{type}.{propname}:{value}]
+ * @return
+ * @throws UnsupportedEncodingException
+ * @throws AAIException
+ */
+ public Optional<Vertex> searchVertexByIdentityMap(String type, Map<String, Object> map) throws AAIException {
+
+ Introspector relationship = constructRelationship(type, map);
+ RelationshipToURI parser;
+ URI uri;
+ QueryParser queryParser;
+ try {
+ parser = new RelationshipToURI(loader, relationship);
+ uri = parser.getUri();
+ queryParser = this.engine.getQueryBuilder().createQueryFromURI(uri);
+ } catch (UnsupportedEncodingException e) {
+ throw new AAIException("AAI_3000");
+ }
+
+ List<Vertex> results = queryParser.getQueryBuilder().toList();
+
+ return reduceToSingleVertex(results, map);
+ }
+
+ /**
+ * @param type
+ * @param map - form [{propname}:{value}]
+ * @return
+ * @throws AAIException
+ */
+ public Optional<Vertex> locateUniqueVertex(String type, Map<String, Object> map) throws AAIException {
+
+ return reduceToSingleVertex(locateUniqueVertices(type, map), map);
+ }
+
+ public List<Vertex> locateUniqueVertices(String type, Map<String, Object> map) throws AAIException {
+ Introspector obj = this.createIntrospectorFromMap(type, map);
+ QueryBuilder builder = this.engine.getQueryBuilder().exactMatchQuery(obj);
+
+ return builder.toList();
+ }
+
+ private Introspector constructRelationship(String type, Map<String, Object> map) throws AAIUnknownObjectException {
+ final Introspector relationship = loader.introspectorFromName("relationship");
+ relationship.setValue("related-to", type);
+ final List<Object> data = relationship.getValue("relationship-data");
+ for (Entry<String, Object> entry : map.entrySet()) {
+ final Introspector dataObj = loader.introspectorFromName("relationship-data");
+ dataObj.setValue("relationship-key", entry.getKey());
+ dataObj.setValue("relationship-value", entry.getValue());
+ data.add(dataObj.getUnderlyingObject());
+ }
+
+ return relationship;
+ }
+
+ private Introspector createIntrospectorFromMap(String targetNodeType, Map<String, Object> propHash)
+ throws AAIUnknownObjectException {
+ final Introspector result = loader.introspectorFromName(targetNodeType);
+ for (Entry<String, Object> entry : propHash.entrySet()) {
+ result.setValue(entry.getKey(), entry.getValue());
+ }
+ return result;
+ }
+
+ private Optional<Vertex> reduceToSingleVertex(List<Vertex> vertices, Map<String, Object> map) throws AAIException {
+ if (vertices.isEmpty()) {
+ return Optional.empty();
+ } else if (vertices.size() > 1) {
+ throw new AAIException("AAI_6112", "More than one Node found by getUniqueNode for params: " + map);
+ }
+
+ return Optional.of(vertices.get(0));
+ }
+
+ public List<String> getVertexProperties(Vertex v) {
+ List<String> retArr = new ArrayList<>();
+ if (v == null) {
+ retArr.add("null Node object passed to showPropertiesForNode()\n");
+ } else {
+ String nodeType;
+ Object ob = v.<Object>property("aai-node-type").orElse(null);
+ if (ob == null) {
+ nodeType = "null";
+ } else {
+ nodeType = ob.toString();
+ }
+
+ retArr.add(" AAINodeType/VtxID for this Node = [" + nodeType + "/" + v.id() + "]");
+ retArr.add(" Property Detail: ");
+ Iterator<VertexProperty<Object>> pI = v.properties();
+ while (pI.hasNext()) {
+ VertexProperty<Object> tp = pI.next();
+ Object val = tp.value();
+ retArr.add("Prop: [" + tp.key() + "], val = [" + val + "] ");
+ }
+ }
+ return retArr;
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/db/props/AAIProperties.java b/aai-core/src/main/java/org/onap/aai/db/props/AAIProperties.java
index 6b4035c6..a0f6d77e 100644
--- a/aai-core/src/main/java/org/onap/aai/db/props/AAIProperties.java
+++ b/aai-core/src/main/java/org/onap/aai/db/props/AAIProperties.java
@@ -19,6 +19,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.db.props;
public class AAIProperties {
@@ -34,9 +35,9 @@ public class AAIProperties {
public static final String LINKED = "linked";
public static final String DB_ALIAS_SUFFIX = "-local";
public static final String AAI_UUID = "aai-uuid";
-
+
private AAIProperties() {
-
+
}
}
diff --git a/aai-core/src/main/java/org/onap/aai/dbgen/GraphSONPartialIO.java b/aai-core/src/main/java/org/onap/aai/dbgen/GraphSONPartialIO.java
index 915db69c..02dede24 100644
--- a/aai-core/src/main/java/org/onap/aai/dbgen/GraphSONPartialIO.java
+++ b/aai-core/src/main/java/org/onap/aai/dbgen/GraphSONPartialIO.java
@@ -17,8 +17,17 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.dbgen;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.Optional;
+import java.util.function.Consumer;
+
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.io.Io;
import org.apache.tinkerpop.gremlin.structure.io.IoRegistry;
@@ -28,21 +37,15 @@ import org.apache.tinkerpop.gremlin.structure.io.graphson.GraphSONReader;
import org.apache.tinkerpop.gremlin.structure.io.graphson.GraphSONVersion;
import org.apache.tinkerpop.gremlin.structure.io.graphson.GraphSONWriter;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.util.Optional;
-import java.util.function.Consumer;
-
/**
- * Constructs GraphSON IO implementations given a {@link Graph} and {@link IoRegistry}. Implementers of the {@link Graph}
+ * Constructs GraphSON IO implementations given a {@link Graph} and {@link IoRegistry}. Implementers of the
+ * {@link Graph}
* interfaces should see the {@link GraphSONMapper} for information on the expectations for the {@link IoRegistry}.
*
* @author Stephen Mallette (http://stephen.genoprime.com)
*/
-public final class GraphSONPartialIO implements Io<GraphSONPartialReader.Builder, GraphSONWriter.Builder, GraphSONMapper.Builder> {
+public final class GraphSONPartialIO
+ implements Io<GraphSONPartialReader.Builder, GraphSONWriter.Builder, GraphSONMapper.Builder> {
private final IoRegistry registry;
private final Graph graph;
private final Optional<Consumer<Mapper.Builder>> onMapper;
@@ -76,8 +79,8 @@ public final class GraphSONPartialIO implements Io<GraphSONPartialReader.Builder
*/
@Override
public GraphSONMapper.Builder mapper() {
- final GraphSONMapper.Builder builder = (null == this.registry) ?
- GraphSONMapper.build().version(version) : GraphSONMapper.build().version(version).addRegistry(this.registry);
+ final GraphSONMapper.Builder builder = (null == this.registry) ? GraphSONMapper.build().version(version)
+ : GraphSONMapper.build().version(version).addRegistry(this.registry);
onMapper.ifPresent(c -> c.accept(builder));
return builder;
}
@@ -151,7 +154,8 @@ public final class GraphSONPartialIO implements Io<GraphSONPartialReader.Builder
@Override
public GraphSONPartialIO create() {
- if (null == graph) throw new IllegalArgumentException("The graph argument was not specified");
+ if (null == graph)
+ throw new IllegalArgumentException("The graph argument was not specified");
return new GraphSONPartialIO(this);
}
}
diff --git a/aai-core/src/main/java/org/onap/aai/dbgen/GraphSONPartialReader.java b/aai-core/src/main/java/org/onap/aai/dbgen/GraphSONPartialReader.java
index 2088286d..fdc8e814 100644
--- a/aai-core/src/main/java/org/onap/aai/dbgen/GraphSONPartialReader.java
+++ b/aai-core/src/main/java/org/onap/aai/dbgen/GraphSONPartialReader.java
@@ -17,8 +17,25 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.dbgen;
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
+
+import java.io.BufferedReader;
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.function.Function;
+import java.util.stream.Stream;
+
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Graph;
@@ -45,22 +62,6 @@ import org.apache.tinkerpop.shaded.jackson.databind.ObjectMapper;
import org.apache.tinkerpop.shaded.jackson.databind.node.JsonNodeType;
import org.onap.aai.dbmap.InMemoryGraph;
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
-
-import java.io.BufferedReader;
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.OutputStream;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.concurrent.atomic.AtomicLong;
-import java.util.function.Function;
-import java.util.stream.Stream;
-
/**
* This is a Wrapper around the GraphsonReader class
* The idea is to rewrite methods that are customized for A&AI
@@ -70,22 +71,21 @@ import java.util.stream.Stream;
*
*/
public final class GraphSONPartialReader implements GraphReader {
- private final ObjectMapper mapper ;
- private final long batchSize ;
- private final GraphSONVersion version ;
+ private final ObjectMapper mapper;
+ private final long batchSize;
+ private final GraphSONVersion version;
private boolean unwrapAdjacencyList = false;
private final GraphSONReader reader;
-
+
private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(InMemoryGraph.class);
- final TypeReference<Map<String, Object>> mapTypeReference = new TypeReference<Map<String, Object>>() {
- };
+ final TypeReference<Map<String, Object>> mapTypeReference = new TypeReference<Map<String, Object>>() {};
private GraphSONPartialReader(final Builder builder) {
mapper = builder.mapper.createMapper();
batchSize = builder.batchSize;
unwrapAdjacencyList = builder.unwrapAdjacencyList;
- version = ((GraphSONMapper)builder.mapper).getVersion();
+ version = ((GraphSONMapper) builder.mapper).getVersion();
reader = GraphSONReader.build().create();
}
@@ -94,58 +94,62 @@ public final class GraphSONPartialReader implements GraphReader {
* {@code writeVertices} methods or by {@link GryoWriter#writeGraph(OutputStream, Graph)}.
*
* @param inputStream a stream containing an entire graph of vertices and edges as defined by the accompanying
- * {@link GraphSONWriter#writeGraph(OutputStream, Graph)}.
+ * {@link GraphSONWriter#writeGraph(OutputStream, Graph)}.
* @param graphToWriteTo the graph to write to when reading from the stream.
*/
@Override
public void readGraph(final InputStream inputStream, final Graph graphToWriteTo) throws IOException {
- // dual pass - create all vertices and store to cache the ids. then create edges. as long as we don't
+ // dual pass - create all vertices and store to cache the ids. then create edges. as long as we don't
// have vertex labels in the output we can't do this single pass
- LOGGER.info("Read the Partial Graph");
- final Map<StarGraph.StarVertex,Vertex> cache = new HashMap<>();
+ LOGGER.info("Read the Partial Graph");
+ final Map<StarGraph.StarVertex, Vertex> cache = new HashMap<>();
final AtomicLong counter = new AtomicLong(0);
-
+
final boolean supportsTx = graphToWriteTo.features().graph().supportsTransactions();
final Graph.Features.EdgeFeatures edgeFeatures = graphToWriteTo.features().edge();
-
- readVertexStrings(inputStream).<Vertex>map(FunctionUtils.wrapFunction(line -> readVertex(new ByteArrayInputStream(line.getBytes()), null, null, Direction.IN))).forEach(vertex -> {
- try{
- final Attachable<Vertex> attachable = (Attachable<Vertex>) vertex;
- cache.put((StarGraph.StarVertex) attachable.get(), attachable.attach(Attachable.Method.create(graphToWriteTo)));
- if (supportsTx && counter.incrementAndGet() % batchSize == 0)
- graphToWriteTo.tx().commit();
- }
- catch(Exception ex){
- LOGGER.info("Error in reading vertex from graphson"+vertex.toString());
- }
- });
-
+
+ readVertexStrings(inputStream)
+ .<Vertex>map(FunctionUtils.wrapFunction(
+ line -> readVertex(new ByteArrayInputStream(line.getBytes()), null, null, Direction.IN)))
+ .forEach(vertex -> {
+ try {
+ final Attachable<Vertex> attachable = (Attachable<Vertex>) vertex;
+ cache.put((StarGraph.StarVertex) attachable.get(),
+ attachable.attach(Attachable.Method.create(graphToWriteTo)));
+ if (supportsTx && counter.incrementAndGet() % batchSize == 0)
+ graphToWriteTo.tx().commit();
+ } catch (Exception ex) {
+ LOGGER.info("Error in reading vertex from graphson" + vertex.toString());
+ }
+ });
+
cache.entrySet().forEach(kv -> kv.getKey().edges(Direction.IN).forEachRemaining(e -> {
- try{
- // can't use a standard Attachable attach method here because we have to use the cache for those
- // graphs that don't support userSuppliedIds on edges. note that outVertex/inVertex methods return
- // StarAdjacentVertex whose equality should match StarVertex.
- final Vertex cachedOutV = cache.get(e.outVertex());
- final Vertex cachedInV = cache.get(e.inVertex());
-
- if(cachedOutV != null && cachedInV != null){
-
- final Edge newEdge = edgeFeatures.willAllowId(e.id()) ? cachedOutV.addEdge(e.label(), cachedInV, T.id, e.id()) : cachedOutV.addEdge(e.label(), cachedInV);
- e.properties().forEachRemaining(p -> newEdge.property(p.key(), p.value()));
- }
- else{
- LOGGER.debug("Ghost edges from "+ cachedOutV + " to "+ cachedInV);
-
- }
- if (supportsTx && counter.incrementAndGet() % batchSize == 0)
- graphToWriteTo.tx().commit();
- }
- catch(Exception ex){
- LOGGER.info("Error in writing vertex into graph"+e.toString());
- }
+ try {
+ // can't use a standard Attachable attach method here because we have to use the cache for those
+ // graphs that don't support userSuppliedIds on edges. note that outVertex/inVertex methods return
+ // StarAdjacentVertex whose equality should match StarVertex.
+ final Vertex cachedOutV = cache.get(e.outVertex());
+ final Vertex cachedInV = cache.get(e.inVertex());
+
+ if (cachedOutV != null && cachedInV != null) {
+
+ final Edge newEdge =
+ edgeFeatures.willAllowId(e.id()) ? cachedOutV.addEdge(e.label(), cachedInV, T.id, e.id())
+ : cachedOutV.addEdge(e.label(), cachedInV);
+ e.properties().forEachRemaining(p -> newEdge.property(p.key(), p.value()));
+ } else {
+ LOGGER.debug("Ghost edges from " + cachedOutV + " to " + cachedInV);
+
+ }
+ if (supportsTx && counter.incrementAndGet() % batchSize == 0)
+ graphToWriteTo.tx().commit();
+ } catch (Exception ex) {
+ LOGGER.info("Error in writing vertex into graph" + e.toString());
+ }
}));
- if (supportsTx) graphToWriteTo.tx().commit();
+ if (supportsTx)
+ graphToWriteTo.tx().commit();
}
/**
@@ -153,32 +157,35 @@ public final class GraphSONPartialReader implements GraphReader {
* {@code writeVertices} methods or by {@link GraphSONWriter#writeGraph(OutputStream, Graph)}.
*
* @param inputStream a stream containing at least one {@link Vertex} as defined by the accompanying
- * {@link GraphWriter#writeVertices(OutputStream, Iterator, Direction)} or
- * {@link GraphWriter#writeVertices(OutputStream, Iterator)} methods.
+ * {@link GraphWriter#writeVertices(OutputStream, Iterator, Direction)} or
+ * {@link GraphWriter#writeVertices(OutputStream, Iterator)} methods.
* @param vertexAttachMethod a function that creates re-attaches a {@link Vertex} to a {@link Host} object.
* @param edgeAttachMethod a function that creates re-attaches a {@link Edge} to a {@link Host} object.
* @param attachEdgesOfThisDirection only edges of this direction are passed to the {@code edgeMaker}.
*/
@Override
public Iterator<Vertex> readVertices(final InputStream inputStream,
- final Function<Attachable<Vertex>, Vertex> vertexAttachMethod,
- final Function<Attachable<Edge>, Edge> edgeAttachMethod,
- final Direction attachEdgesOfThisDirection) throws IOException {
- // return readVertexStrings(inputStream).<Vertex>map(FunctionUtils.wrapFunction(line -> readVertex(new ByteArrayInputStream(line.getBytes()), vertexAttachMethod, edgeAttachMethod, attachEdgesOfThisDirection))).iterator();
+ final Function<Attachable<Vertex>, Vertex> vertexAttachMethod,
+ final Function<Attachable<Edge>, Edge> edgeAttachMethod, final Direction attachEdgesOfThisDirection)
+ throws IOException {
+ // return readVertexStrings(inputStream).<Vertex>map(FunctionUtils.wrapFunction(line -> readVertex(new
+ // ByteArrayInputStream(line.getBytes()), vertexAttachMethod, edgeAttachMethod,
+ // attachEdgesOfThisDirection))).iterator();
return reader.readVertices(inputStream, vertexAttachMethod, edgeAttachMethod, attachEdgesOfThisDirection);
-
+
}
/**
- * Read a {@link Vertex} from output generated by any of the {@link GraphSONWriter} {@code writeVertex} or
+ * Read a {@link Vertex} from output generated by any of the {@link GraphSONWriter} {@code writeVertex} or
* {@code writeVertices} methods or by {@link GraphSONWriter#writeGraph(OutputStream, Graph)}.
*
* @param inputStream a stream containing at least a single vertex as defined by the accompanying
- * {@link GraphWriter#writeVertex(OutputStream, Vertex)}.
+ * {@link GraphWriter#writeVertex(OutputStream, Vertex)}.
* @param vertexAttachMethod a function that creates re-attaches a {@link Vertex} to a {@link Host} object.
*/
@Override
- public Vertex readVertex(final InputStream inputStream, final Function<Attachable<Vertex>, Vertex> vertexAttachMethod) throws IOException {
+ public Vertex readVertex(final InputStream inputStream,
+ final Function<Attachable<Vertex>, Vertex> vertexAttachMethod) throws IOException {
return reader.readVertex(inputStream, vertexAttachMethod);
}
@@ -187,18 +194,18 @@ public final class GraphSONPartialReader implements GraphReader {
* {@code writeVertices} methods or by {@link GraphSONWriter#writeGraph(OutputStream, Graph)}.
*
* @param inputStream a stream containing at least one {@link Vertex} as defined by the accompanying
- * {@link GraphWriter#writeVertices(OutputStream, Iterator, Direction)} method.
+ * {@link GraphWriter#writeVertices(OutputStream, Iterator, Direction)} method.
* @param vertexAttachMethod a function that creates re-attaches a {@link Vertex} to a {@link Host} object.
* @param edgeAttachMethod a function that creates re-attaches a {@link Edge} to a {@link Host} object.
* @param attachEdgesOfThisDirection only edges of this direction are passed to the {@code edgeMaker}.
*/
@Override
public Vertex readVertex(final InputStream inputStream,
- final Function<Attachable<Vertex>, Vertex> vertexAttachMethod,
- final Function<Attachable<Edge>, Edge> edgeAttachMethod,
- final Direction attachEdgesOfThisDirection) throws IOException {
-
- return reader.readVertex(inputStream, vertexAttachMethod, edgeAttachMethod, attachEdgesOfThisDirection);
+ final Function<Attachable<Vertex>, Vertex> vertexAttachMethod,
+ final Function<Attachable<Edge>, Edge> edgeAttachMethod, final Direction attachEdgesOfThisDirection)
+ throws IOException {
+
+ return reader.readVertex(inputStream, vertexAttachMethod, edgeAttachMethod, attachEdgesOfThisDirection);
}
/**
@@ -206,27 +213,30 @@ public final class GraphSONPartialReader implements GraphReader {
* an {@link Edge} passed to {@link GraphSONWriter#writeObject(OutputStream, Object)}.
*
* @param inputStream a stream containing at least one {@link Edge} as defined by the accompanying
- * {@link GraphWriter#writeEdge(OutputStream, Edge)} method.
+ * {@link GraphWriter#writeEdge(OutputStream, Edge)} method.
* @param edgeAttachMethod a function that creates re-attaches a {@link Edge} to a {@link Host} object.
*/
@Override
- public Edge readEdge(final InputStream inputStream, final Function<Attachable<Edge>, Edge> edgeAttachMethod) throws IOException {
- /*if (version == GraphSONVersion.v1_0) {
- final Map<String, Object> edgeData = mapper.readValue(inputStream, mapTypeReference);
-
- final Map<String, Object> edgeProperties = edgeData.containsKey(GraphSONTokens.PROPERTIES) ?
- (Map<String, Object>) edgeData.get(GraphSONTokens.PROPERTIES) : Collections.EMPTY_MAP;
- final DetachedEdge edge = new DetachedEdge(edgeData.get(GraphSONTokens.ID),
- edgeData.get(GraphSONTokens.LABEL).toString(),
- edgeProperties,
- Pair.with(edgeData.get(GraphSONTokens.OUT), edgeData.get(GraphSONTokens.OUT_LABEL).toString()),
- Pair.with(edgeData.get(GraphSONTokens.IN), edgeData.get(GraphSONTokens.IN_LABEL).toString()));
-
- return edgeAttachMethod.apply(edge);
- } else {
- return edgeAttachMethod.apply((DetachedEdge) mapper.readValue(inputStream, Edge.class));
- }*/
- return reader.readEdge(inputStream, edgeAttachMethod);
+ public Edge readEdge(final InputStream inputStream, final Function<Attachable<Edge>, Edge> edgeAttachMethod)
+ throws IOException {
+ /*
+ * if (version == GraphSONVersion.v1_0) {
+ * final Map<String, Object> edgeData = mapper.readValue(inputStream, mapTypeReference);
+ *
+ * final Map<String, Object> edgeProperties = edgeData.containsKey(GraphSONTokens.PROPERTIES) ?
+ * (Map<String, Object>) edgeData.get(GraphSONTokens.PROPERTIES) : Collections.EMPTY_MAP;
+ * final DetachedEdge edge = new DetachedEdge(edgeData.get(GraphSONTokens.ID),
+ * edgeData.get(GraphSONTokens.LABEL).toString(),
+ * edgeProperties,
+ * Pair.with(edgeData.get(GraphSONTokens.OUT), edgeData.get(GraphSONTokens.OUT_LABEL).toString()),
+ * Pair.with(edgeData.get(GraphSONTokens.IN), edgeData.get(GraphSONTokens.IN_LABEL).toString()));
+ *
+ * return edgeAttachMethod.apply(edge);
+ * } else {
+ * return edgeAttachMethod.apply((DetachedEdge) mapper.readValue(inputStream, Edge.class));
+ * }
+ */
+ return reader.readEdge(inputStream, edgeAttachMethod);
}
/**
@@ -235,45 +245,51 @@ public final class GraphSONPartialReader implements GraphReader {
* to {@link GraphSONWriter#writeObject(OutputStream, Object)}.
*
* @param inputStream a stream containing at least one {@link VertexProperty} as written by the accompanying
- * {@link GraphWriter#writeVertexProperty(OutputStream, VertexProperty)} method.
+ * {@link GraphWriter#writeVertexProperty(OutputStream, VertexProperty)} method.
* @param vertexPropertyAttachMethod a function that creates re-attaches a {@link VertexProperty} to a
- * {@link Host} object.
+ * {@link Host} object.
*/
@Override
public VertexProperty readVertexProperty(final InputStream inputStream,
- final Function<Attachable<VertexProperty>, VertexProperty> vertexPropertyAttachMethod) throws IOException {
- /*if (version == GraphSONVersion.v1_0) {
- final Map<String, Object> vpData = mapper.readValue(inputStream, mapTypeReference);
- final Map<String, Object> metaProperties = (Map<String, Object>) vpData.get(GraphSONTokens.PROPERTIES);
- final DetachedVertexProperty vp = new DetachedVertexProperty(vpData.get(GraphSONTokens.ID),
- vpData.get(GraphSONTokens.LABEL).toString(),
- vpData.get(GraphSONTokens.VALUE), metaProperties);
- return vertexPropertyAttachMethod.apply(vp);
- } else {
- return vertexPropertyAttachMethod.apply((DetachedVertexProperty) mapper.readValue(inputStream, VertexProperty.class));
- }*/
- return reader.readVertexProperty(inputStream, vertexPropertyAttachMethod);
+ final Function<Attachable<VertexProperty>, VertexProperty> vertexPropertyAttachMethod) throws IOException {
+ /*
+ * if (version == GraphSONVersion.v1_0) {
+ * final Map<String, Object> vpData = mapper.readValue(inputStream, mapTypeReference);
+ * final Map<String, Object> metaProperties = (Map<String, Object>) vpData.get(GraphSONTokens.PROPERTIES);
+ * final DetachedVertexProperty vp = new DetachedVertexProperty(vpData.get(GraphSONTokens.ID),
+ * vpData.get(GraphSONTokens.LABEL).toString(),
+ * vpData.get(GraphSONTokens.VALUE), metaProperties);
+ * return vertexPropertyAttachMethod.apply(vp);
+ * } else {
+ * return vertexPropertyAttachMethod.apply((DetachedVertexProperty) mapper.readValue(inputStream,
+ * VertexProperty.class));
+ * }
+ */
+ return reader.readVertexProperty(inputStream, vertexPropertyAttachMethod);
}
/**
- * Read a {@link Property} from output generated by {@link GraphSONWriter#writeProperty(OutputStream, Property)} or
+ * Read a {@link Property} from output generated by {@link GraphSONWriter#writeProperty(OutputStream, Property)} or
* via an {@link Property} passed to {@link GraphSONWriter#writeObject(OutputStream, Object)}.
*
* @param inputStream a stream containing at least one {@link Property} as written by the accompanying
- * {@link GraphWriter#writeProperty(OutputStream, Property)} method.
+ * {@link GraphWriter#writeProperty(OutputStream, Property)} method.
* @param propertyAttachMethod a function that creates re-attaches a {@link Property} to a {@link Host} object.
*/
@Override
public Property readProperty(final InputStream inputStream,
- final Function<Attachable<Property>, Property> propertyAttachMethod) throws IOException {
- /*if (version == GraphSONVersion.v1_0) {
- final Map<String, Object> propertyData = mapper.readValue(inputStream, mapTypeReference);
- final DetachedProperty p = new DetachedProperty(propertyData.get(GraphSONTokens.KEY).toString(), propertyData.get(GraphSONTokens.VALUE));
- return propertyAttachMethod.apply(p);
- } else {
- return propertyAttachMethod.apply((DetachedProperty) mapper.readValue(inputStream, Property.class));
- }*/
- return reader.readProperty(inputStream, propertyAttachMethod);
+ final Function<Attachable<Property>, Property> propertyAttachMethod) throws IOException {
+ /*
+ * if (version == GraphSONVersion.v1_0) {
+ * final Map<String, Object> propertyData = mapper.readValue(inputStream, mapTypeReference);
+ * final DetachedProperty p = new DetachedProperty(propertyData.get(GraphSONTokens.KEY).toString(),
+ * propertyData.get(GraphSONTokens.VALUE));
+ * return propertyAttachMethod.apply(p);
+ * } else {
+ * return propertyAttachMethod.apply((DetachedProperty) mapper.readValue(inputStream, Property.class));
+ * }
+ */
+ return reader.readProperty(inputStream, propertyAttachMethod);
}
/**
@@ -286,18 +302,18 @@ public final class GraphSONPartialReader implements GraphReader {
private Stream<String> readVertexStrings(final InputStream inputStream) throws IOException {
if (unwrapAdjacencyList) {
- final JsonNode root = mapper.readTree(inputStream);
+ final JsonNode root = mapper.readTree(inputStream);
final JsonNode vertices = root.get(GraphSONTokens.VERTICES);
- if (!vertices.getNodeType().equals(JsonNodeType.ARRAY)) throw new IOException(String.format("The '%s' key must be an array", GraphSONTokens.VERTICES));
+ if (!vertices.getNodeType().equals(JsonNodeType.ARRAY))
+ throw new IOException(String.format("The '%s' key must be an array", GraphSONTokens.VERTICES));
return IteratorUtils.stream(vertices.elements()).map(Object::toString);
} else {
- final BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
+ final BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
return br.lines();
}
-
+
}
-
public static Builder build() {
return new Builder();
}
@@ -307,9 +323,9 @@ public final class GraphSONPartialReader implements GraphReader {
private Mapper<ObjectMapper> mapper = GraphSONMapper.build().create();
private boolean unwrapAdjacencyList = false;
-
- private Builder() {}
+ private Builder() {
+ }
/**
* Number of mutations to perform before a commit is executed when using
@@ -322,7 +338,7 @@ public final class GraphSONPartialReader implements GraphReader {
/**
* Override all of the {@link GraphSONMapper} builder
- * options with this mapper. If this value is set to something other than null then that value will be
+ * options with this mapper. If this value is set to something other than null then that value will be
* used to construct the writer.
*/
public Builder mapper(final Mapper<ObjectMapper> mapper) {
@@ -333,11 +349,11 @@ public final class GraphSONPartialReader implements GraphReader {
/**
* If the adjacency list is wrapped in a JSON object, as is done when writing a graph with
* {@link GraphSONWriter.Builder#wrapAdjacencyList} set to {@code true}, this setting needs to be set to
- * {@code true} to properly read it. By default, this value is {@code false} and the adjacency list is
+ * {@code true} to properly read it. By default, this value is {@code false} and the adjacency list is
* simply read as line delimited vertices.
* <p/>
* By setting this value to {@code true}, the generated JSON is no longer "splittable" by line and thus not
- * suitable for OLAP processing. Furthermore, reading this format of the JSON with
+ * suitable for OLAP processing. Furthermore, reading this format of the JSON with
* {@link GraphSONPartialReader#readGraph(InputStream, Graph)} or
* {@link GraphSONPartialReader#readVertices(InputStream, Function, Function, Direction)} requires that the
* entire JSON object be read into memory, so it is best saved for "small" graphs.
diff --git a/aai-core/src/main/java/org/onap/aai/dbgen/PropertyLimitDesc.java b/aai-core/src/main/java/org/onap/aai/dbgen/PropertyLimitDesc.java
index 2a1a4c07..1221c6cc 100644
--- a/aai-core/src/main/java/org/onap/aai/dbgen/PropertyLimitDesc.java
+++ b/aai-core/src/main/java/org/onap/aai/dbgen/PropertyLimitDesc.java
@@ -17,10 +17,9 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.dbgen;
public enum PropertyLimitDesc {
- SHOW_NONE,
- SHOW_ALL,
- SHOW_NAME_AND_KEYS_ONLY
+ SHOW_NONE, SHOW_ALL, SHOW_NAME_AND_KEYS_ONLY
}
diff --git a/aai-core/src/main/java/org/onap/aai/dbgen/SchemaGenerator.java b/aai-core/src/main/java/org/onap/aai/dbgen/SchemaGenerator.java
index 11b96ae1..bfd1f55b 100644
--- a/aai-core/src/main/java/org/onap/aai/dbgen/SchemaGenerator.java
+++ b/aai-core/src/main/java/org/onap/aai/dbgen/SchemaGenerator.java
@@ -17,8 +17,13 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.dbgen;
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
+import com.google.common.collect.Multimap;
+
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
@@ -26,160 +31,156 @@ import java.util.Optional;
import java.util.Set;
import org.apache.tinkerpop.gremlin.structure.Vertex;
+import org.janusgraph.core.Cardinality;
+import org.janusgraph.core.JanusGraph;
+import org.janusgraph.core.Multiplicity;
+import org.janusgraph.core.PropertyKey;
+import org.janusgraph.core.schema.JanusGraphManagement;
import org.onap.aai.config.SpringContextAware;
import org.onap.aai.db.props.AAIProperties;
import org.onap.aai.edges.EdgeIngestor;
+import org.onap.aai.edges.EdgeRule;
import org.onap.aai.edges.exceptions.EdgeRuleNotFoundException;
import org.onap.aai.introspection.*;
import org.onap.aai.logging.LogFormatTools;
import org.onap.aai.schema.enums.PropertyMetadata;
-import org.onap.aai.edges.EdgeRule;
import org.onap.aai.setup.SchemaVersions;
import org.onap.aai.util.AAIConfig;
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
-import com.google.common.collect.Multimap;
-import org.janusgraph.core.Cardinality;
-import org.janusgraph.core.Multiplicity;
-import org.janusgraph.core.PropertyKey;
-import org.janusgraph.core.JanusGraph;
-import org.janusgraph.core.schema.JanusGraphManagement;
-
public class SchemaGenerator {
- private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(SchemaGenerator.class);
-
- /**
- * Load schema into JanusGraph.
- *
- * @param graph
- * the graph
- * @param graphMgmt
- * the graph mgmt
- */
- public static void loadSchemaIntoJanusGraph(final JanusGraph graph, final JanusGraphManagement graphMgmt,
- String backend) {
-
- try {
- AAIConfig.init();
- } catch (Exception ex) {
- LOGGER.error(" ERROR - Could not run AAIConfig.init(). " + LogFormatTools.getStackTop(ex));
- //System.out.println(" ERROR - Could not run AAIConfig.init(). ");
- System.exit(1);
- }
-
- // NOTE - JanusGraph 0.5.3 doesn't keep a list of legal node Labels.
- // They are only used when a vertex is actually being created.
- // JanusGraph 1.1 will keep track (we think).
-
- // Use EdgeRules to make sure edgeLabels are defined in the db. NOTE:
- // the multiplicty used here is
- // always "MULTI". This is not the same as our internal "Many2Many",
- // "One2One", "One2Many" or "Many2One"
- // We use the same edge-label for edges between many different types of
- // nodes and our internal
- // multiplicty definitions depends on which two types of nodes are being
- // connected.
-
- Multimap<String, EdgeRule> edges = null;
- Set<String> labels = new HashSet<>();
-
- EdgeIngestor edgeIngestor = SpringContextAware.getBean(EdgeIngestor.class);
-
- try {
- edges = edgeIngestor.getAllCurrentRules();
- } catch (EdgeRuleNotFoundException e) {
- LOGGER.error("Unable to find all rules {}", LogFormatTools.getStackTop(e));
- }
-
- for (EdgeRule rule : edges.values()) {
- labels.add(rule.getLabel());
- }
-
- for (String label : labels) {
- if (graphMgmt.containsRelationType(label)) {
- String dmsg = " EdgeLabel [" + label + "] already existed. ";
- LOGGER.debug(dmsg);
- } else {
- String dmsg = "Making EdgeLabel: [" + label + "]";
- LOGGER.debug(dmsg);
- graphMgmt.makeEdgeLabel(label).multiplicity(Multiplicity.valueOf("MULTI")).make();
- }
- }
-
- Loader loader = LoaderUtil.getLatestVersion();
-
- Map<String, Introspector> objs = loader.getAllObjects();
- Map<String, PropertyKey> seenProps = new HashMap<>();
-
- for (Introspector obj : objs.values()) {
- for (String propName : obj.getProperties()) {
- String dbPropName = propName;
- Optional<String> alias = obj.getPropertyMetadata(propName, PropertyMetadata.DB_ALIAS);
- if (alias.isPresent()) {
- dbPropName = alias.get();
- }
- if (graphMgmt.containsRelationType(dbPropName)) {
- String dmsg = " PropertyKey [" + dbPropName + "] already existed in the DB. ";
- LOGGER.debug(dmsg);
- } else {
- Class<?> type = obj.getClass(propName);
- Cardinality cardinality = Cardinality.SINGLE;
- boolean process = false;
- if (obj.isListType(propName) && obj.isSimpleGenericType(propName)) {
- cardinality = Cardinality.SET;
- type = obj.getGenericTypeClass(propName);
- process = true;
- } else if (obj.isSimpleType(propName)) {
- process = true;
- }
-
- if (process) {
-
- String imsg = "Creating PropertyKey: [" + dbPropName + "], [" + type.getSimpleName() + "], ["
- + cardinality + "]";
- LOGGER.info(imsg);
- PropertyKey propK;
- if (!seenProps.containsKey(dbPropName)) {
- propK = graphMgmt.makePropertyKey(dbPropName).dataType(type).cardinality(cardinality)
- .make();
- seenProps.put(dbPropName, propK);
- } else {
- propK = seenProps.get(dbPropName);
- }
- if (graphMgmt.containsGraphIndex(dbPropName)) {
- String dmsg = " Index [" + dbPropName + "] already existed in the DB. ";
- LOGGER.debug(dmsg);
- } else {
- if (obj.getIndexedProperties().contains(propName)) {
- if (obj.getUniqueProperties().contains(propName)) {
- imsg = "Add Unique index for PropertyKey: [" + dbPropName + "]";
- LOGGER.info(imsg);
- graphMgmt.buildIndex(dbPropName, Vertex.class).addKey(propK).unique()
- .buildCompositeIndex();
- } else {
- imsg = "Add index for PropertyKey: [" + dbPropName + "]";
- LOGGER.info(imsg);
- graphMgmt.buildIndex(dbPropName, Vertex.class).addKey(propK).buildCompositeIndex();
- }
- } else {
- imsg = "No index added for PropertyKey: [" + dbPropName + "]";
- LOGGER.info(imsg);
- }
- }
- }
- }
- }
- }
-
- String imsg = "-- About to call graphMgmt commit";
- LOGGER.info(imsg);
- if(backend != null){
- LOGGER.info("Successfully loaded the schema to " + backend);
- }
-
- graphMgmt.commit();
- }
+ private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(SchemaGenerator.class);
+
+ /**
+ * Load schema into JanusGraph.
+ *
+ * @param graph
+ * the graph
+ * @param graphMgmt
+ * the graph mgmt
+ */
+ public static void loadSchemaIntoJanusGraph(final JanusGraph graph, final JanusGraphManagement graphMgmt,
+ String backend) {
+
+ try {
+ AAIConfig.init();
+ } catch (Exception ex) {
+ LOGGER.error(" ERROR - Could not run AAIConfig.init(). " + LogFormatTools.getStackTop(ex));
+ // System.out.println(" ERROR - Could not run AAIConfig.init(). ");
+ System.exit(1);
+ }
+
+ // NOTE - JanusGraph 0.5.3 doesn't keep a list of legal node Labels.
+ // They are only used when a vertex is actually being created.
+ // JanusGraph 1.1 will keep track (we think).
+
+ // Use EdgeRules to make sure edgeLabels are defined in the db. NOTE:
+ // the multiplicty used here is
+ // always "MULTI". This is not the same as our internal "Many2Many",
+ // "One2One", "One2Many" or "Many2One"
+ // We use the same edge-label for edges between many different types of
+ // nodes and our internal
+ // multiplicty definitions depends on which two types of nodes are being
+ // connected.
+
+ Multimap<String, EdgeRule> edges = null;
+ Set<String> labels = new HashSet<>();
+
+ EdgeIngestor edgeIngestor = SpringContextAware.getBean(EdgeIngestor.class);
+
+ try {
+ edges = edgeIngestor.getAllCurrentRules();
+ } catch (EdgeRuleNotFoundException e) {
+ LOGGER.error("Unable to find all rules {}", LogFormatTools.getStackTop(e));
+ }
+
+ for (EdgeRule rule : edges.values()) {
+ labels.add(rule.getLabel());
+ }
+
+ for (String label : labels) {
+ if (graphMgmt.containsRelationType(label)) {
+ String dmsg = " EdgeLabel [" + label + "] already existed. ";
+ LOGGER.debug(dmsg);
+ } else {
+ String dmsg = "Making EdgeLabel: [" + label + "]";
+ LOGGER.debug(dmsg);
+ graphMgmt.makeEdgeLabel(label).multiplicity(Multiplicity.valueOf("MULTI")).make();
+ }
+ }
+
+ Loader loader = LoaderUtil.getLatestVersion();
+
+ Map<String, Introspector> objs = loader.getAllObjects();
+ Map<String, PropertyKey> seenProps = new HashMap<>();
+
+ for (Introspector obj : objs.values()) {
+ for (String propName : obj.getProperties()) {
+ String dbPropName = propName;
+ Optional<String> alias = obj.getPropertyMetadata(propName, PropertyMetadata.DB_ALIAS);
+ if (alias.isPresent()) {
+ dbPropName = alias.get();
+ }
+ if (graphMgmt.containsRelationType(dbPropName)) {
+ String dmsg = " PropertyKey [" + dbPropName + "] already existed in the DB. ";
+ LOGGER.debug(dmsg);
+ } else {
+ Class<?> type = obj.getClass(propName);
+ Cardinality cardinality = Cardinality.SINGLE;
+ boolean process = false;
+ if (obj.isListType(propName) && obj.isSimpleGenericType(propName)) {
+ cardinality = Cardinality.SET;
+ type = obj.getGenericTypeClass(propName);
+ process = true;
+ } else if (obj.isSimpleType(propName)) {
+ process = true;
+ }
+
+ if (process) {
+
+ String imsg = "Creating PropertyKey: [" + dbPropName + "], [" + type.getSimpleName() + "], ["
+ + cardinality + "]";
+ LOGGER.info(imsg);
+ PropertyKey propK;
+ if (!seenProps.containsKey(dbPropName)) {
+ propK = graphMgmt.makePropertyKey(dbPropName).dataType(type).cardinality(cardinality)
+ .make();
+ seenProps.put(dbPropName, propK);
+ } else {
+ propK = seenProps.get(dbPropName);
+ }
+ if (graphMgmt.containsGraphIndex(dbPropName)) {
+ String dmsg = " Index [" + dbPropName + "] already existed in the DB. ";
+ LOGGER.debug(dmsg);
+ } else {
+ if (obj.getIndexedProperties().contains(propName)) {
+ if (obj.getUniqueProperties().contains(propName)) {
+ imsg = "Add Unique index for PropertyKey: [" + dbPropName + "]";
+ LOGGER.info(imsg);
+ graphMgmt.buildIndex(dbPropName, Vertex.class).addKey(propK).unique()
+ .buildCompositeIndex();
+ } else {
+ imsg = "Add index for PropertyKey: [" + dbPropName + "]";
+ LOGGER.info(imsg);
+ graphMgmt.buildIndex(dbPropName, Vertex.class).addKey(propK).buildCompositeIndex();
+ }
+ } else {
+ imsg = "No index added for PropertyKey: [" + dbPropName + "]";
+ LOGGER.info(imsg);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ String imsg = "-- About to call graphMgmt commit";
+ LOGGER.info(imsg);
+ if (backend != null) {
+ LOGGER.info("Successfully loaded the schema to " + backend);
+ }
+
+ graphMgmt.commit();
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/dbmap/AAIGraph.java b/aai-core/src/main/java/org/onap/aai/dbmap/AAIGraph.java
index 84218e85..0e7c0578 100644
--- a/aai-core/src/main/java/org/onap/aai/dbmap/AAIGraph.java
+++ b/aai-core/src/main/java/org/onap/aai/dbmap/AAIGraph.java
@@ -19,8 +19,12 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.dbmap;
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
+
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
@@ -33,16 +37,13 @@ import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.io.IoCore;
+import org.janusgraph.core.JanusGraph;
+import org.janusgraph.core.JanusGraphFactory;
+import org.janusgraph.core.schema.JanusGraphManagement;
import org.onap.aai.dbgen.SchemaGenerator;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.util.AAIConstants;
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
-import org.janusgraph.core.JanusGraphFactory;
-import org.janusgraph.core.JanusGraph;
-import org.janusgraph.core.schema.JanusGraphManagement;
-
/**
* Database Mapping class which acts as the middle man between the REST
* interface objects and JanusGraph DB objects. This class provides methods to commit
@@ -52,7 +53,7 @@ import org.janusgraph.core.schema.JanusGraphManagement;
* rules such as keys/required properties are handled by calling DBMeth methods
* which are driven by a specification file in json.
*
-
+ *
*/
public class AAIGraph {
@@ -63,8 +64,6 @@ public class AAIGraph {
private static final String CACHED_DB = "cached";
private static boolean isInit = false;
-
-
/**
* Instantiates a new AAI graph.
*/
@@ -85,14 +84,15 @@ public class AAIGraph {
throw new RuntimeException("Failed to instantiate graphs", e);
}
}
-
+
private static class Helper {
private static final AAIGraph INSTANCE = new AAIGraph();
+
private Helper() {
-
+
}
}
-
+
/**
* Gets the single instance of AAIGraph.
*
@@ -106,16 +106,18 @@ public class AAIGraph {
public static boolean isInit() {
return isInit;
}
-
+
private void loadGraph(String name, String configPath, String serviceName) throws Exception {
// Graph being opened by JanusGraphFactory is being placed in hashmap to be used later
// These graphs shouldn't be closed until the application shutdown
try {
- PropertiesConfiguration propertiesConfiguration = new AAIGraphConfig.Builder(configPath).forService(serviceName).withGraphType(name).buildConfiguration();
+ PropertiesConfiguration propertiesConfiguration = new AAIGraphConfig.Builder(configPath)
+ .forService(serviceName).withGraphType(name).buildConfiguration();
JanusGraph graph = JanusGraphFactory.open(propertiesConfiguration);
Properties graphProps = new Properties();
- propertiesConfiguration.getKeys().forEachRemaining(k -> graphProps.setProperty(k, propertiesConfiguration.getString(k)));
+ propertiesConfiguration.getKeys()
+ .forEachRemaining(k -> graphProps.setProperty(k, propertiesConfiguration.getString(k)));
if ("inmemory".equals(graphProps.get("storage.backend"))) {
// Load the propertyKeys, indexes and edge-Labels into the DB
@@ -149,8 +151,7 @@ public class AAIGraph {
transaction.tx().commit();
logAndPrint(logger, "Snapshot loaded to inmemory graph.");
} catch (Exception e) {
- logAndPrint(logger,
- "ERROR: Could not load datasnapshot to in memory graph. \n"
+ logAndPrint(logger, "ERROR: Could not load datasnapshot to in memory graph. \n"
+ ExceptionUtils.getFullStackTrace(e));
throw new RuntimeException(e);
}
@@ -161,9 +162,9 @@ public class AAIGraph {
private void loadSchema(JanusGraph graph) {
// Load the propertyKeys, indexes and edge-Labels into the DB
JanusGraphManagement graphMgt = graph.openManagement();
-
+
System.out.println("-- loading schema into JanusGraph");
- SchemaGenerator.loadSchemaIntoJanusGraph( graph, graphMgt, "inmemory");
+ SchemaGenerator.loadSchemaIntoJanusGraph(graph, graphMgt, "inmemory");
}
/**
@@ -181,16 +182,16 @@ public class AAIGraph {
public JanusGraph getGraph() {
return graphs.get(REALTIME_DB);
}
-
+
public void graphShutdown(DBConnectionType connectionType) {
-
+
graphs.get(this.getGraphName(connectionType)).close();
}
-
+
public JanusGraph getGraph(DBConnectionType connectionType) {
return graphs.get(this.getGraphName(connectionType));
}
-
+
private String getGraphName(DBConnectionType connectionType) {
String graphName = "";
if (DBConnectionType.CACHED.equals(connectionType)) {
@@ -198,10 +199,10 @@ public class AAIGraph {
} else if (DBConnectionType.REALTIME.equals(connectionType)) {
graphName = this.REALTIME_DB;
}
-
+
return graphName;
}
-
+
private void logAndPrint(EELFLogger logger, String msg) {
System.out.println(msg);
logger.info(msg);
diff --git a/aai-core/src/main/java/org/onap/aai/dbmap/AAIGraphConfig.java b/aai-core/src/main/java/org/onap/aai/dbmap/AAIGraphConfig.java
index eff7f0ec..d2f81610 100644
--- a/aai-core/src/main/java/org/onap/aai/dbmap/AAIGraphConfig.java
+++ b/aai-core/src/main/java/org/onap/aai/dbmap/AAIGraphConfig.java
@@ -17,18 +17,16 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.dbmap;
+import static org.janusgraph.graphdb.configuration.GraphDatabaseConfiguration.*;
+
import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterators;
-import org.janusgraph.diskstorage.configuration.ConfigElement;
-import org.janusgraph.diskstorage.configuration.backend.CommonsConfiguration;
-import org.apache.commons.configuration.ConfigurationException;
-import org.apache.commons.configuration.PropertiesConfiguration;
-import org.apache.commons.lang.StringUtils;
import java.io.File;
import java.io.FileNotFoundException;
@@ -37,68 +35,74 @@ import java.util.Iterator;
import java.util.Objects;
import java.util.regex.Pattern;
-import static org.janusgraph.graphdb.configuration.GraphDatabaseConfiguration.*;
+import org.apache.commons.configuration.ConfigurationException;
+import org.apache.commons.configuration.PropertiesConfiguration;
+import org.apache.commons.lang.StringUtils;
+import org.janusgraph.diskstorage.configuration.ConfigElement;
+import org.janusgraph.diskstorage.configuration.backend.CommonsConfiguration;
/**
* For building a config that JanusGraphFactory.open can use with an identifiable graph.unique-instance-id
*/
public class AAIGraphConfig {
- private static final EELFLogger logger = EELFManager.getInstance().getLogger(AAIGraphConfig.class);
-
- private AAIGraphConfig(){};
-
- public PropertiesConfiguration getCc(String configPath, String graphType, String service) throws ConfigurationException, FileNotFoundException {
+ private static final EELFLogger logger = EELFManager.getInstance().getLogger(AAIGraphConfig.class);
- PropertiesConfiguration cc = this.loadJanusGraphPropFile(configPath);
+ private AAIGraphConfig() {
+ };
- String uid = ManagementFactory.getRuntimeMXBean().getName() + "_" + service + "_" + graphType + "_" + System.currentTimeMillis();
- for (char c : ConfigElement.ILLEGAL_CHARS) {
- uid = StringUtils.replaceChars(uid, c,'_');
- }
+ public PropertiesConfiguration getCc(String configPath, String graphType, String service)
+ throws ConfigurationException, FileNotFoundException {
- cc.addProperty("graph.unique-instance-id", uid);
+ PropertiesConfiguration cc = this.loadJanusGraphPropFile(configPath);
- return cc;
- }
+ String uid = ManagementFactory.getRuntimeMXBean().getName() + "_" + service + "_" + graphType + "_"
+ + System.currentTimeMillis();
+ for (char c : ConfigElement.ILLEGAL_CHARS) {
+ uid = StringUtils.replaceChars(uid, c, '_');
+ }
+ cc.addProperty("graph.unique-instance-id", uid);
- private PropertiesConfiguration loadJanusGraphPropFile(String shortcutOrFile) throws ConfigurationException, FileNotFoundException {
- File file = new File(shortcutOrFile);
- if (file.exists()) {
- PropertiesConfiguration propertiesConfiguration = new PropertiesConfiguration();
- propertiesConfiguration.setAutoSave(false);
- propertiesConfiguration.load(shortcutOrFile);
- return propertiesConfiguration;
- } else {
- throw new FileNotFoundException(shortcutOrFile);
- }
- }
+ return cc;
+ }
- public static class Builder {
- private String configPath;
- private String graphType;
- private String service;
+ private PropertiesConfiguration loadJanusGraphPropFile(String shortcutOrFile)
+ throws ConfigurationException, FileNotFoundException {
+ File file = new File(shortcutOrFile);
+ if (file.exists()) {
+ PropertiesConfiguration propertiesConfiguration = new PropertiesConfiguration();
+ propertiesConfiguration.setAutoSave(false);
+ propertiesConfiguration.load(shortcutOrFile);
+ return propertiesConfiguration;
+ } else {
+ throw new FileNotFoundException(shortcutOrFile);
+ }
+ }
- public Builder(String configPath) {
- this.configPath = configPath;
- }
+ public static class Builder {
+ private String configPath;
+ private String graphType;
+ private String service;
- public Builder withGraphType(String graphType) {
- this.graphType = Objects.toString(graphType, "NA");
- return this;
- }
+ public Builder(String configPath) {
+ this.configPath = configPath;
+ }
- public Builder forService(String service) {
- this.service = Objects.toString(service, "NA");
- return this;
- }
+ public Builder withGraphType(String graphType) {
+ this.graphType = Objects.toString(graphType, "NA");
+ return this;
+ }
- public PropertiesConfiguration buildConfiguration() throws ConfigurationException, FileNotFoundException {
- return new AAIGraphConfig().getCc(this.configPath, this.graphType, this.service);
- }
+ public Builder forService(String service) {
+ this.service = Objects.toString(service, "NA");
+ return this;
+ }
- }
+ public PropertiesConfiguration buildConfiguration() throws ConfigurationException, FileNotFoundException {
+ return new AAIGraphConfig().getCc(this.configPath, this.graphType, this.service);
+ }
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/dbmap/DBConnectionType.java b/aai-core/src/main/java/org/onap/aai/dbmap/DBConnectionType.java
index f0b6c144..b100cad8 100644
--- a/aai-core/src/main/java/org/onap/aai/dbmap/DBConnectionType.java
+++ b/aai-core/src/main/java/org/onap/aai/dbmap/DBConnectionType.java
@@ -17,9 +17,9 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.dbmap;
public enum DBConnectionType {
- REALTIME,
- CACHED
+ REALTIME, CACHED
}
diff --git a/aai-core/src/main/java/org/onap/aai/dbmap/InMemoryGraph.java b/aai-core/src/main/java/org/onap/aai/dbmap/InMemoryGraph.java
index 84e15479..a5d3cda7 100644
--- a/aai-core/src/main/java/org/onap/aai/dbmap/InMemoryGraph.java
+++ b/aai-core/src/main/java/org/onap/aai/dbmap/InMemoryGraph.java
@@ -17,133 +17,129 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.dbmap;
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
+
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
-
import java.util.Properties;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.tinkerpop.gremlin.structure.io.IoCore;
-import org.onap.aai.dbgen.GraphSONPartialIO;
-import org.onap.aai.dbgen.SchemaGenerator;
-import org.onap.aai.logging.LogFormatTools;
-
-import org.janusgraph.core.JanusGraphFactory;
import org.janusgraph.core.JanusGraph;
+import org.janusgraph.core.JanusGraphFactory;
import org.janusgraph.core.JanusGraphTransaction;
import org.janusgraph.core.schema.JanusGraphManagement;
-
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
+import org.onap.aai.dbgen.GraphSONPartialIO;
+import org.onap.aai.dbgen.SchemaGenerator;
+import org.onap.aai.logging.LogFormatTools;
public class InMemoryGraph {
- private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(InMemoryGraph.class);
- private JanusGraph graph = null;
-
-
- public InMemoryGraph(Builder builder) throws IOException {
- /*
- * Create a In-memory graph
- */
- InputStream is = new FileInputStream(builder.propertyFile);
- try {
- graph = JanusGraphFactory.open(builder.propertyFile);
-
- Properties graphProps = new Properties();
- graphProps.load(is);
- JanusGraphManagement graphMgt = graph.openManagement();
- if(builder.isSchemaEnabled){
- LOGGER.info("Schema Enabled");
- SchemaGenerator.loadSchemaIntoJanusGraph(graph, graphMgt, graphProps.getProperty("storage.backend"));
+ private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(InMemoryGraph.class);
+ private JanusGraph graph = null;
+
+ public InMemoryGraph(Builder builder) throws IOException {
+ /*
+ * Create a In-memory graph
+ */
+ InputStream is = new FileInputStream(builder.propertyFile);
+ try {
+ graph = JanusGraphFactory.open(builder.propertyFile);
+
+ Properties graphProps = new Properties();
+ graphProps.load(is);
+ JanusGraphManagement graphMgt = graph.openManagement();
+ if (builder.isSchemaEnabled) {
+ LOGGER.info("Schema Enabled");
+ SchemaGenerator.loadSchemaIntoJanusGraph(graph, graphMgt, graphProps.getProperty("storage.backend"));
+ }
+ JanusGraphTransaction transaction = graph.newTransaction();
+ LOGGER.info("Loading snapshot");
+ if (builder.isPartialGraph) {
+ if ((builder.graphsonLocation != null) && (builder.graphsonLocation.length() > 0)) {
+ transaction.io(GraphSONPartialIO.build()).readGraph(builder.graphsonLocation);
+ } else {
+ transaction.io(GraphSONPartialIO.build()).reader().create().readGraph(builder.seqInputStream,
+ graph);
+ }
+ } else {
+ if ((builder.graphsonLocation != null) && (builder.graphsonLocation.length() > 0)) {
+ transaction.io(IoCore.graphson()).readGraph(builder.graphsonLocation);
+ } else {
+ transaction.io(IoCore.graphson()).reader().create().readGraph(builder.seqInputStream, graph);
+ }
}
- JanusGraphTransaction transaction = graph.newTransaction();
- LOGGER.info("Loading snapshot");
- if(builder.isPartialGraph){
- if ( (builder.graphsonLocation != null) && (builder.graphsonLocation.length() > 0) ) {
- transaction.io(GraphSONPartialIO.build()).readGraph(builder.graphsonLocation);
- }
- else {
- transaction.io(GraphSONPartialIO.build()).reader().create().readGraph(builder.seqInputStream, graph);
- }
- }
- else{
- if ( (builder.graphsonLocation != null) && (builder.graphsonLocation.length() > 0) ) {
- transaction.io(IoCore.graphson()).readGraph(builder.graphsonLocation);
- }
- else {
- transaction.io(IoCore.graphson()).reader().create().readGraph(builder.seqInputStream, graph);
- }
- }
- transaction.commit();
-
- } catch (Exception e) {
- // TODO : Changesysout to logger
- e.printStackTrace();
- LOGGER.error(
- "ERROR: Could not load datasnapshot to in memory graph. \n" + LogFormatTools.getStackTop(e));
- throw new IllegalStateException("Could not load datasnapshot to in memory graph");
-
- }
- finally{
- is.close();
- }
-
- }
-
- public static class Builder {
- private String graphsonLocation = "";
- private String propertyFile = "";
- private boolean isSchemaEnabled = false;
- private InputStream seqInputStream = null;
- private boolean isPartialGraph = false;
-
-
- /*
- * Builder constructor doesnt do anything
- */
- public Builder() {
- //Do nothing
- }
-
- public InMemoryGraph build(String graphsonFile, String propertyFile, boolean isSchemaEnabled) throws IOException {
- this.graphsonLocation = graphsonFile;
- this.propertyFile = propertyFile;
- this.isSchemaEnabled = isSchemaEnabled;
- return new InMemoryGraph(this);
- }
-
- public InMemoryGraph build(InputStream sis, String propertyFile, boolean isSchemaEnabled) throws IOException {
- this.graphsonLocation = null;
- this.propertyFile = propertyFile;
- this.isSchemaEnabled = isSchemaEnabled;
- this.seqInputStream = sis;
- return new InMemoryGraph(this);
- }
-
- public InMemoryGraph build(String graphsonFile, String propertyFile, boolean isSchemaEnabled, boolean isPartialGraph) throws IOException {
- this.graphsonLocation = graphsonFile;
- this.propertyFile = propertyFile;
- this.isSchemaEnabled = isSchemaEnabled;
- this.isPartialGraph = isPartialGraph;
- return new InMemoryGraph(this);
- }
-
- public InMemoryGraph build(InputStream sis, String propertyFile, boolean isSchemaEnabled, boolean isPartialGraph) throws IOException {
- this.graphsonLocation = null;
- this.propertyFile = propertyFile;
- this.isSchemaEnabled = isSchemaEnabled;
- this.seqInputStream = sis;
- this.isPartialGraph = isPartialGraph;
- return new InMemoryGraph(this);
- }
- }
-
- public JanusGraph getGraph() {
- return graph;
- }
+ transaction.commit();
+
+ } catch (Exception e) {
+ // TODO : Changesysout to logger
+ e.printStackTrace();
+ LOGGER.error("ERROR: Could not load datasnapshot to in memory graph. \n" + LogFormatTools.getStackTop(e));
+ throw new IllegalStateException("Could not load datasnapshot to in memory graph");
+
+ } finally {
+ is.close();
+ }
+
+ }
+
+ public static class Builder {
+ private String graphsonLocation = "";
+ private String propertyFile = "";
+ private boolean isSchemaEnabled = false;
+ private InputStream seqInputStream = null;
+ private boolean isPartialGraph = false;
+
+ /*
+ * Builder constructor doesnt do anything
+ */
+ public Builder() {
+ // Do nothing
+ }
+
+ public InMemoryGraph build(String graphsonFile, String propertyFile, boolean isSchemaEnabled)
+ throws IOException {
+ this.graphsonLocation = graphsonFile;
+ this.propertyFile = propertyFile;
+ this.isSchemaEnabled = isSchemaEnabled;
+ return new InMemoryGraph(this);
+ }
+
+ public InMemoryGraph build(InputStream sis, String propertyFile, boolean isSchemaEnabled) throws IOException {
+ this.graphsonLocation = null;
+ this.propertyFile = propertyFile;
+ this.isSchemaEnabled = isSchemaEnabled;
+ this.seqInputStream = sis;
+ return new InMemoryGraph(this);
+ }
+
+ public InMemoryGraph build(String graphsonFile, String propertyFile, boolean isSchemaEnabled,
+ boolean isPartialGraph) throws IOException {
+ this.graphsonLocation = graphsonFile;
+ this.propertyFile = propertyFile;
+ this.isSchemaEnabled = isSchemaEnabled;
+ this.isPartialGraph = isPartialGraph;
+ return new InMemoryGraph(this);
+ }
+
+ public InMemoryGraph build(InputStream sis, String propertyFile, boolean isSchemaEnabled,
+ boolean isPartialGraph) throws IOException {
+ this.graphsonLocation = null;
+ this.propertyFile = propertyFile;
+ this.isSchemaEnabled = isSchemaEnabled;
+ this.seqInputStream = sis;
+ this.isPartialGraph = isPartialGraph;
+ return new InMemoryGraph(this);
+ }
+ }
+
+ public JanusGraph getGraph() {
+ return graph;
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/dmaap/AAIDmaapEventJMSConsumer.java b/aai-core/src/main/java/org/onap/aai/dmaap/AAIDmaapEventJMSConsumer.java
index 14550891..44ff599f 100644
--- a/aai-core/src/main/java/org/onap/aai/dmaap/AAIDmaapEventJMSConsumer.java
+++ b/aai-core/src/main/java/org/onap/aai/dmaap/AAIDmaapEventJMSConsumer.java
@@ -19,16 +19,20 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.dmaap;
import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
+
import java.util.Objects;
import java.util.UUID;
+
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
+
import org.apache.log4j.MDC;
import org.json.JSONException;
import org.json.JSONObject;
@@ -66,7 +70,7 @@ public class AAIDmaapEventJMSConsumer implements MessageListener {
@Override
public void onMessage(Message message) {
- if(restTemplate == null){
+ if (restTemplate == null) {
return;
}
@@ -98,7 +102,7 @@ public class AAIDmaapEventJMSConsumer implements MessageListener {
eventName = jo.getString(EVENT_TOPIC);
}
- LoggingContext.targetEntity ("DMAAP");
+ LoggingContext.targetEntity("DMAAP");
if (jo.getString(EVENT_TOPIC) != null) {
eventName = jo.getString(EVENT_TOPIC);
LoggingContext.targetServiceName(eventName);
@@ -107,11 +111,11 @@ public class AAIDmaapEventJMSConsumer implements MessageListener {
LoggingContext.statusCode(StatusCode.COMPLETE);
LoggingContext.responseCode(LoggingContext.SUCCESS);
LOGGER.info(eventName + "|" + aaiEvent);
-
+
HttpEntity httpEntity = new HttpEntity(aaiEvent, httpHeaders);
String transportType = environment.getProperty("dmaap.ribbon.transportType", "http");
- String baseUrl = transportType + "://" + environment.getProperty("dmaap.ribbon.listOfServers");
+ String baseUrl = transportType + "://" + environment.getProperty("dmaap.ribbon.listOfServers");
String endpoint = "/events/" + eventName;
if ("AAI-EVENT".equals(eventName)) {
@@ -123,11 +127,13 @@ public class AAIDmaapEventJMSConsumer implements MessageListener {
} catch (JMSException | JSONException e) {
LoggingContext.statusCode(StatusCode.ERROR);
LoggingContext.responseCode(LoggingContext.DATA_ERROR);
- LOGGER.error("AAI_7350 Error parsing aaievent jsm message for sending to dmaap. {} {}", jsmMessageTxt, LogFormatTools.getStackTop(e));
+ LOGGER.error("AAI_7350 Error parsing aaievent jsm message for sending to dmaap. {} {}", jsmMessageTxt,
+ LogFormatTools.getStackTop(e));
} catch (Exception e) {
LoggingContext.statusCode(StatusCode.ERROR);
LoggingContext.responseCode(LoggingContext.AVAILABILITY_TIMEOUT_ERROR);
- LOGGER.error("AAI_7350 Error sending message to dmaap. {} {}" , jsmMessageTxt, LogFormatTools.getStackTop(e));
+ LOGGER.error("AAI_7350 Error sending message to dmaap. {} {}", jsmMessageTxt,
+ LogFormatTools.getStackTop(e));
}
}
diff --git a/aai-core/src/main/java/org/onap/aai/dmaap/AAIDmaapEventJMSProducer.java b/aai-core/src/main/java/org/onap/aai/dmaap/AAIDmaapEventJMSProducer.java
index 35e1a4a5..4036b907 100644
--- a/aai-core/src/main/java/org/onap/aai/dmaap/AAIDmaapEventJMSProducer.java
+++ b/aai-core/src/main/java/org/onap/aai/dmaap/AAIDmaapEventJMSProducer.java
@@ -19,6 +19,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.dmaap;
import org.apache.activemq.ActiveMQConnectionFactory;
@@ -33,16 +34,17 @@ public class AAIDmaapEventJMSProducer implements MessageProducer {
private JmsTemplate jmsTemplate;
public AAIDmaapEventJMSProducer() {
- if("true".equals(AAIConfig.get("aai.jms.enable", "true"))){
+ if ("true".equals(AAIConfig.get("aai.jms.enable", "true"))) {
this.jmsTemplate = new JmsTemplate();
String activeMqTcpUrl = System.getProperty("activemq.tcp.url", "tcp://localhost:61547");
- this.jmsTemplate.setConnectionFactory(new CachingConnectionFactory(new ActiveMQConnectionFactory(activeMqTcpUrl)));
+ this.jmsTemplate
+ .setConnectionFactory(new CachingConnectionFactory(new ActiveMQConnectionFactory(activeMqTcpUrl)));
this.jmsTemplate.setDefaultDestination(new ActiveMQQueue("IN_QUEUE"));
}
}
public void sendMessageToDefaultDestination(JSONObject finalJson) {
- if(jmsTemplate != null){
+ if (jmsTemplate != null) {
jmsTemplate.convertAndSend(finalJson.toString());
CachingConnectionFactory ccf = (CachingConnectionFactory) this.jmsTemplate.getConnectionFactory();
ccf.destroy();
diff --git a/aai-core/src/main/java/org/onap/aai/dmaap/MessageProducer.java b/aai-core/src/main/java/org/onap/aai/dmaap/MessageProducer.java
index c7edfd25..9b17d881 100644
--- a/aai-core/src/main/java/org/onap/aai/dmaap/MessageProducer.java
+++ b/aai-core/src/main/java/org/onap/aai/dmaap/MessageProducer.java
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.dmaap;
import org.json.JSONObject;
diff --git a/aai-core/src/main/java/org/onap/aai/domain/model/AAIResource.java b/aai-core/src/main/java/org/onap/aai/domain/model/AAIResource.java
index 3048c119..ddeabf07 100644
--- a/aai-core/src/main/java/org/onap/aai/domain/model/AAIResource.java
+++ b/aai-core/src/main/java/org/onap/aai/domain/model/AAIResource.java
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.domain.model;
import com.google.common.collect.Multimap;
@@ -24,651 +25,650 @@ import com.google.common.collect.Multimap;
import java.util.ArrayList;
import java.util.Map;
-
public class AAIResource {
- private AAIResource parent;
- private AAIResources children;
-
- private AAIResourceKeys aaiResourceKeys;
-
- private String namespace; // /Network/Vces/Vce/PortGroups/PortGroup/CvlanTags/CvlanTag -> "Network"
-
- private String resourceType; // node or container
- private String resourceClassName;
- private String simpleName; // Vce
- private String fullName; // /Network/Vces/Vce/PortGroups/PortGroup/CvlanTags/CvlanTag
- private String uri; // /network/vces/vce/{vnf-id}/port-groups/port-group/{interface-name}/cvlan-tags/cvlan-tag/{cvlan-tag}
- private String apiVersion;
- private String relationshipListClass;
- private String relationshipUtils;
-
- private Map<String, String> PropertyDataTypeMap;
- private Multimap<String, String> NodeMapIndexedProps;
- private Multimap<String, String> NodeAltKey1Props;
- private Multimap<String, String> NodeDependencies;
- private Multimap<String, String> NodeKeyProps;
- private Multimap<String, String> NodeReqProps;
- private Multimap<String, String> NodeNameProps;
- private Multimap<String, String> NodeUniqueProps;
-
- // if new dataTypes are added - make sure to update getAllFields() method below
- private ArrayList<String> stringFields;
- private ArrayList<String> stringListFields;
- private ArrayList<String> longFields;
- private ArrayList<String> intFields;
- private ArrayList<String> shortFields;
- private ArrayList<String> booleanFields;
-
- private ArrayList<String> requiredFields;
- private ArrayList<String> orderedFields;
- private AAIResource recurseToResource;
- private boolean allowDirectWrite;
- private boolean allowDirectRead;
- private ArrayList<String> autoGenUuidFields;
-
- /**
- * Gets the parent.
- *
- * @return the parent
- */
- public AAIResource getParent() {
- return parent;
- }
-
- /**
- * Sets the parent.
- *
- * @param parent the new parent
- */
- public void setParent(AAIResource parent) {
- this.parent = parent;
- }
-
- /**
- * Gets the children.
- *
- * @return the children
- */
- public AAIResources getChildren() {
- if (this.children == null) {
- this.children = new AAIResources();
- }
- return this.children;
- }
-
- /**
- * Gets the aai resource keys.
- *
- * @return the aai resource keys
- */
- public AAIResourceKeys getAaiResourceKeys() {
- if (aaiResourceKeys == null) {
- aaiResourceKeys = new AAIResourceKeys();
- }
- return aaiResourceKeys;
- }
-
- /**
- * Gets the namespace.
- *
- * @return the namespace
- */
- public String getNamespace() {
- return namespace;
- }
-
- /**
- * Sets the namespace.
- *
- * @param namespace the new namespace
- */
- public void setNamespace(String namespace) {
- this.namespace = namespace;
- }
-
- /**
- * Gets the resource type.
- *
- * @return the resource type
- */
- public String getResourceType() {
- return resourceType;
- }
-
- /**
- * Sets the resource type.
- *
- * @param resourceType the new resource type
- */
- public void setResourceType(String resourceType) {
- this.resourceType = resourceType;
- }
-
- /**
- * Gets the simple name.
- *
- * @return the simple name
- */
- public String getSimpleName() {
- return simpleName;
- }
-
- /**
- * Sets the simple name.
- *
- * @param simpleName the new simple name
- */
- public void setSimpleName(String simpleName) {
- this.simpleName = simpleName;
- }
-
- /**
- * Gets the full name.
- *
- * @return the full name
- */
- public String getFullName() {
- return fullName;
- }
-
- /**
- * Sets the full name.
- *
- * @param fullName the new full name
- */
- public void setFullName(String fullName) {
- this.fullName = fullName;
- }
-
- /**
- * Gets the uri.
- *
- * @return the uri
- */
- public String getUri() {
- return uri;
- }
-
- /**
- * Sets the uri.
- *
- * @param uri the new uri
- */
- public void setUri(String uri) {
- this.uri = uri;
- }
-
- /**
- * Gets the resource class name.
- *
- * @return the resource class name
- */
- public String getResourceClassName() {
- return resourceClassName;
- }
-
- /**
- * Sets the resource class name.
- *
- * @param resourceClassName the new resource class name
- */
- public void setResourceClassName(String resourceClassName) {
- this.resourceClassName = resourceClassName;
- }
-
- /**
- * Gets the property data type map.
- *
- * @return the property data type map
- */
- public Map<String, String> getPropertyDataTypeMap() {
- return PropertyDataTypeMap;
- }
-
- /**
- * Sets the property data type map.
- *
- * @param propertyDataTypeMap the property data type map
- */
- public void setPropertyDataTypeMap(Map<String, String> propertyDataTypeMap) {
- PropertyDataTypeMap = propertyDataTypeMap;
- }
-
- /**
- * Gets the node map indexed props.
- *
- * @return the node map indexed props
- */
- public Multimap<String, String> getNodeMapIndexedProps() {
- return NodeMapIndexedProps;
- }
-
- /**
- * Sets the node map indexed props.
- *
- * @param nodeMapIndexedProps the node map indexed props
- */
- public void setNodeMapIndexedProps(Multimap<String, String> nodeMapIndexedProps) {
- NodeMapIndexedProps = nodeMapIndexedProps;
- }
-
- /**
- * Gets the node key props.
- *
- * @return the node key props
- */
- public Multimap<String, String> getNodeKeyProps() {
- return NodeKeyProps;
- }
-
- /**
- * Sets the node key props.
- *
- * @param nodeKeyProps the node key props
- */
- public void setNodeKeyProps(Multimap<String, String> nodeKeyProps) {
- this.NodeKeyProps = nodeKeyProps;
- }
-
- /**
- * Gets the node name props.
- *
- * @return the node name props
- */
- public Multimap<String, String> getNodeNameProps() {
- return NodeNameProps;
- }
-
- /**
- * Sets the node name props.
- *
- * @param nodeNameProps the node name props
- */
- public void setNodeNameProps(Multimap<String, String> nodeNameProps) {
-
- NodeNameProps = nodeNameProps;
- }
-
- /**
- * Gets the node unique props.
- *
- * @return the node unique props
- */
- public Multimap<String, String> getNodeUniqueProps() {
- return NodeUniqueProps;
- }
-
- /**
- * Sets the node unique props.
- *
- * @param nodeUniqueProps the node unique props
- */
- public void setNodeUniqueProps(Multimap<String, String> nodeUniqueProps) {
- NodeUniqueProps = nodeUniqueProps;
- }
-
- /**
- * Gets the node req props.
- *
- * @return the node req props
- */
- public Multimap<String, String> getNodeReqProps() {
- return NodeReqProps;
- }
-
- /**
- * Sets the node req props.
- *
- * @param nodeReqProps the node req props
- */
- public void setNodeReqProps(Multimap<String, String> nodeReqProps) {
- NodeReqProps = nodeReqProps;
- }
-
- /**
- * Gets the api version.
- *
- * @return the api version
- */
- public String getApiVersion() {
- return apiVersion;
- }
-
- /**
- * Sets the api version.
- *
- * @param apiVersion the new api version
- */
- public void setApiVersion(String apiVersion) {
- this.apiVersion = apiVersion;
- }
-
- /**
- * Gets the relationship list class.
- *
- * @return the relationship list class
- */
- public String getRelationshipListClass() {
- return relationshipListClass;
- }
-
- /**
- * Sets the relationship list class.
- *
- * @param relationshipListClass the new relationship list class
- */
- public void setRelationshipListClass(String relationshipListClass) {
- this.relationshipListClass = relationshipListClass;
- }
-
- /**
- * Gets the relationship utils.
- *
- * @return the relationship utils
- */
- public String getRelationshipUtils() {
- return relationshipUtils;
- }
-
- /**
- * Sets the relationship utils.
- *
- * @param relationshipUtils the new relationship utils
- */
- public void setRelationshipUtils(String relationshipUtils) {
- this.relationshipUtils = relationshipUtils;
- }
-
- /**
- * Gets the string fields.
- *
- * @return the string fields
- */
- public ArrayList<String> getStringFields() {
- if (this.stringFields == null) {
- this.stringFields = new ArrayList<String>();
- }
- return this.stringFields;
- }
-
- /**
- * Sets the string fields.
- *
- * @param stringFields the new string fields
- */
- public void setStringFields(ArrayList<String> stringFields) {
- this.stringFields = stringFields;
- }
-
- /**
- * Gets the string list fields.
- *
- * @return the string list fields
- */
- public ArrayList<String> getStringListFields() {
- if (this.stringListFields == null) {
- this.stringListFields = new ArrayList<String>();
- }
- return this.stringListFields;
- }
-
- /**
- * Sets the string list fields.
- *
- * @param stringListFields the new string list fields
- */
- public void setStringListFields(ArrayList<String> stringListFields) {
- this.stringListFields = stringListFields;
- }
-
- /**
- * Gets the long fields.
- *
- * @return the long fields
- */
- public ArrayList<String> getLongFields() {
- if (this.longFields == null) {
- this.longFields = new ArrayList<String>();
- }
- return longFields;
- }
-
- /**
- * Sets the long fields.
- *
- * @param longFields the new long fields
- */
- public void setLongFields(ArrayList<String> longFields) {
- this.longFields = longFields;
- }
-
- /**
- * Gets the int fields.
- *
- * @return the int fields
- */
- public ArrayList<String> getIntFields() {
- if (this.intFields == null) {
- this.intFields = new ArrayList<String>();
- }
- return intFields;
- }
-
- /**
- * Sets the int fields.
- *
- * @param intFields the new int fields
- */
- public void setIntFields(ArrayList<String> intFields) {
- this.intFields = intFields;
- }
-
- /**
- * Gets the short fields.
- *
- * @return the short fields
- */
- public ArrayList<String> getShortFields() {
- if (this.shortFields == null) {
- this.shortFields = new ArrayList<String>();
- }
- return shortFields;
- }
-
- /**
- * Sets the short fields.
- *
- * @param shortFields the new short fields
- */
- public void setShortFields(ArrayList<String> shortFields) {
- this.shortFields = shortFields;
- }
-
- /**
- * Gets the boolean fields.
- *
- * @return the boolean fields
- */
- public ArrayList<String> getBooleanFields() {
- if (this.booleanFields == null) {
- this.booleanFields = new ArrayList<String>();
- }
- return booleanFields;
- }
-
- /**
- * Sets the boolean fields.
- *
- * @param booleanFields the new boolean fields
- */
- public void setBooleanFields(ArrayList<String> booleanFields) {
- this.booleanFields = booleanFields;
- }
-
- /**
- * Gets the required fields.
- *
- * @return the required fields
- */
- public ArrayList<String> getRequiredFields() {
- if (this.requiredFields == null) {
- this.requiredFields = new ArrayList<String>();
- }
- return requiredFields;
- }
-
- /**
- * Sets the required fields.
- *
- * @param requiredFields the new required fields
- */
- public void setRequiredFields(ArrayList<String> requiredFields) {
- this.requiredFields = requiredFields;
- }
-
- /**
- * Gets the ordered fields.
- *
- * @return the ordered fields
- */
- public ArrayList<String> getOrderedFields() {
- if (this.orderedFields == null) {
- this.orderedFields = new ArrayList<String>();
- }
- return this.orderedFields;
- }
-
- /**
- * Gets the all fields.
- *
- * @return the all fields
- */
- public ArrayList<String> getAllFields() {
-
- ArrayList<String> allFields = new ArrayList<String>();
- allFields.addAll(getBooleanFields());
- allFields.addAll(getStringListFields());
- allFields.addAll(getStringFields());
- allFields.addAll(getIntFields());
- allFields.addAll(getLongFields());
- allFields.addAll(getShortFields());
-
- return allFields;
- }
-
- /**
- * Gets the plural name.
- *
- * @return the plural name
- */
- public String getPluralName() {
-
- if (simpleName.contains("List") || simpleName.contains("-list") )
- return "";
- String[] fullNameList = getFullName().split("/");
- return fullNameList[fullNameList.length - 2];
- }
-
- /**
- * Sets the node alt key 1 props.
- *
- * @param _dbRulesNodeAltKey1Props the db rules node alt key 1 props
- */
- public void setNodeAltKey1Props(Multimap<String, String> _dbRulesNodeAltKey1Props) {
- this.NodeAltKey1Props = _dbRulesNodeAltKey1Props;
- }
-
- /**
- * Gets the node alt key 1 props.
- *
- * @return the node alt key 1 props
- */
- public Multimap<String,String> getNodeAltKey1Props() {
- return this.NodeAltKey1Props;
- }
-
- /**
- * Sets the node dependencies.
- *
- * @param _dbRulesNodeDependencies the db rules node dependencies
- */
- public void setNodeDependencies(Multimap<String, String> _dbRulesNodeDependencies) {
- this.NodeDependencies = _dbRulesNodeDependencies;
- }
-
- /**
- * Gets the node dependencies.
- *
- * @return the node dependencies
- */
- public Multimap<String,String> getNodeDependencies() {
- return this.NodeDependencies;
- }
-
- /**
- * Gets the recurse to resource.
- *
- * @return the recurse to resource
- */
- public AAIResource getRecurseToResource() {
- return this.recurseToResource;
- }
-
- /**
- * Sets the recurse to resource.
- *
- * @param ancestor the new recurse to resource
- */
- public void setRecurseToResource(AAIResource ancestor) {
- this.recurseToResource = ancestor;
-
- }
-
- /**
- * Sets the allow direct write.
- *
- * @param allowDirectWrite the new allow direct write
- */
- public void setAllowDirectWrite(boolean allowDirectWrite) {
- this.allowDirectWrite = allowDirectWrite;
- }
-
- /**
- * Checks if is allow direct write.
- *
- * @return true, if is allow direct write
- */
- public boolean isAllowDirectWrite() {
- return this.allowDirectWrite;
- }
-
- /**
- * Sets the allow direct read.
- *
- * @param allowDirectRead the new allow direct read
- */
- public void setAllowDirectRead(boolean allowDirectRead) {
- this.allowDirectRead = allowDirectRead;
- }
-
- /**
- * Checks if is allow direct read.
- *
- * @return true, if is allow direct read
- */
- public boolean isAllowDirectRead() {
- return this.allowDirectRead;
- }
-
- /**
- * Gets the auto gen uuid fields.
- *
- * @return the auto gen uuid fields
- */
- public ArrayList<String> getAutoGenUuidFields() {
- if (this.autoGenUuidFields == null) {
- this.autoGenUuidFields = new ArrayList<String>();
- }
- return this.autoGenUuidFields;
- }
-} \ No newline at end of file
+ private AAIResource parent;
+ private AAIResources children;
+
+ private AAIResourceKeys aaiResourceKeys;
+
+ private String namespace; // /Network/Vces/Vce/PortGroups/PortGroup/CvlanTags/CvlanTag -> "Network"
+
+ private String resourceType; // node or container
+ private String resourceClassName;
+ private String simpleName; // Vce
+ private String fullName; // /Network/Vces/Vce/PortGroups/PortGroup/CvlanTags/CvlanTag
+ private String uri; // /network/vces/vce/{vnf-id}/port-groups/port-group/{interface-name}/cvlan-tags/cvlan-tag/{cvlan-tag}
+ private String apiVersion;
+ private String relationshipListClass;
+ private String relationshipUtils;
+
+ private Map<String, String> PropertyDataTypeMap;
+ private Multimap<String, String> NodeMapIndexedProps;
+ private Multimap<String, String> NodeAltKey1Props;
+ private Multimap<String, String> NodeDependencies;
+ private Multimap<String, String> NodeKeyProps;
+ private Multimap<String, String> NodeReqProps;
+ private Multimap<String, String> NodeNameProps;
+ private Multimap<String, String> NodeUniqueProps;
+
+ // if new dataTypes are added - make sure to update getAllFields() method below
+ private ArrayList<String> stringFields;
+ private ArrayList<String> stringListFields;
+ private ArrayList<String> longFields;
+ private ArrayList<String> intFields;
+ private ArrayList<String> shortFields;
+ private ArrayList<String> booleanFields;
+
+ private ArrayList<String> requiredFields;
+ private ArrayList<String> orderedFields;
+ private AAIResource recurseToResource;
+ private boolean allowDirectWrite;
+ private boolean allowDirectRead;
+ private ArrayList<String> autoGenUuidFields;
+
+ /**
+ * Gets the parent.
+ *
+ * @return the parent
+ */
+ public AAIResource getParent() {
+ return parent;
+ }
+
+ /**
+ * Sets the parent.
+ *
+ * @param parent the new parent
+ */
+ public void setParent(AAIResource parent) {
+ this.parent = parent;
+ }
+
+ /**
+ * Gets the children.
+ *
+ * @return the children
+ */
+ public AAIResources getChildren() {
+ if (this.children == null) {
+ this.children = new AAIResources();
+ }
+ return this.children;
+ }
+
+ /**
+ * Gets the aai resource keys.
+ *
+ * @return the aai resource keys
+ */
+ public AAIResourceKeys getAaiResourceKeys() {
+ if (aaiResourceKeys == null) {
+ aaiResourceKeys = new AAIResourceKeys();
+ }
+ return aaiResourceKeys;
+ }
+
+ /**
+ * Gets the namespace.
+ *
+ * @return the namespace
+ */
+ public String getNamespace() {
+ return namespace;
+ }
+
+ /**
+ * Sets the namespace.
+ *
+ * @param namespace the new namespace
+ */
+ public void setNamespace(String namespace) {
+ this.namespace = namespace;
+ }
+
+ /**
+ * Gets the resource type.
+ *
+ * @return the resource type
+ */
+ public String getResourceType() {
+ return resourceType;
+ }
+
+ /**
+ * Sets the resource type.
+ *
+ * @param resourceType the new resource type
+ */
+ public void setResourceType(String resourceType) {
+ this.resourceType = resourceType;
+ }
+
+ /**
+ * Gets the simple name.
+ *
+ * @return the simple name
+ */
+ public String getSimpleName() {
+ return simpleName;
+ }
+
+ /**
+ * Sets the simple name.
+ *
+ * @param simpleName the new simple name
+ */
+ public void setSimpleName(String simpleName) {
+ this.simpleName = simpleName;
+ }
+
+ /**
+ * Gets the full name.
+ *
+ * @return the full name
+ */
+ public String getFullName() {
+ return fullName;
+ }
+
+ /**
+ * Sets the full name.
+ *
+ * @param fullName the new full name
+ */
+ public void setFullName(String fullName) {
+ this.fullName = fullName;
+ }
+
+ /**
+ * Gets the uri.
+ *
+ * @return the uri
+ */
+ public String getUri() {
+ return uri;
+ }
+
+ /**
+ * Sets the uri.
+ *
+ * @param uri the new uri
+ */
+ public void setUri(String uri) {
+ this.uri = uri;
+ }
+
+ /**
+ * Gets the resource class name.
+ *
+ * @return the resource class name
+ */
+ public String getResourceClassName() {
+ return resourceClassName;
+ }
+
+ /**
+ * Sets the resource class name.
+ *
+ * @param resourceClassName the new resource class name
+ */
+ public void setResourceClassName(String resourceClassName) {
+ this.resourceClassName = resourceClassName;
+ }
+
+ /**
+ * Gets the property data type map.
+ *
+ * @return the property data type map
+ */
+ public Map<String, String> getPropertyDataTypeMap() {
+ return PropertyDataTypeMap;
+ }
+
+ /**
+ * Sets the property data type map.
+ *
+ * @param propertyDataTypeMap the property data type map
+ */
+ public void setPropertyDataTypeMap(Map<String, String> propertyDataTypeMap) {
+ PropertyDataTypeMap = propertyDataTypeMap;
+ }
+
+ /**
+ * Gets the node map indexed props.
+ *
+ * @return the node map indexed props
+ */
+ public Multimap<String, String> getNodeMapIndexedProps() {
+ return NodeMapIndexedProps;
+ }
+
+ /**
+ * Sets the node map indexed props.
+ *
+ * @param nodeMapIndexedProps the node map indexed props
+ */
+ public void setNodeMapIndexedProps(Multimap<String, String> nodeMapIndexedProps) {
+ NodeMapIndexedProps = nodeMapIndexedProps;
+ }
+
+ /**
+ * Gets the node key props.
+ *
+ * @return the node key props
+ */
+ public Multimap<String, String> getNodeKeyProps() {
+ return NodeKeyProps;
+ }
+
+ /**
+ * Sets the node key props.
+ *
+ * @param nodeKeyProps the node key props
+ */
+ public void setNodeKeyProps(Multimap<String, String> nodeKeyProps) {
+ this.NodeKeyProps = nodeKeyProps;
+ }
+
+ /**
+ * Gets the node name props.
+ *
+ * @return the node name props
+ */
+ public Multimap<String, String> getNodeNameProps() {
+ return NodeNameProps;
+ }
+
+ /**
+ * Sets the node name props.
+ *
+ * @param nodeNameProps the node name props
+ */
+ public void setNodeNameProps(Multimap<String, String> nodeNameProps) {
+
+ NodeNameProps = nodeNameProps;
+ }
+
+ /**
+ * Gets the node unique props.
+ *
+ * @return the node unique props
+ */
+ public Multimap<String, String> getNodeUniqueProps() {
+ return NodeUniqueProps;
+ }
+
+ /**
+ * Sets the node unique props.
+ *
+ * @param nodeUniqueProps the node unique props
+ */
+ public void setNodeUniqueProps(Multimap<String, String> nodeUniqueProps) {
+ NodeUniqueProps = nodeUniqueProps;
+ }
+
+ /**
+ * Gets the node req props.
+ *
+ * @return the node req props
+ */
+ public Multimap<String, String> getNodeReqProps() {
+ return NodeReqProps;
+ }
+
+ /**
+ * Sets the node req props.
+ *
+ * @param nodeReqProps the node req props
+ */
+ public void setNodeReqProps(Multimap<String, String> nodeReqProps) {
+ NodeReqProps = nodeReqProps;
+ }
+
+ /**
+ * Gets the api version.
+ *
+ * @return the api version
+ */
+ public String getApiVersion() {
+ return apiVersion;
+ }
+
+ /**
+ * Sets the api version.
+ *
+ * @param apiVersion the new api version
+ */
+ public void setApiVersion(String apiVersion) {
+ this.apiVersion = apiVersion;
+ }
+
+ /**
+ * Gets the relationship list class.
+ *
+ * @return the relationship list class
+ */
+ public String getRelationshipListClass() {
+ return relationshipListClass;
+ }
+
+ /**
+ * Sets the relationship list class.
+ *
+ * @param relationshipListClass the new relationship list class
+ */
+ public void setRelationshipListClass(String relationshipListClass) {
+ this.relationshipListClass = relationshipListClass;
+ }
+
+ /**
+ * Gets the relationship utils.
+ *
+ * @return the relationship utils
+ */
+ public String getRelationshipUtils() {
+ return relationshipUtils;
+ }
+
+ /**
+ * Sets the relationship utils.
+ *
+ * @param relationshipUtils the new relationship utils
+ */
+ public void setRelationshipUtils(String relationshipUtils) {
+ this.relationshipUtils = relationshipUtils;
+ }
+
+ /**
+ * Gets the string fields.
+ *
+ * @return the string fields
+ */
+ public ArrayList<String> getStringFields() {
+ if (this.stringFields == null) {
+ this.stringFields = new ArrayList<String>();
+ }
+ return this.stringFields;
+ }
+
+ /**
+ * Sets the string fields.
+ *
+ * @param stringFields the new string fields
+ */
+ public void setStringFields(ArrayList<String> stringFields) {
+ this.stringFields = stringFields;
+ }
+
+ /**
+ * Gets the string list fields.
+ *
+ * @return the string list fields
+ */
+ public ArrayList<String> getStringListFields() {
+ if (this.stringListFields == null) {
+ this.stringListFields = new ArrayList<String>();
+ }
+ return this.stringListFields;
+ }
+
+ /**
+ * Sets the string list fields.
+ *
+ * @param stringListFields the new string list fields
+ */
+ public void setStringListFields(ArrayList<String> stringListFields) {
+ this.stringListFields = stringListFields;
+ }
+
+ /**
+ * Gets the long fields.
+ *
+ * @return the long fields
+ */
+ public ArrayList<String> getLongFields() {
+ if (this.longFields == null) {
+ this.longFields = new ArrayList<String>();
+ }
+ return longFields;
+ }
+
+ /**
+ * Sets the long fields.
+ *
+ * @param longFields the new long fields
+ */
+ public void setLongFields(ArrayList<String> longFields) {
+ this.longFields = longFields;
+ }
+
+ /**
+ * Gets the int fields.
+ *
+ * @return the int fields
+ */
+ public ArrayList<String> getIntFields() {
+ if (this.intFields == null) {
+ this.intFields = new ArrayList<String>();
+ }
+ return intFields;
+ }
+
+ /**
+ * Sets the int fields.
+ *
+ * @param intFields the new int fields
+ */
+ public void setIntFields(ArrayList<String> intFields) {
+ this.intFields = intFields;
+ }
+
+ /**
+ * Gets the short fields.
+ *
+ * @return the short fields
+ */
+ public ArrayList<String> getShortFields() {
+ if (this.shortFields == null) {
+ this.shortFields = new ArrayList<String>();
+ }
+ return shortFields;
+ }
+
+ /**
+ * Sets the short fields.
+ *
+ * @param shortFields the new short fields
+ */
+ public void setShortFields(ArrayList<String> shortFields) {
+ this.shortFields = shortFields;
+ }
+
+ /**
+ * Gets the boolean fields.
+ *
+ * @return the boolean fields
+ */
+ public ArrayList<String> getBooleanFields() {
+ if (this.booleanFields == null) {
+ this.booleanFields = new ArrayList<String>();
+ }
+ return booleanFields;
+ }
+
+ /**
+ * Sets the boolean fields.
+ *
+ * @param booleanFields the new boolean fields
+ */
+ public void setBooleanFields(ArrayList<String> booleanFields) {
+ this.booleanFields = booleanFields;
+ }
+
+ /**
+ * Gets the required fields.
+ *
+ * @return the required fields
+ */
+ public ArrayList<String> getRequiredFields() {
+ if (this.requiredFields == null) {
+ this.requiredFields = new ArrayList<String>();
+ }
+ return requiredFields;
+ }
+
+ /**
+ * Sets the required fields.
+ *
+ * @param requiredFields the new required fields
+ */
+ public void setRequiredFields(ArrayList<String> requiredFields) {
+ this.requiredFields = requiredFields;
+ }
+
+ /**
+ * Gets the ordered fields.
+ *
+ * @return the ordered fields
+ */
+ public ArrayList<String> getOrderedFields() {
+ if (this.orderedFields == null) {
+ this.orderedFields = new ArrayList<String>();
+ }
+ return this.orderedFields;
+ }
+
+ /**
+ * Gets the all fields.
+ *
+ * @return the all fields
+ */
+ public ArrayList<String> getAllFields() {
+
+ ArrayList<String> allFields = new ArrayList<String>();
+ allFields.addAll(getBooleanFields());
+ allFields.addAll(getStringListFields());
+ allFields.addAll(getStringFields());
+ allFields.addAll(getIntFields());
+ allFields.addAll(getLongFields());
+ allFields.addAll(getShortFields());
+
+ return allFields;
+ }
+
+ /**
+ * Gets the plural name.
+ *
+ * @return the plural name
+ */
+ public String getPluralName() {
+
+ if (simpleName.contains("List") || simpleName.contains("-list"))
+ return "";
+ String[] fullNameList = getFullName().split("/");
+ return fullNameList[fullNameList.length - 2];
+ }
+
+ /**
+ * Sets the node alt key 1 props.
+ *
+ * @param _dbRulesNodeAltKey1Props the db rules node alt key 1 props
+ */
+ public void setNodeAltKey1Props(Multimap<String, String> _dbRulesNodeAltKey1Props) {
+ this.NodeAltKey1Props = _dbRulesNodeAltKey1Props;
+ }
+
+ /**
+ * Gets the node alt key 1 props.
+ *
+ * @return the node alt key 1 props
+ */
+ public Multimap<String, String> getNodeAltKey1Props() {
+ return this.NodeAltKey1Props;
+ }
+
+ /**
+ * Sets the node dependencies.
+ *
+ * @param _dbRulesNodeDependencies the db rules node dependencies
+ */
+ public void setNodeDependencies(Multimap<String, String> _dbRulesNodeDependencies) {
+ this.NodeDependencies = _dbRulesNodeDependencies;
+ }
+
+ /**
+ * Gets the node dependencies.
+ *
+ * @return the node dependencies
+ */
+ public Multimap<String, String> getNodeDependencies() {
+ return this.NodeDependencies;
+ }
+
+ /**
+ * Gets the recurse to resource.
+ *
+ * @return the recurse to resource
+ */
+ public AAIResource getRecurseToResource() {
+ return this.recurseToResource;
+ }
+
+ /**
+ * Sets the recurse to resource.
+ *
+ * @param ancestor the new recurse to resource
+ */
+ public void setRecurseToResource(AAIResource ancestor) {
+ this.recurseToResource = ancestor;
+
+ }
+
+ /**
+ * Sets the allow direct write.
+ *
+ * @param allowDirectWrite the new allow direct write
+ */
+ public void setAllowDirectWrite(boolean allowDirectWrite) {
+ this.allowDirectWrite = allowDirectWrite;
+ }
+
+ /**
+ * Checks if is allow direct write.
+ *
+ * @return true, if is allow direct write
+ */
+ public boolean isAllowDirectWrite() {
+ return this.allowDirectWrite;
+ }
+
+ /**
+ * Sets the allow direct read.
+ *
+ * @param allowDirectRead the new allow direct read
+ */
+ public void setAllowDirectRead(boolean allowDirectRead) {
+ this.allowDirectRead = allowDirectRead;
+ }
+
+ /**
+ * Checks if is allow direct read.
+ *
+ * @return true, if is allow direct read
+ */
+ public boolean isAllowDirectRead() {
+ return this.allowDirectRead;
+ }
+
+ /**
+ * Gets the auto gen uuid fields.
+ *
+ * @return the auto gen uuid fields
+ */
+ public ArrayList<String> getAutoGenUuidFields() {
+ if (this.autoGenUuidFields == null) {
+ this.autoGenUuidFields = new ArrayList<String>();
+ }
+ return this.autoGenUuidFields;
+ }
+}
diff --git a/aai-core/src/main/java/org/onap/aai/domain/model/AAIResourceKey.java b/aai-core/src/main/java/org/onap/aai/domain/model/AAIResourceKey.java
index c85a17db..a61598f6 100644
--- a/aai-core/src/main/java/org/onap/aai/domain/model/AAIResourceKey.java
+++ b/aai-core/src/main/java/org/onap/aai/domain/model/AAIResourceKey.java
@@ -17,84 +17,85 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.domain.model;
public class AAIResourceKey {
- private String keyName;
- private String keyType;
- private String pathParamName;
- private String dnCamKeyName;
-
- /**
- * Gets the key name.
- *
- * @return the key name
- */
- public String getKeyName() {
- return keyName;
- }
-
- /**
- * Sets the key name.
- *
- * @param keyName the new key name
- */
- public void setKeyName(String keyName) {
- this.keyName = keyName;
- }
-
- /**
- * Gets the key type.
- *
- * @return the key type
- */
- public String getKeyType() {
- return keyType;
- }
-
- /**
- * Sets the key type.
- *
- * @param t the new key type
- */
- public void setKeyType(String t) {
- this.keyType = t;
- }
-
- /**
- * Gets the path param name.
- *
- * @return the path param name
- */
- public String getPathParamName() {
- return pathParamName;
- }
-
- /**
- * Sets the path param name.
- *
- * @param pathParamName the new path param name
- */
- public void setPathParamName(String pathParamName) {
- this.pathParamName = pathParamName;
- }
-
- /**
- * Gets the dn cam key name.
- *
- * @return the dn cam key name
- */
- public String getDnCamKeyName() {
- return dnCamKeyName;
- }
-
- /**
- * Sets the dn cam key name.
- *
- * @param dnCamKeyName the new dn cam key name
- */
- public void setDnCamKeyName(String dnCamKeyName) {
- this.dnCamKeyName = dnCamKeyName;
- }
-
+ private String keyName;
+ private String keyType;
+ private String pathParamName;
+ private String dnCamKeyName;
+
+ /**
+ * Gets the key name.
+ *
+ * @return the key name
+ */
+ public String getKeyName() {
+ return keyName;
+ }
+
+ /**
+ * Sets the key name.
+ *
+ * @param keyName the new key name
+ */
+ public void setKeyName(String keyName) {
+ this.keyName = keyName;
+ }
+
+ /**
+ * Gets the key type.
+ *
+ * @return the key type
+ */
+ public String getKeyType() {
+ return keyType;
+ }
+
+ /**
+ * Sets the key type.
+ *
+ * @param t the new key type
+ */
+ public void setKeyType(String t) {
+ this.keyType = t;
+ }
+
+ /**
+ * Gets the path param name.
+ *
+ * @return the path param name
+ */
+ public String getPathParamName() {
+ return pathParamName;
+ }
+
+ /**
+ * Sets the path param name.
+ *
+ * @param pathParamName the new path param name
+ */
+ public void setPathParamName(String pathParamName) {
+ this.pathParamName = pathParamName;
+ }
+
+ /**
+ * Gets the dn cam key name.
+ *
+ * @return the dn cam key name
+ */
+ public String getDnCamKeyName() {
+ return dnCamKeyName;
+ }
+
+ /**
+ * Sets the dn cam key name.
+ *
+ * @param dnCamKeyName the new dn cam key name
+ */
+ public void setDnCamKeyName(String dnCamKeyName) {
+ this.dnCamKeyName = dnCamKeyName;
+ }
+
}
diff --git a/aai-core/src/main/java/org/onap/aai/domain/model/AAIResourceKeys.java b/aai-core/src/main/java/org/onap/aai/domain/model/AAIResourceKeys.java
index a863eb47..64149513 100644
--- a/aai-core/src/main/java/org/onap/aai/domain/model/AAIResourceKeys.java
+++ b/aai-core/src/main/java/org/onap/aai/domain/model/AAIResourceKeys.java
@@ -17,23 +17,24 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.domain.model;
import java.util.ArrayList;
import java.util.List;
public class AAIResourceKeys {
- private List<AAIResourceKey> aaiResourceKey;
+ private List<AAIResourceKey> aaiResourceKey;
- /**
- * Gets the aai resource key.
- *
- * @return the aai resource key
- */
- public List<AAIResourceKey> getAaiResourceKey() {
- if (aaiResourceKey == null) {
- aaiResourceKey = new ArrayList<AAIResourceKey>();
- }
- return aaiResourceKey;
- }
+ /**
+ * Gets the aai resource key.
+ *
+ * @return the aai resource key
+ */
+ public List<AAIResourceKey> getAaiResourceKey() {
+ if (aaiResourceKey == null) {
+ aaiResourceKey = new ArrayList<AAIResourceKey>();
+ }
+ return aaiResourceKey;
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/domain/model/AAIResources.java b/aai-core/src/main/java/org/onap/aai/domain/model/AAIResources.java
index 15a8852a..4e5f0392 100644
--- a/aai-core/src/main/java/org/onap/aai/domain/model/AAIResources.java
+++ b/aai-core/src/main/java/org/onap/aai/domain/model/AAIResources.java
@@ -17,69 +17,69 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-package org.onap.aai.domain.model;
-import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext;
+package org.onap.aai.domain.model;
import java.util.HashMap;
+import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext;
+
public class AAIResources {
-
- private DynamicJAXBContext jaxbContext;
-
- private HashMap<String, AAIResource> aaiResources;
- private HashMap<String, AAIResource> resourceLookup;
-
-
- /**
- * Gets the aai resources.
- *
- * @return the aai resources
- */
- public HashMap<String, AAIResource> getAaiResources() {
- if (aaiResources == null) {
- aaiResources = new HashMap<String, AAIResource>();
- }
- return aaiResources;
- }
- /**
- * Gets the jaxb context.
- *
- * @return the jaxb context
- */
- public DynamicJAXBContext getJaxbContext() {
- return jaxbContext;
- }
+ private DynamicJAXBContext jaxbContext;
+
+ private HashMap<String, AAIResource> aaiResources;
+ private HashMap<String, AAIResource> resourceLookup;
+
+ /**
+ * Gets the aai resources.
+ *
+ * @return the aai resources
+ */
+ public HashMap<String, AAIResource> getAaiResources() {
+ if (aaiResources == null) {
+ aaiResources = new HashMap<String, AAIResource>();
+ }
+ return aaiResources;
+ }
+
+ /**
+ * Gets the jaxb context.
+ *
+ * @return the jaxb context
+ */
+ public DynamicJAXBContext getJaxbContext() {
+ return jaxbContext;
+ }
+
+ /**
+ * Sets the jaxb context.
+ *
+ * @param jaxbContext the new jaxb context
+ */
+ public void setJaxbContext(DynamicJAXBContext jaxbContext) {
+ this.jaxbContext = jaxbContext;
+ }
- /**
- * Sets the jaxb context.
- *
- * @param jaxbContext the new jaxb context
- */
- public void setJaxbContext(DynamicJAXBContext jaxbContext) {
- this.jaxbContext = jaxbContext;
- }
+ /**
+ * Gets the resource lookup.
+ *
+ * @return the resource lookup
+ */
+ public HashMap<String, AAIResource> getResourceLookup() {
+ if (resourceLookup == null) {
+ resourceLookup = new HashMap<String, AAIResource>();
+ }
+ return resourceLookup;
+ }
- /**
- * Gets the resource lookup.
- *
- * @return the resource lookup
- */
- public HashMap<String, AAIResource> getResourceLookup() {
- if (resourceLookup == null) {
- resourceLookup = new HashMap<String, AAIResource>();
- }
- return resourceLookup;
- }
+ /**
+ * Sets the resource lookup.
+ *
+ * @param resourceLookup the resource lookup
+ */
+ public void setResourceLookup(HashMap<String, AAIResource> resourceLookup) {
+ this.resourceLookup = resourceLookup;
+ }
- /**
- * Sets the resource lookup.
- *
- * @param resourceLookup the resource lookup
- */
- public void setResourceLookup(HashMap<String, AAIResource> resourceLookup) {
- this.resourceLookup = resourceLookup;
- }
-
-} \ No newline at end of file
+}
diff --git a/aai-core/src/main/java/org/onap/aai/domain/notificationEvent/NotificationEvent.java b/aai-core/src/main/java/org/onap/aai/domain/notificationEvent/NotificationEvent.java
index dca48496..d8b9b997 100644
--- a/aai-core/src/main/java/org/onap/aai/domain/notificationEvent/NotificationEvent.java
+++ b/aai-core/src/main/java/org/onap/aai/domain/notificationEvent/NotificationEvent.java
@@ -24,7 +24,6 @@
// Generated on: 2016.01.06 at 05:38:00 PM EST
//
-
package org.onap.aai.domain.notificationEvent;
import javax.xml.bind.annotation.XmlAccessType;
@@ -33,13 +32,15 @@ import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
-import org.w3c.dom.Element;
+import org.w3c.dom.Element;
/**
- * <p>Java class for anonymous complex type.
+ * <p>
+ * Java class for anonymous complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType>
@@ -80,16 +81,12 @@ import org.w3c.dom.Element;
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "", propOrder = {
- "cambriaPartition",
- "eventHeader",
- "entity"
-})
+@XmlType(name = "", propOrder = {"cambriaPartition", "eventHeader", "entity"})
@XmlRootElement(name = "NotificationEvent")
public class NotificationEvent {
- @XmlElement(name = "cambria.partition")
- protected String cambriaPartition;
+ @XmlElement(name = "cambria.partition")
+ protected String cambriaPartition;
@XmlElement(name = "event-header")
protected EventHeader eventHeader;
@XmlAnyElement(lax = true)
@@ -99,9 +96,9 @@ public class NotificationEvent {
* Gets the value of the eventHeader property.
*
* @return
- * possible object is
- * {@link EventHeader }
- *
+ * possible object is
+ * {@link EventHeader }
+ *
*/
public EventHeader getEventHeader() {
return eventHeader;
@@ -111,9 +108,9 @@ public class NotificationEvent {
* Sets the value of the eventHeader property.
*
* @param value
- * allowed object is
- * {@link EventHeader }
- *
+ * allowed object is
+ * {@link EventHeader }
+ *
*/
public void setEventHeader(EventHeader value) {
this.eventHeader = value;
@@ -123,10 +120,10 @@ public class NotificationEvent {
* Gets the value of the any property.
*
* @return
- * possible object is
- * {@link Object }
- * {@link Element }
- *
+ * possible object is
+ * {@link Object }
+ * {@link Element }
+ *
*/
public Object getEntity() {
return entity;
@@ -136,10 +133,10 @@ public class NotificationEvent {
* Sets the value of the any property.
*
* @param value
- * allowed object is
- * {@link Object }
- * {@link Element }
- *
+ * allowed object is
+ * {@link Object }
+ * {@link Element }
+ *
*/
public void setEntity(Object value) {
this.entity = value;
@@ -149,9 +146,9 @@ public class NotificationEvent {
* Gets the value of the cambriaPartition property.
*
* @return
- * possible object is
- * {@link String }
- *
+ * possible object is
+ * {@link String }
+ *
*/
public String getCambriaPartition() {
return cambriaPartition;
@@ -161,19 +158,20 @@ public class NotificationEvent {
* Sets the value of the cambriaPartition property.
*
* @param value
- * allowed object is
- * {@link String }
- *
+ * allowed object is
+ * {@link String }
+ *
*/
public void setCambriaPartition(String value) {
this.cambriaPartition = value;
}
-
/**
- * <p>Java class for anonymous complex type.
+ * <p>
+ * Java class for anonymous complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType>
@@ -202,21 +200,10 @@ public class NotificationEvent {
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
- @XmlType(name = "", propOrder = {
- "id",
- "timestamp",
- "sourceName",
- "domain",
- "sequenceNumber",
- "severity",
- "eventType",
- "version",
- "action",
- "entityType",
- "topEntityType",
- "entityLink",
- "status"
- })
+ @XmlType(
+ name = "",
+ propOrder = {"id", "timestamp", "sourceName", "domain", "sequenceNumber", "severity", "eventType",
+ "version", "action", "entityType", "topEntityType", "entityLink", "status"})
public static class EventHeader {
@XmlElement(required = true)
@@ -250,9 +237,9 @@ public class NotificationEvent {
* Gets the value of the id property.
*
* @return
- * possible object is
- * {@link String }
- *
+ * possible object is
+ * {@link String }
+ *
*/
public String getId() {
return id;
@@ -262,9 +249,9 @@ public class NotificationEvent {
* Sets the value of the id property.
*
* @param value
- * allowed object is
- * {@link String }
- *
+ * allowed object is
+ * {@link String }
+ *
*/
public void setId(String value) {
this.id = value;
@@ -274,9 +261,9 @@ public class NotificationEvent {
* Gets the value of the timestamp property.
*
* @return
- * possible object is
- * {@link String }
- *
+ * possible object is
+ * {@link String }
+ *
*/
public String getTimestamp() {
return timestamp;
@@ -286,9 +273,9 @@ public class NotificationEvent {
* Sets the value of the timestamp property.
*
* @param value
- * allowed object is
- * {@link String }
- *
+ * allowed object is
+ * {@link String }
+ *
*/
public void setTimestamp(String value) {
this.timestamp = value;
@@ -298,9 +285,9 @@ public class NotificationEvent {
* Gets the value of the sourceName property.
*
* @return
- * possible object is
- * {@link String }
- *
+ * possible object is
+ * {@link String }
+ *
*/
public String getSourceName() {
return sourceName;
@@ -310,9 +297,9 @@ public class NotificationEvent {
* Sets the value of the sourceName property.
*
* @param value
- * allowed object is
- * {@link String }
- *
+ * allowed object is
+ * {@link String }
+ *
*/
public void setSourceName(String value) {
this.sourceName = value;
@@ -322,9 +309,9 @@ public class NotificationEvent {
* Gets the value of the domain property.
*
* @return
- * possible object is
- * {@link String }
- *
+ * possible object is
+ * {@link String }
+ *
*/
public String getDomain() {
return domain;
@@ -334,9 +321,9 @@ public class NotificationEvent {
* Sets the value of the domain property.
*
* @param value
- * allowed object is
- * {@link String }
- *
+ * allowed object is
+ * {@link String }
+ *
*/
public void setDomain(String value) {
this.domain = value;
@@ -346,9 +333,9 @@ public class NotificationEvent {
* Gets the value of the sequenceNumber property.
*
* @return
- * possible object is
- * {@link String }
- *
+ * possible object is
+ * {@link String }
+ *
*/
public String getSequenceNumber() {
return sequenceNumber;
@@ -358,9 +345,9 @@ public class NotificationEvent {
* Sets the value of the sequenceNumber property.
*
* @param value
- * allowed object is
- * {@link String }
- *
+ * allowed object is
+ * {@link String }
+ *
*/
public void setSequenceNumber(String value) {
this.sequenceNumber = value;
@@ -370,9 +357,9 @@ public class NotificationEvent {
* Gets the value of the severity property.
*
* @return
- * possible object is
- * {@link String }
- *
+ * possible object is
+ * {@link String }
+ *
*/
public String getSeverity() {
return severity;
@@ -382,9 +369,9 @@ public class NotificationEvent {
* Sets the value of the severity property.
*
* @param value
- * allowed object is
- * {@link String }
- *
+ * allowed object is
+ * {@link String }
+ *
*/
public void setSeverity(String value) {
this.severity = value;
@@ -394,9 +381,9 @@ public class NotificationEvent {
* Gets the value of the eventType property.
*
* @return
- * possible object is
- * {@link String }
- *
+ * possible object is
+ * {@link String }
+ *
*/
public String getEventType() {
return eventType;
@@ -406,9 +393,9 @@ public class NotificationEvent {
* Sets the value of the eventType property.
*
* @param value
- * allowed object is
- * {@link String }
- *
+ * allowed object is
+ * {@link String }
+ *
*/
public void setEventType(String value) {
this.eventType = value;
@@ -418,9 +405,9 @@ public class NotificationEvent {
* Gets the value of the version property.
*
* @return
- * possible object is
- * {@link String }
- *
+ * possible object is
+ * {@link String }
+ *
*/
public String getVersion() {
return version;
@@ -430,9 +417,9 @@ public class NotificationEvent {
* Sets the value of the version property.
*
* @param value
- * allowed object is
- * {@link String }
- *
+ * allowed object is
+ * {@link String }
+ *
*/
public void setVersion(String value) {
this.version = value;
@@ -442,9 +429,9 @@ public class NotificationEvent {
* Gets the value of the action property.
*
* @return
- * possible object is
- * {@link String }
- *
+ * possible object is
+ * {@link String }
+ *
*/
public String getAction() {
return action;
@@ -454,9 +441,9 @@ public class NotificationEvent {
* Sets the value of the action property.
*
* @param value
- * allowed object is
- * {@link String }
- *
+ * allowed object is
+ * {@link String }
+ *
*/
public void setAction(String value) {
this.action = value;
@@ -466,9 +453,9 @@ public class NotificationEvent {
* Gets the value of the entityType property.
*
* @return
- * possible object is
- * {@link String }
- *
+ * possible object is
+ * {@link String }
+ *
*/
public String getEntityType() {
return entityType;
@@ -478,9 +465,9 @@ public class NotificationEvent {
* Sets the value of the entityType property.
*
* @param value
- * allowed object is
- * {@link String }
- *
+ * allowed object is
+ * {@link String }
+ *
*/
public void setEntityType(String value) {
this.entityType = value;
@@ -490,9 +477,9 @@ public class NotificationEvent {
* Gets the value of the topEntityType property.
*
* @return
- * possible object is
- * {@link String }
- *
+ * possible object is
+ * {@link String }
+ *
*/
public String getTopEntityType() {
return topEntityType;
@@ -502,9 +489,9 @@ public class NotificationEvent {
* Sets the value of the topEntityType property.
*
* @param value
- * allowed object is
- * {@link String }
- *
+ * allowed object is
+ * {@link String }
+ *
*/
public void setTopEntityType(String value) {
this.topEntityType = value;
@@ -514,9 +501,9 @@ public class NotificationEvent {
* Gets the value of the entityLink property.
*
* @return
- * possible object is
- * {@link String }
- *
+ * possible object is
+ * {@link String }
+ *
*/
public String getEntityLink() {
return entityLink;
@@ -526,9 +513,9 @@ public class NotificationEvent {
* Sets the value of the entityLink property.
*
* @param value
- * allowed object is
- * {@link String }
- *
+ * allowed object is
+ * {@link String }
+ *
*/
public void setEntityLink(String value) {
this.entityLink = value;
@@ -538,9 +525,9 @@ public class NotificationEvent {
* Gets the value of the status property.
*
* @return
- * possible object is
- * {@link String }
- *
+ * possible object is
+ * {@link String }
+ *
*/
public String getStatus() {
return status;
@@ -550,9 +537,9 @@ public class NotificationEvent {
* Sets the value of the status property.
*
* @param value
- * allowed object is
- * {@link String }
- *
+ * allowed object is
+ * {@link String }
+ *
*/
public void setStatus(String value) {
this.status = value;
diff --git a/aai-core/src/main/java/org/onap/aai/domain/notificationEvent/ObjectFactory.java b/aai-core/src/main/java/org/onap/aai/domain/notificationEvent/ObjectFactory.java
index 84f1920e..84f720d0 100644
--- a/aai-core/src/main/java/org/onap/aai/domain/notificationEvent/ObjectFactory.java
+++ b/aai-core/src/main/java/org/onap/aai/domain/notificationEvent/ObjectFactory.java
@@ -24,32 +24,31 @@
// Generated on: 2016.01.06 at 05:38:00 PM EST
//
-
package org.onap.aai.domain.notificationEvent;
import javax.xml.bind.annotation.XmlRegistry;
-
/**
- * This object contains factory methods for each
- * Java content interface and Java element interface
- * generated in the org.onap.aai.domain.notificationEvent package.
- * <p>An ObjectFactory allows you to programatically
- * construct new instances of the Java representation
- * for XML content. The Java representation of XML
- * content can consist of schema derived interfaces
- * and classes representing the binding of schema
- * type definitions, element declarations and model
- * groups. Factory methods for each of these are
+ * This object contains factory methods for each
+ * Java content interface and Java element interface
+ * generated in the org.onap.aai.domain.notificationEvent package.
+ * <p>
+ * An ObjectFactory allows you to programatically
+ * construct new instances of the Java representation
+ * for XML content. The Java representation of XML
+ * content can consist of schema derived interfaces
+ * and classes representing the binding of schema
+ * type definitions, element declarations and model
+ * groups. Factory methods for each of these are
* provided in this class.
*
*/
@XmlRegistry
public class ObjectFactory {
-
/**
- * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: org.onap.aai.domain.notificationEvent
+ * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package:
+ * org.onap.aai.domain.notificationEvent
*
*/
public ObjectFactory() {
diff --git a/aai-core/src/main/java/org/onap/aai/domain/responseMessage/AAIResponseMessage.java b/aai-core/src/main/java/org/onap/aai/domain/responseMessage/AAIResponseMessage.java
index 490666c4..6cd82eef 100644
--- a/aai-core/src/main/java/org/onap/aai/domain/responseMessage/AAIResponseMessage.java
+++ b/aai-core/src/main/java/org/onap/aai/domain/responseMessage/AAIResponseMessage.java
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.domain.responseMessage;
import javax.xml.bind.annotation.XmlAccessType;
@@ -26,12 +27,10 @@ import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "", propOrder = {
- "aaiResponseMessageCode",
- "aaiResponseMessageResourceType",
- "aaiResponseMessageDescription",
- "aaiResponseMessageData",
-})
+@XmlType(
+ name = "",
+ propOrder = {"aaiResponseMessageCode", "aaiResponseMessageResourceType", "aaiResponseMessageDescription",
+ "aaiResponseMessageData",})
@XmlRootElement(name = "aai-response-message", namespace = "http://org.onap.aai.inventory")
public class AAIResponseMessage {
@@ -43,82 +42,79 @@ public class AAIResponseMessage {
protected String aaiResponseMessageDescription;
@XmlElement(name = "aai-response-message-data")
protected AAIResponseMessageData aaiResponseMessageData;
-
- /**
- * Gets the aai response message code.
- *
- * @return the aai response message code
- */
- public String getAaiResponseMessageCode() {
- return aaiResponseMessageCode;
- }
-
- /**
- * Sets the aai response message code.
- *
- * @param aaiResponseMessageCode the new aai response message code
- */
- public void setAaiResponseMessageCode(String aaiResponseMessageCode) {
- this.aaiResponseMessageCode = aaiResponseMessageCode;
- }
-
- /**
- * Gets the aai response message resource type.
- *
- * @return the aai response message resource type
- */
- public String getAaiResponseMessageResourceType() {
- return aaiResponseMessageResourceType;
- }
-
- /**
- * Sets the aai response message resource type.
- *
- * @param aaiResponseMessageResourceType the new aai response message resource type
- */
- public void setAaiResponseMessageResourceType(
- String aaiResponseMessageResourceType) {
- this.aaiResponseMessageResourceType = aaiResponseMessageResourceType;
- }
-
- /**
- * Gets the aai response message description.
- *
- * @return the aai response message description
- */
- public String getAaiResponseMessageDescription() {
- return aaiResponseMessageDescription;
- }
-
- /**
- * Sets the aai response message description.
- *
- * @param aaiResponseMessageDescription the new aai response message description
- */
- public void setAaiResponseMessageDescription(
- String aaiResponseMessageDescription) {
- this.aaiResponseMessageDescription = aaiResponseMessageDescription;
- }
-
- /**
- * Gets the aai response message data.
- *
- * @return the aai response message data
- */
- public AAIResponseMessageData getAaiResponseMessageData() {
- if (aaiResponseMessageData == null) {
- aaiResponseMessageData = new AAIResponseMessageData();
- }
- return aaiResponseMessageData;
- }
-
- /**
- * Sets the AAI response message data.
- *
- * @param aaiResponseMessageData the new AAI response message data
- */
- public void setAAIResponseMessageData(
- AAIResponseMessageData aaiResponseMessageData) {
- this.aaiResponseMessageData = aaiResponseMessageData;
- }
+
+ /**
+ * Gets the aai response message code.
+ *
+ * @return the aai response message code
+ */
+ public String getAaiResponseMessageCode() {
+ return aaiResponseMessageCode;
+ }
+
+ /**
+ * Sets the aai response message code.
+ *
+ * @param aaiResponseMessageCode the new aai response message code
+ */
+ public void setAaiResponseMessageCode(String aaiResponseMessageCode) {
+ this.aaiResponseMessageCode = aaiResponseMessageCode;
+ }
+
+ /**
+ * Gets the aai response message resource type.
+ *
+ * @return the aai response message resource type
+ */
+ public String getAaiResponseMessageResourceType() {
+ return aaiResponseMessageResourceType;
+ }
+
+ /**
+ * Sets the aai response message resource type.
+ *
+ * @param aaiResponseMessageResourceType the new aai response message resource type
+ */
+ public void setAaiResponseMessageResourceType(String aaiResponseMessageResourceType) {
+ this.aaiResponseMessageResourceType = aaiResponseMessageResourceType;
+ }
+
+ /**
+ * Gets the aai response message description.
+ *
+ * @return the aai response message description
+ */
+ public String getAaiResponseMessageDescription() {
+ return aaiResponseMessageDescription;
+ }
+
+ /**
+ * Sets the aai response message description.
+ *
+ * @param aaiResponseMessageDescription the new aai response message description
+ */
+ public void setAaiResponseMessageDescription(String aaiResponseMessageDescription) {
+ this.aaiResponseMessageDescription = aaiResponseMessageDescription;
+ }
+
+ /**
+ * Gets the aai response message data.
+ *
+ * @return the aai response message data
+ */
+ public AAIResponseMessageData getAaiResponseMessageData() {
+ if (aaiResponseMessageData == null) {
+ aaiResponseMessageData = new AAIResponseMessageData();
+ }
+ return aaiResponseMessageData;
+ }
+
+ /**
+ * Sets the AAI response message data.
+ *
+ * @param aaiResponseMessageData the new AAI response message data
+ */
+ public void setAAIResponseMessageData(AAIResponseMessageData aaiResponseMessageData) {
+ this.aaiResponseMessageData = aaiResponseMessageData;
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/domain/responseMessage/AAIResponseMessageData.java b/aai-core/src/main/java/org/onap/aai/domain/responseMessage/AAIResponseMessageData.java
index 1f40906f..76b73642 100644
--- a/aai-core/src/main/java/org/onap/aai/domain/responseMessage/AAIResponseMessageData.java
+++ b/aai-core/src/main/java/org/onap/aai/domain/responseMessage/AAIResponseMessageData.java
@@ -19,8 +19,8 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-package org.onap.aai.domain.responseMessage;
+package org.onap.aai.domain.responseMessage;
//
//This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
@@ -40,10 +40,7 @@ import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "", propOrder = {
- "aaiResponseMessageDatum",
- "any"
-})
+@XmlType(name = "", propOrder = {"aaiResponseMessageDatum", "any"})
@XmlRootElement(name = "aai-response-message-data", namespace = "http://org.onap.aai.inventory")
public class AAIResponseMessageData {
diff --git a/aai-core/src/main/java/org/onap/aai/domain/responseMessage/AAIResponseMessageDatum.java b/aai-core/src/main/java/org/onap/aai/domain/responseMessage/AAIResponseMessageDatum.java
index 00ed166d..90c6e280 100644
--- a/aai-core/src/main/java/org/onap/aai/domain/responseMessage/AAIResponseMessageDatum.java
+++ b/aai-core/src/main/java/org/onap/aai/domain/responseMessage/AAIResponseMessageDatum.java
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.domain.responseMessage;
import javax.xml.bind.annotation.XmlAccessType;
@@ -26,9 +27,7 @@ import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "", propOrder = {
- "aaiResponseMessageDatumKey",
- "aaiResponseMessageDatumValue",
+@XmlType(name = "", propOrder = {"aaiResponseMessageDatumKey", "aaiResponseMessageDatumValue",
})
@@ -39,42 +38,41 @@ public class AAIResponseMessageDatum {
protected String aaiResponseMessageDatumKey;
@XmlElement(name = "aai-response-message-datum-value", required = true)
protected String aaiResponseMessageDatumValue;
-
- /**
- * Gets the aai response message datum key.
- *
- * @return the aai response message datum key
- */
- public String getAaiResponseMessageDatumKey() {
- return aaiResponseMessageDatumKey;
- }
-
- /**
- * Sets the aai response message datum key.
- *
- * @param aaiResponseMessageDatumKey the new aai response message datum key
- */
- public void setAaiResponseMessageDatumKey(String aaiResponseMessageDatumKey) {
- this.aaiResponseMessageDatumKey = aaiResponseMessageDatumKey;
- }
-
- /**
- * Gets the aai response message datum value.
- *
- * @return the aai response message datum value
- */
- public String getAaiResponseMessageDatumValue() {
- return aaiResponseMessageDatumValue;
- }
-
- /**
- * Sets the aai response message datum value.
- *
- * @param aaiResponseMessageDatumValue the new aai response message datum value
- */
- public void setAaiResponseMessageDatumValue(String aaiResponseMessageDatumValue) {
- this.aaiResponseMessageDatumValue = aaiResponseMessageDatumValue;
- }
-
-
+
+ /**
+ * Gets the aai response message datum key.
+ *
+ * @return the aai response message datum key
+ */
+ public String getAaiResponseMessageDatumKey() {
+ return aaiResponseMessageDatumKey;
+ }
+
+ /**
+ * Sets the aai response message datum key.
+ *
+ * @param aaiResponseMessageDatumKey the new aai response message datum key
+ */
+ public void setAaiResponseMessageDatumKey(String aaiResponseMessageDatumKey) {
+ this.aaiResponseMessageDatumKey = aaiResponseMessageDatumKey;
+ }
+
+ /**
+ * Gets the aai response message datum value.
+ *
+ * @return the aai response message datum value
+ */
+ public String getAaiResponseMessageDatumValue() {
+ return aaiResponseMessageDatumValue;
+ }
+
+ /**
+ * Sets the aai response message datum value.
+ *
+ * @param aaiResponseMessageDatumValue the new aai response message datum value
+ */
+ public void setAaiResponseMessageDatumValue(String aaiResponseMessageDatumValue) {
+ this.aaiResponseMessageDatumValue = aaiResponseMessageDatumValue;
+ }
+
}
diff --git a/aai-core/src/main/java/org/onap/aai/domain/responseMessage/AAIResponseMessages.java b/aai-core/src/main/java/org/onap/aai/domain/responseMessage/AAIResponseMessages.java
index d4ea5651..09bf30e3 100644
--- a/aai-core/src/main/java/org/onap/aai/domain/responseMessage/AAIResponseMessages.java
+++ b/aai-core/src/main/java/org/onap/aai/domain/responseMessage/AAIResponseMessages.java
@@ -17,8 +17,8 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-package org.onap.aai.domain.responseMessage;
+package org.onap.aai.domain.responseMessage;
//
//This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
@@ -38,9 +38,11 @@ import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
- * <p>Java class for anonymous complex type.
+ * <p>
+ * Java class for anonymous complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType>
@@ -79,39 +81,36 @@ import javax.xml.bind.annotation.XmlType;
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "", propOrder = {
- "aaiResponseMessage",
- "any"
-})
+@XmlType(name = "", propOrder = {"aaiResponseMessage", "any"})
@XmlRootElement(name = "aai-response-messages", namespace = "http://org.onap.aai.inventory")
public class AAIResponseMessages {
- @XmlElement(name = "aai-response-message")
- protected List<AAIResponseMessage> aaiResponseMessage;
- @XmlAnyElement(lax = true)
- protected List<Object> any;
+ @XmlElement(name = "aai-response-message")
+ protected List<AAIResponseMessage> aaiResponseMessage;
+ @XmlAnyElement(lax = true)
+ protected List<Object> any;
- /**
- * Gets the AAI response message.
- *
- * @return the AAI response message
- */
- public List<AAIResponseMessage> getAAIResponseMessage() {
- if (aaiResponseMessage == null) {
- aaiResponseMessage = new ArrayList<AAIResponseMessage>();
- }
- return this.aaiResponseMessage;
- }
+ /**
+ * Gets the AAI response message.
+ *
+ * @return the AAI response message
+ */
+ public List<AAIResponseMessage> getAAIResponseMessage() {
+ if (aaiResponseMessage == null) {
+ aaiResponseMessage = new ArrayList<AAIResponseMessage>();
+ }
+ return this.aaiResponseMessage;
+ }
- /**
- * Gets the any.
- *
- * @return the any
- */
- public List<Object> getAny() {
- if (any == null) {
- any = new ArrayList<Object>();
- }
- return this.any;
- }
+ /**
+ * Gets the any.
+ *
+ * @return the any
+ */
+ public List<Object> getAny() {
+ if (any == null) {
+ any = new ArrayList<Object>();
+ }
+ return this.any;
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/domain/responseMessage/package-info.java b/aai-core/src/main/java/org/onap/aai/domain/responseMessage/package-info.java
index e305196d..7c4dd4df 100644
--- a/aai-core/src/main/java/org/onap/aai/domain/responseMessage/package-info.java
+++ b/aai-core/src/main/java/org/onap/aai/domain/responseMessage/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,
@@ -18,14 +18,13 @@
* ============LICENSE_END=========================================================
*/
//
-// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
-// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
-// Any modifications to this file will be lost upon recompilation of the source schema.
-// Generated on: 2015.06.15 at 03:03:58 PM EDT
+// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
+// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
+// Any modifications to this file will be lost upon recompilation of the source schema.
+// Generated on: 2015.06.15 at 03:03:58 PM EDT
//
@javax.xml.bind.annotation.XmlSchema(
- namespace = "http://org.onap.aai.inventory",
- elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
+ namespace = "http://org.onap.aai.inventory",
+ elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package org.onap.aai.domain.responseMessage;
-
diff --git a/aai-core/src/main/java/org/onap/aai/domain/restPolicyException/Fault.java b/aai-core/src/main/java/org/onap/aai/domain/restPolicyException/Fault.java
index 69856873..55e45b64 100644
--- a/aai-core/src/main/java/org/onap/aai/domain/restPolicyException/Fault.java
+++ b/aai-core/src/main/java/org/onap/aai/domain/restPolicyException/Fault.java
@@ -24,22 +24,23 @@
// Generated on: 2015.02.11 at 04:54:39 PM EST
//
-
package org.onap.aai.domain.restPolicyException;
import java.util.ArrayList;
import java.util.List;
+
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
-
/**
- * <p>Java class for anonymous complex type.
+ * <p>
+ * Java class for anonymous complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType>
@@ -88,9 +89,7 @@ import javax.xml.bind.annotation.XmlType;
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "", propOrder = {
- "requestError"
-})
+@XmlType(name = "", propOrder = {"requestError"})
@XmlRootElement(name = "Fault")
public class Fault {
@@ -101,9 +100,9 @@ public class Fault {
* Gets the value of the requestError property.
*
* @return
- * possible object is
- * {@link RequestError }
- *
+ * possible object is
+ * {@link RequestError }
+ *
*/
public RequestError getRequestError() {
return requestError;
@@ -113,19 +112,20 @@ public class Fault {
* Sets the value of the requestError property.
*
* @param value
- * allowed object is
- * {@link RequestError }
- *
+ * allowed object is
+ * {@link RequestError }
+ *
*/
public void setRequestError(RequestError value) {
this.requestError = value;
}
-
/**
- * <p>Java class for anonymous complex type.
+ * <p>
+ * Java class for anonymous complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType>
@@ -164,9 +164,7 @@ public class Fault {
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
- @XmlType(name = "", propOrder = {
- "policyException"
- })
+ @XmlType(name = "", propOrder = {"policyException"})
public static class RequestError {
@XmlElement(required = true)
@@ -176,9 +174,9 @@ public class Fault {
* Gets the value of the policyException property.
*
* @return
- * possible object is
- * {@link PolicyException }
- *
+ * possible object is
+ * {@link PolicyException }
+ *
*/
public PolicyException getPolicyException() {
return policyException;
@@ -188,19 +186,20 @@ public class Fault {
* Sets the value of the policyException property.
*
* @param value
- * allowed object is
- * {@link PolicyException }
- *
+ * allowed object is
+ * {@link PolicyException }
+ *
*/
public void setPolicyException(PolicyException value) {
this.policyException = value;
}
-
/**
- * <p>Java class for anonymous complex type.
+ * <p>
+ * Java class for anonymous complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType>
@@ -229,11 +228,7 @@ public class Fault {
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
- @XmlType(name = "", propOrder = {
- "messageId",
- "text",
- "variables"
- })
+ @XmlType(name = "", propOrder = {"messageId", "text", "variables"})
public static class PolicyException {
@XmlElement(required = true)
@@ -247,9 +242,9 @@ public class Fault {
* Gets the value of the messageId property.
*
* @return
- * possible object is
- * {@link String }
- *
+ * possible object is
+ * {@link String }
+ *
*/
public String getMessageId() {
return messageId;
@@ -259,9 +254,9 @@ public class Fault {
* Sets the value of the messageId property.
*
* @param value
- * allowed object is
- * {@link String }
- *
+ * allowed object is
+ * {@link String }
+ *
*/
public void setMessageId(String value) {
this.messageId = value;
@@ -271,9 +266,9 @@ public class Fault {
* Gets the value of the text property.
*
* @return
- * possible object is
- * {@link String }
- *
+ * possible object is
+ * {@link String }
+ *
*/
public String getText() {
return text;
@@ -283,9 +278,9 @@ public class Fault {
* Sets the value of the text property.
*
* @param value
- * allowed object is
- * {@link String }
- *
+ * allowed object is
+ * {@link String }
+ *
*/
public void setText(String value) {
this.text = value;
@@ -295,9 +290,9 @@ public class Fault {
* Gets the value of the variables property.
*
* @return
- * possible object is
- * {@link Variables }
- *
+ * possible object is
+ * {@link Variables }
+ *
*/
public Variables getVariables() {
return variables;
@@ -307,19 +302,20 @@ public class Fault {
* Sets the value of the variables property.
*
* @param value
- * allowed object is
- * {@link Variables }
- *
+ * allowed object is
+ * {@link Variables }
+ *
*/
public void setVariables(Variables value) {
this.variables = value;
}
-
/**
- * <p>Java class for anonymous complex type.
+ * <p>
+ * Java class for anonymous complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType>
@@ -336,9 +332,7 @@ public class Fault {
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
- @XmlType(name = "", propOrder = {
- "variable"
- })
+ @XmlType(name = "", propOrder = {"variable"})
public static class Variables {
protected List<String> variable;
@@ -354,8 +348,9 @@ public class Fault {
*
* <p>
* For example, to add a new item, do as follows:
+ *
* <pre>
- * getVariable().add(newItem);
+ * getVariable().add(newItem);
* </pre>
*
*
diff --git a/aai-core/src/main/java/org/onap/aai/domain/restPolicyException/ObjectFactory.java b/aai-core/src/main/java/org/onap/aai/domain/restPolicyException/ObjectFactory.java
index 1cde4876..f85fe748 100644
--- a/aai-core/src/main/java/org/onap/aai/domain/restPolicyException/ObjectFactory.java
+++ b/aai-core/src/main/java/org/onap/aai/domain/restPolicyException/ObjectFactory.java
@@ -24,32 +24,31 @@
// Generated on: 2015.02.11 at 04:54:39 PM EST
//
-
package org.onap.aai.domain.restPolicyException;
import javax.xml.bind.annotation.XmlRegistry;
-
/**
- * This object contains factory methods for each
- * Java content interface and Java element interface
- * generated in the org.onap.aai.domain.restPolicyException package.
- * <p>An ObjectFactory allows you to programatically
- * construct new instances of the Java representation
- * for XML content. The Java representation of XML
- * content can consist of schema derived interfaces
- * and classes representing the binding of schema
- * type definitions, element declarations and model
- * groups. Factory methods for each of these are
+ * This object contains factory methods for each
+ * Java content interface and Java element interface
+ * generated in the org.onap.aai.domain.restPolicyException package.
+ * <p>
+ * An ObjectFactory allows you to programatically
+ * construct new instances of the Java representation
+ * for XML content. The Java representation of XML
+ * content can consist of schema derived interfaces
+ * and classes representing the binding of schema
+ * type definitions, element declarations and model
+ * groups. Factory methods for each of these are
* provided in this class.
*
*/
@XmlRegistry
public class ObjectFactory {
-
/**
- * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: org.onap.aai.domain.restPolicyException
+ * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package:
+ * org.onap.aai.domain.restPolicyException
*
*/
public ObjectFactory() {
diff --git a/aai-core/src/main/java/org/onap/aai/domain/restPolicyException/PolicyException.java b/aai-core/src/main/java/org/onap/aai/domain/restPolicyException/PolicyException.java
index b6e0d2e3..1aa2673a 100644
--- a/aai-core/src/main/java/org/onap/aai/domain/restPolicyException/PolicyException.java
+++ b/aai-core/src/main/java/org/onap/aai/domain/restPolicyException/PolicyException.java
@@ -17,13 +17,9 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.domain.restPolicyException;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
@@ -31,13 +27,16 @@ import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.annotation.Generated;
+
@JsonInclude(JsonInclude.Include.NON_NULL)
@Generated("org.jsonschema2pojo")
-@JsonPropertyOrder({
- "messageId",
- "text",
- "variables"
-})
+@JsonPropertyOrder({"messageId", "text", "variables"})
public class PolicyException {
@JsonProperty("messageId")
@@ -52,7 +51,7 @@ public class PolicyException {
/**
* Gets the message id.
*
- * @return The messageId
+ * @return The messageId
*/
@JsonProperty("messageId")
public String getMessageId() {
@@ -62,7 +61,7 @@ public class PolicyException {
/**
* Sets the message id.
*
- * @param messageId The messageId
+ * @param messageId The messageId
*/
@JsonProperty("messageId")
public void setMessageId(String messageId) {
@@ -72,7 +71,7 @@ public class PolicyException {
/**
* Gets the text.
*
- * @return The text
+ * @return The text
*/
@JsonProperty("text")
public String getText() {
@@ -82,7 +81,7 @@ public class PolicyException {
/**
* Sets the text.
*
- * @param text The text
+ * @param text The text
*/
@JsonProperty("text")
public void setText(String text) {
@@ -92,7 +91,7 @@ public class PolicyException {
/**
* Gets the variables.
*
- * @return The variables
+ * @return The variables
*/
@JsonProperty("variables")
public List<String> getVariables() {
@@ -102,7 +101,7 @@ public class PolicyException {
/**
* Sets the variables.
*
- * @param variables The variables
+ * @param variables The variables
*/
@JsonProperty("variables")
public void setVariables(List<String> variables) {
diff --git a/aai-core/src/main/java/org/onap/aai/domain/restPolicyException/RESTResponse.java b/aai-core/src/main/java/org/onap/aai/domain/restPolicyException/RESTResponse.java
index e6f98bc7..262ca855 100644
--- a/aai-core/src/main/java/org/onap/aai/domain/restPolicyException/RESTResponse.java
+++ b/aai-core/src/main/java/org/onap/aai/domain/restPolicyException/RESTResponse.java
@@ -17,11 +17,9 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.domain.restPolicyException;
-import java.util.HashMap;
-import java.util.Map;
-import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
@@ -29,11 +27,14 @@ import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.annotation.Generated;
+
@JsonInclude(JsonInclude.Include.NON_NULL)
@Generated("org.jsonschema2pojo")
-@JsonPropertyOrder({
- "requestError"
-})
+@JsonPropertyOrder({"requestError"})
public class RESTResponse {
@JsonProperty("requestError")
@@ -44,7 +45,7 @@ public class RESTResponse {
/**
* Gets the request error.
*
- * @return The requestError
+ * @return The requestError
*/
@JsonProperty("requestError")
public RequestError getRequestError() {
@@ -54,7 +55,7 @@ public class RESTResponse {
/**
* Sets the request error.
*
- * @param requestError The requestError
+ * @param requestError The requestError
*/
@JsonProperty("requestError")
public void setRequestError(RequestError requestError) {
diff --git a/aai-core/src/main/java/org/onap/aai/domain/restPolicyException/RequestError.java b/aai-core/src/main/java/org/onap/aai/domain/restPolicyException/RequestError.java
index 36245165..54580de7 100644
--- a/aai-core/src/main/java/org/onap/aai/domain/restPolicyException/RequestError.java
+++ b/aai-core/src/main/java/org/onap/aai/domain/restPolicyException/RequestError.java
@@ -17,11 +17,9 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.domain.restPolicyException;
-import java.util.HashMap;
-import java.util.Map;
-import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
@@ -29,11 +27,14 @@ import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.annotation.Generated;
+
@JsonInclude(JsonInclude.Include.NON_NULL)
@Generated("org.jsonschema2pojo")
-@JsonPropertyOrder({
- "policyException"
-})
+@JsonPropertyOrder({"policyException"})
public class RequestError {
@JsonProperty("policyException")
@@ -44,7 +45,7 @@ public class RequestError {
/**
* Gets the policy exception.
*
- * @return The policyException
+ * @return The policyException
*/
@JsonProperty("policyException")
public PolicyException getPolicyException() {
@@ -54,7 +55,7 @@ public class RequestError {
/**
* Sets the policy exception.
*
- * @param policyException The policyException
+ * @param policyException The policyException
*/
@JsonProperty("policyException")
public void setPolicyException(PolicyException policyException) {
@@ -83,4 +84,3 @@ public class RequestError {
}
}
-
diff --git a/aai-core/src/main/java/org/onap/aai/domain/restResponseInfo/Info.java b/aai-core/src/main/java/org/onap/aai/domain/restResponseInfo/Info.java
index 49d6190e..789fe926 100644
--- a/aai-core/src/main/java/org/onap/aai/domain/restResponseInfo/Info.java
+++ b/aai-core/src/main/java/org/onap/aai/domain/restResponseInfo/Info.java
@@ -24,22 +24,23 @@
// Generated on: 2015.10.28 at 05:53:17 PM EDT
//
-
package org.onap.aai.domain.restResponseInfo;
import java.util.ArrayList;
import java.util.List;
+
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
-
/**
- * <p>Java class for anonymous complex type.
+ * <p>
+ * Java class for anonymous complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType>
@@ -88,9 +89,7 @@ import javax.xml.bind.annotation.XmlType;
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "", propOrder = {
- "responseMessages"
-})
+@XmlType(name = "", propOrder = {"responseMessages"})
@XmlRootElement(name = "Info")
public class Info {
@@ -100,9 +99,9 @@ public class Info {
* Gets the value of the responseMessages property.
*
* @return
- * possible object is
- * {@link ResponseMessages }
- *
+ * possible object is
+ * {@link ResponseMessages }
+ *
*/
public ResponseMessages getResponseMessages() {
return responseMessages;
@@ -112,19 +111,20 @@ public class Info {
* Sets the value of the responseMessages property.
*
* @param value
- * allowed object is
- * {@link ResponseMessages }
- *
+ * allowed object is
+ * {@link ResponseMessages }
+ *
*/
public void setResponseMessages(ResponseMessages value) {
this.responseMessages = value;
}
-
/**
- * <p>Java class for anonymous complex type.
+ * <p>
+ * Java class for anonymous complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType>
@@ -163,9 +163,7 @@ public class Info {
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
- @XmlType(name = "", propOrder = {
- "responseMessage"
- })
+ @XmlType(name = "", propOrder = {"responseMessage"})
public static class ResponseMessages {
protected List<ResponseMessage> responseMessage;
@@ -181,8 +179,9 @@ public class Info {
*
* <p>
* For example, to add a new item, do as follows:
+ *
* <pre>
- * getResponseMessage().add(newItem);
+ * getResponseMessage().add(newItem);
* </pre>
*
*
@@ -199,11 +198,12 @@ public class Info {
return this.responseMessage;
}
-
/**
- * <p>Java class for anonymous complex type.
+ * <p>
+ * Java class for anonymous complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType>
@@ -232,11 +232,7 @@ public class Info {
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
- @XmlType(name = "", propOrder = {
- "messageId",
- "text",
- "variables"
- })
+ @XmlType(name = "", propOrder = {"messageId", "text", "variables"})
public static class ResponseMessage {
@XmlElement(required = true)
@@ -250,9 +246,9 @@ public class Info {
* Gets the value of the messageId property.
*
* @return
- * possible object is
- * {@link String }
- *
+ * possible object is
+ * {@link String }
+ *
*/
public String getMessageId() {
return messageId;
@@ -262,9 +258,9 @@ public class Info {
* Sets the value of the messageId property.
*
* @param value
- * allowed object is
- * {@link String }
- *
+ * allowed object is
+ * {@link String }
+ *
*/
public void setMessageId(String value) {
this.messageId = value;
@@ -274,9 +270,9 @@ public class Info {
* Gets the value of the text property.
*
* @return
- * possible object is
- * {@link String }
- *
+ * possible object is
+ * {@link String }
+ *
*/
public String getText() {
return text;
@@ -286,9 +282,9 @@ public class Info {
* Sets the value of the text property.
*
* @param value
- * allowed object is
- * {@link String }
- *
+ * allowed object is
+ * {@link String }
+ *
*/
public void setText(String value) {
this.text = value;
@@ -298,9 +294,9 @@ public class Info {
* Gets the value of the variables property.
*
* @return
- * possible object is
- * {@link Variables }
- *
+ * possible object is
+ * {@link Variables }
+ *
*/
public Variables getVariables() {
return variables;
@@ -310,19 +306,20 @@ public class Info {
* Sets the value of the variables property.
*
* @param value
- * allowed object is
- * {@link Variables }
- *
+ * allowed object is
+ * {@link Variables }
+ *
*/
public void setVariables(Variables value) {
this.variables = value;
}
-
/**
- * <p>Java class for anonymous complex type.
+ * <p>
+ * Java class for anonymous complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType>
@@ -339,9 +336,7 @@ public class Info {
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
- @XmlType(name = "", propOrder = {
- "variable"
- })
+ @XmlType(name = "", propOrder = {"variable"})
public static class Variables {
protected List<String> variable;
@@ -357,8 +352,9 @@ public class Info {
*
* <p>
* For example, to add a new item, do as follows:
+ *
* <pre>
- * getVariable().add(newItem);
+ * getVariable().add(newItem);
* </pre>
*
*
diff --git a/aai-core/src/main/java/org/onap/aai/domain/restResponseInfo/ObjectFactory.java b/aai-core/src/main/java/org/onap/aai/domain/restResponseInfo/ObjectFactory.java
index 6d6ddd0b..4efafb23 100644
--- a/aai-core/src/main/java/org/onap/aai/domain/restResponseInfo/ObjectFactory.java
+++ b/aai-core/src/main/java/org/onap/aai/domain/restResponseInfo/ObjectFactory.java
@@ -24,32 +24,31 @@
// Generated on: 2015.10.28 at 05:53:17 PM EDT
//
-
package org.onap.aai.domain.restResponseInfo;
import javax.xml.bind.annotation.XmlRegistry;
-
/**
- * This object contains factory methods for each
- * Java content interface and Java element interface
- * generated in the org.onap.aai.domain.restResponseInfo package.
- * <p>An ObjectFactory allows you to programatically
- * construct new instances of the Java representation
- * for XML content. The Java representation of XML
- * content can consist of schema derived interfaces
- * and classes representing the binding of schema
- * type definitions, element declarations and model
- * groups. Factory methods for each of these are
+ * This object contains factory methods for each
+ * Java content interface and Java element interface
+ * generated in the org.onap.aai.domain.restResponseInfo package.
+ * <p>
+ * An ObjectFactory allows you to programatically
+ * construct new instances of the Java representation
+ * for XML content. The Java representation of XML
+ * content can consist of schema derived interfaces
+ * and classes representing the binding of schema
+ * type definitions, element declarations and model
+ * groups. Factory methods for each of these are
* provided in this class.
*
*/
@XmlRegistry
public class ObjectFactory {
-
/**
- * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: org.onap.aai.domain.restResponseInfo
+ * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package:
+ * org.onap.aai.domain.restResponseInfo
*
*/
public ObjectFactory() {
diff --git a/aai-core/src/main/java/org/onap/aai/domain/restServiceException/Fault.java b/aai-core/src/main/java/org/onap/aai/domain/restServiceException/Fault.java
index dd0df4f0..3efa13c3 100644
--- a/aai-core/src/main/java/org/onap/aai/domain/restServiceException/Fault.java
+++ b/aai-core/src/main/java/org/onap/aai/domain/restServiceException/Fault.java
@@ -24,22 +24,23 @@
// Generated on: 2015.02.11 at 04:54:29 PM EST
//
-
package org.onap.aai.domain.restServiceException;
import java.util.ArrayList;
import java.util.List;
+
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
-
/**
- * <p>Java class for anonymous complex type.
+ * <p>
+ * Java class for anonymous complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType>
@@ -88,9 +89,7 @@ import javax.xml.bind.annotation.XmlType;
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "", propOrder = {
- "requestError"
-})
+@XmlType(name = "", propOrder = {"requestError"})
@XmlRootElement(name = "Fault")
public class Fault {
@@ -101,9 +100,9 @@ public class Fault {
* Gets the value of the requestError property.
*
* @return
- * possible object is
- * {@link RequestError }
- *
+ * possible object is
+ * {@link RequestError }
+ *
*/
public RequestError getRequestError() {
return requestError;
@@ -113,19 +112,20 @@ public class Fault {
* Sets the value of the requestError property.
*
* @param value
- * allowed object is
- * {@link RequestError }
- *
+ * allowed object is
+ * {@link RequestError }
+ *
*/
public void setRequestError(RequestError value) {
this.requestError = value;
}
-
/**
- * <p>Java class for anonymous complex type.
+ * <p>
+ * Java class for anonymous complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType>
@@ -164,9 +164,7 @@ public class Fault {
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
- @XmlType(name = "", propOrder = {
- "serviceException"
- })
+ @XmlType(name = "", propOrder = {"serviceException"})
public static class RequestError {
@XmlElement(required = true)
@@ -176,9 +174,9 @@ public class Fault {
* Gets the value of the serviceException property.
*
* @return
- * possible object is
- * {@link ServiceException }
- *
+ * possible object is
+ * {@link ServiceException }
+ *
*/
public ServiceException getServiceException() {
return serviceException;
@@ -188,19 +186,20 @@ public class Fault {
* Sets the value of the serviceException property.
*
* @param value
- * allowed object is
- * {@link ServiceException }
- *
+ * allowed object is
+ * {@link ServiceException }
+ *
*/
public void setServiceException(ServiceException value) {
this.serviceException = value;
}
-
/**
- * <p>Java class for anonymous complex type.
+ * <p>
+ * Java class for anonymous complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType>
@@ -229,11 +228,7 @@ public class Fault {
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
- @XmlType(name = "", propOrder = {
- "messageId",
- "text",
- "variables"
- })
+ @XmlType(name = "", propOrder = {"messageId", "text", "variables"})
public static class ServiceException {
@XmlElement(required = true)
@@ -247,9 +242,9 @@ public class Fault {
* Gets the value of the messageId property.
*
* @return
- * possible object is
- * {@link String }
- *
+ * possible object is
+ * {@link String }
+ *
*/
public String getMessageId() {
return messageId;
@@ -259,9 +254,9 @@ public class Fault {
* Sets the value of the messageId property.
*
* @param value
- * allowed object is
- * {@link String }
- *
+ * allowed object is
+ * {@link String }
+ *
*/
public void setMessageId(String value) {
this.messageId = value;
@@ -271,9 +266,9 @@ public class Fault {
* Gets the value of the text property.
*
* @return
- * possible object is
- * {@link String }
- *
+ * possible object is
+ * {@link String }
+ *
*/
public String getText() {
return text;
@@ -283,9 +278,9 @@ public class Fault {
* Sets the value of the text property.
*
* @param value
- * allowed object is
- * {@link String }
- *
+ * allowed object is
+ * {@link String }
+ *
*/
public void setText(String value) {
this.text = value;
@@ -295,9 +290,9 @@ public class Fault {
* Gets the value of the variables property.
*
* @return
- * possible object is
- * {@link Variables }
- *
+ * possible object is
+ * {@link Variables }
+ *
*/
public Variables getVariables() {
return variables;
@@ -307,19 +302,20 @@ public class Fault {
* Sets the value of the variables property.
*
* @param value
- * allowed object is
- * {@link Variables }
- *
+ * allowed object is
+ * {@link Variables }
+ *
*/
public void setVariables(Variables value) {
this.variables = value;
}
-
/**
- * <p>Java class for anonymous complex type.
+ * <p>
+ * Java class for anonymous complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType>
@@ -336,9 +332,7 @@ public class Fault {
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
- @XmlType(name = "", propOrder = {
- "variable"
- })
+ @XmlType(name = "", propOrder = {"variable"})
public static class Variables {
protected List<String> variable;
@@ -354,8 +348,9 @@ public class Fault {
*
* <p>
* For example, to add a new item, do as follows:
+ *
* <pre>
- * getVariable().add(newItem);
+ * getVariable().add(newItem);
* </pre>
*
*
diff --git a/aai-core/src/main/java/org/onap/aai/domain/restServiceException/ObjectFactory.java b/aai-core/src/main/java/org/onap/aai/domain/restServiceException/ObjectFactory.java
index 39581f3c..95eb2cba 100644
--- a/aai-core/src/main/java/org/onap/aai/domain/restServiceException/ObjectFactory.java
+++ b/aai-core/src/main/java/org/onap/aai/domain/restServiceException/ObjectFactory.java
@@ -24,32 +24,31 @@
// Generated on: 2015.02.11 at 04:54:29 PM EST
//
-
package org.onap.aai.domain.restServiceException;
import javax.xml.bind.annotation.XmlRegistry;
-
/**
- * This object contains factory methods for each
- * Java content interface and Java element interface
- * generated in the org.onap.aai.domain.restServiceException package.
- * <p>An ObjectFactory allows you to programatically
- * construct new instances of the Java representation
- * for XML content. The Java representation of XML
- * content can consist of schema derived interfaces
- * and classes representing the binding of schema
- * type definitions, element declarations and model
- * groups. Factory methods for each of these are
+ * This object contains factory methods for each
+ * Java content interface and Java element interface
+ * generated in the org.onap.aai.domain.restServiceException package.
+ * <p>
+ * An ObjectFactory allows you to programatically
+ * construct new instances of the Java representation
+ * for XML content. The Java representation of XML
+ * content can consist of schema derived interfaces
+ * and classes representing the binding of schema
+ * type definitions, element declarations and model
+ * groups. Factory methods for each of these are
* provided in this class.
*
*/
@XmlRegistry
public class ObjectFactory {
-
/**
- * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: org.onap.aai.domain.restServiceException
+ * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package:
+ * org.onap.aai.domain.restServiceException
*
*/
public ObjectFactory() {
diff --git a/aai-core/src/main/java/org/onap/aai/domain/restServiceException/RESTResponse.java b/aai-core/src/main/java/org/onap/aai/domain/restServiceException/RESTResponse.java
index 0a6ee1c2..09178937 100644
--- a/aai-core/src/main/java/org/onap/aai/domain/restServiceException/RESTResponse.java
+++ b/aai-core/src/main/java/org/onap/aai/domain/restServiceException/RESTResponse.java
@@ -17,11 +17,9 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.domain.restServiceException;
-import java.util.HashMap;
-import java.util.Map;
-import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
@@ -29,11 +27,14 @@ import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.annotation.Generated;
+
@JsonInclude(JsonInclude.Include.NON_NULL)
@Generated("org.jsonschema2pojo")
-@JsonPropertyOrder({
- "requestError"
-})
+@JsonPropertyOrder({"requestError"})
public class RESTResponse {
@JsonProperty("requestError")
@@ -44,7 +45,7 @@ public class RESTResponse {
/**
* Gets the request error.
*
- * @return The requestError
+ * @return The requestError
*/
@JsonProperty("requestError")
public RequestError getRequestError() {
@@ -54,7 +55,7 @@ public class RESTResponse {
/**
* Sets the request error.
*
- * @param requestError The requestError
+ * @param requestError The requestError
*/
@JsonProperty("requestError")
public void setRequestError(RequestError requestError) {
diff --git a/aai-core/src/main/java/org/onap/aai/domain/restServiceException/RequestError.java b/aai-core/src/main/java/org/onap/aai/domain/restServiceException/RequestError.java
index bf220775..38320218 100644
--- a/aai-core/src/main/java/org/onap/aai/domain/restServiceException/RequestError.java
+++ b/aai-core/src/main/java/org/onap/aai/domain/restServiceException/RequestError.java
@@ -17,11 +17,9 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.domain.restServiceException;
-import java.util.HashMap;
-import java.util.Map;
-import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
@@ -29,11 +27,14 @@ import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.annotation.Generated;
+
@JsonInclude(JsonInclude.Include.NON_NULL)
@Generated("org.jsonschema2pojo")
-@JsonPropertyOrder({
- "serviceException"
-})
+@JsonPropertyOrder({"serviceException"})
public class RequestError {
@JsonProperty("serviceException")
@@ -44,7 +45,7 @@ public class RequestError {
/**
* Gets the service exception.
*
- * @return The serviceException
+ * @return The serviceException
*/
@JsonProperty("serviceException")
public ServiceException getServiceException() {
@@ -54,7 +55,7 @@ public class RequestError {
/**
* Sets the service exception.
*
- * @param serviceException The serviceException
+ * @param serviceException The serviceException
*/
@JsonProperty("serviceException")
public void setServiceException(ServiceException serviceException) {
diff --git a/aai-core/src/main/java/org/onap/aai/domain/restServiceException/ServiceException.java b/aai-core/src/main/java/org/onap/aai/domain/restServiceException/ServiceException.java
index 10f136b9..ec658ce3 100644
--- a/aai-core/src/main/java/org/onap/aai/domain/restServiceException/ServiceException.java
+++ b/aai-core/src/main/java/org/onap/aai/domain/restServiceException/ServiceException.java
@@ -17,13 +17,9 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.domain.restServiceException;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
@@ -31,13 +27,16 @@ import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.annotation.Generated;
+
@JsonInclude(JsonInclude.Include.NON_NULL)
@Generated("org.jsonschema2pojo")
-@JsonPropertyOrder({
- "messageId",
- "text",
- "variables"
-})
+@JsonPropertyOrder({"messageId", "text", "variables"})
public class ServiceException {
@JsonProperty("messageId")
@@ -52,7 +51,7 @@ public class ServiceException {
/**
* Gets the message id.
*
- * @return The messageId
+ * @return The messageId
*/
@JsonProperty("messageId")
public String getMessageId() {
@@ -62,7 +61,7 @@ public class ServiceException {
/**
* Sets the message id.
*
- * @param messageId The messageId
+ * @param messageId The messageId
*/
@JsonProperty("messageId")
public void setMessageId(String messageId) {
@@ -72,7 +71,7 @@ public class ServiceException {
/**
* Gets the text.
*
- * @return The text
+ * @return The text
*/
@JsonProperty("text")
public String getText() {
@@ -82,7 +81,7 @@ public class ServiceException {
/**
* Sets the text.
*
- * @param text The text
+ * @param text The text
*/
@JsonProperty("text")
public void setText(String text) {
@@ -92,7 +91,7 @@ public class ServiceException {
/**
* Gets the variables.
*
- * @return The variables
+ * @return The variables
*/
@JsonProperty("variables")
public List<String> getVariables() {
@@ -102,7 +101,7 @@ public class ServiceException {
/**
* Sets the variables.
*
- * @param variables The variables
+ * @param variables The variables
*/
@JsonProperty("variables")
public void setVariables(List<String> variables) {
diff --git a/aai-core/src/main/java/org/onap/aai/domain/translog/TransactionLogEntries.java b/aai-core/src/main/java/org/onap/aai/domain/translog/TransactionLogEntries.java
index ae184d9b..7f02cb53 100644
--- a/aai-core/src/main/java/org/onap/aai/domain/translog/TransactionLogEntries.java
+++ b/aai-core/src/main/java/org/onap/aai/domain/translog/TransactionLogEntries.java
@@ -24,7 +24,6 @@
// Generated on: 2015.03.20 at 09:46:47 AM CDT
//
-
package org.onap.aai.domain.translog;
import java.util.ArrayList;
@@ -35,11 +34,12 @@ import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
-
/**
- * <p>Java class for anonymous complex type.
+ * <p>
+ * Java class for anonymous complex type.
*
- * <p>The following schema fragment specifies the expected content contained within this class.
+ * <p>
+ * The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType>
@@ -106,14 +106,12 @@ import javax.xml.bind.annotation.XmlType;
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "", propOrder = {
- "transactionLogEntries"
-})
+@XmlType(name = "", propOrder = {"transactionLogEntries"})
@XmlRootElement(name = "transaction-log-entries", namespace = "http://org.onap.aai.inventory")
public class TransactionLogEntries {
protected List<TransactionLogEntry> transactionLogEntries;
-
+
/**
* Gets the transaction log entries.
*
@@ -126,5 +124,4 @@ public class TransactionLogEntries {
return this.transactionLogEntries;
}
-
}
diff --git a/aai-core/src/main/java/org/onap/aai/domain/translog/TransactionLogEntry.java b/aai-core/src/main/java/org/onap/aai/domain/translog/TransactionLogEntry.java
index 843afb2f..2ce485be 100644
--- a/aai-core/src/main/java/org/onap/aai/domain/translog/TransactionLogEntry.java
+++ b/aai-core/src/main/java/org/onap/aai/domain/translog/TransactionLogEntry.java
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.domain.translog;
import javax.xml.bind.annotation.XmlAccessType;
@@ -28,410 +29,396 @@ import javax.xml.bind.annotation.XmlType;
import org.eclipse.persistence.oxm.annotations.XmlCDATA;
@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "", propOrder = {
- "transactionLogEntryId",
- "status",
- "rqstDate",
- "respDate",
- "sourceId",
- "resourceId",
- "resourceType",
- "rqstBuf",
- "respBuf",
- "notificationPayload",
- "notificationId",
- "notificationStatus",
- "notificationTopic",
- "notificationEntityLink",
- "notificationAction"
-})
+@XmlType(
+ name = "",
+ propOrder = {"transactionLogEntryId", "status", "rqstDate", "respDate", "sourceId", "resourceId",
+ "resourceType", "rqstBuf", "respBuf", "notificationPayload", "notificationId", "notificationStatus",
+ "notificationTopic", "notificationEntityLink", "notificationAction"})
@XmlRootElement(name = "transaction-log-entry", namespace = "http://org.onap.aai.inventory")
public class TransactionLogEntry {
- @XmlElement(name = "transaction-log-entry-id", required = true)
- protected String transactionLogEntryId;
- @XmlElement(name = "status")
- protected String status;
- @XmlElement(name = "rqst-date")
- protected String rqstDate;
- @XmlElement(name = "resp-date")
- protected String respDate;
- @XmlElement(name = "source-id")
- protected String sourceId;
- @XmlElement(name = "resource-id")
- protected String resourceId;
- @XmlElement(name = "resource-type")
- protected String resourceType;
- @XmlElement(name = "rqst-buf")
- protected String rqstBuf;
- @XmlElement(name = "resp-buf")
- protected String respBuf;
- @XmlElement(name = "notification-payload")
- protected String notificationPayload;
- @XmlElement(name = "notification-id")
- protected String notificationId;
- @XmlElement(name = "notification-status")
- protected String notificationStatus;
- @XmlElement(name = "notification-topic")
- private String notificationTopic;
- @XmlElement(name = "notification-entity-link")
- private String notificationEntityLink;
- @XmlElement(name = "notification-action")
- private String notificationAction;
-
- /**
- * Gets the value of the transcationLogEntryId property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getTransactionLogEntryId() {
- return transactionLogEntryId;
- }
-
- /**
- * Sets the value of the transactionLogEntryId property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setTransactionLogEntryId(String value) {
- this.transactionLogEntryId = value;
- }
-
- /**
- * Gets the value of the status property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getStatus() {
- return status;
- }
-
- /**
- * Sets the value of the status property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setStatus(String value) {
- this.status = value;
- }
-
- /**
- * Gets the value of the rqstDate property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
-
- public String getRqstDate() {
- return rqstDate;
- }
-
- /**
- * Sets the value of the rqstDate property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setRqstDate(String value) {
- this.rqstDate = value;
- }
-
-
- /**
- * Gets the value of the respDate property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
-
- public String getRespDate() {
- return respDate;
- }
-
- /**
- * Sets the value of the respDate property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setRespDate(String value) {
- this.respDate = value;
- }
- /**
- * Gets the value of the sourceId property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getSourceId() {
- return sourceId;
- }
-
- /**
- * Sets the value of the sourceId property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setSourceId(String value) {
- this.sourceId = value;
- }
-
- /**
- * Gets the value of the resourceId property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getResourceId() {
- return resourceId;
- }
-
- /**
- * Sets the value of the resourceId property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setResourceId(String value) {
- this.resourceId = value;
- }
-
- /**
- * Gets the value of the resourceType property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getResourceType() {
- return resourceType;
- }
-
- /**
- * Sets the value of the resourceType property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setResourceType(String value) {
- this.resourceType = value;
- }
-
- /**
- * Gets the value of the rqstBuf property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getRqstBuf() {
- return rqstBuf;
- }
-
- /**
- * Sets the value of the rqstBuf property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- @XmlCDATA
- public void setRqstBuf(String value) {
- this.rqstBuf = value;
- }
-
- /**
- * Gets the value of the respBuf property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getrespBuf() {
- return respBuf;
- }
-
- /**
- * Sets the value of the respBuf property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- @XmlCDATA
- public void setrespBuf(String value) {
- this.respBuf = value;
- }
-
- /**
- * Gets the value of the notificationPayload property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getNotificationPayload() {
- return notificationPayload;
- }
-
- /**
- * Sets the value of the notificationPayload property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- @XmlCDATA
- public void setNotificationPayload(String value) {
- this.notificationPayload = value;
- }
-
-
- /**
- * Gets the value of the notificationId property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getNotificationId() {
- return notificationId;
- }
-
- /**
- * Sets the value of the notificationId property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setNotificationId(String value) {
- this.notificationId = value;
- }
-
- /**
- * Gets the value of the notificationId property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getNotificationStatus() {
- return notificationStatus;
- }
-
- /**
- * Sets the value of the notificationId property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setNotificationStatus(String value) {
- this.notificationStatus = value;
- }
-
- /**
- * Gets the value of the notificationTopic property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getNotificationTopic() {
- return notificationTopic;
- }
-
- /**
- * Sets the value of the notificationTopic property.
- *
- * @param topic the new notification topic
- */
- public void setNotificationTopic(String topic) {
- this.notificationTopic = topic;
- }
-
- /**
- * Gets the value of the notificationEntityLink property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getNotificationEntityLink() {
- return notificationEntityLink;
- }
-
- /**
- * Sets the value of the notificationEntityLink property.
- *
- * @param entityLink the new notification entity link
- */
- public void setNotificationEntityLink(String entityLink) {
- this.notificationEntityLink = entityLink;
- }
-
- /**
- * Sets the value of the notificationAction property.
- *
- * @return the notification action
- */
- public String getNotificationAction() {
- return notificationAction;
- }
-
- /**
- * Sets the value of the notificationAction property.
- *
- * @param action the new notification action
- */
- public void setNotificationAction(String action) {
- this.notificationAction = action;
- }
-
+ @XmlElement(name = "transaction-log-entry-id", required = true)
+ protected String transactionLogEntryId;
+ @XmlElement(name = "status")
+ protected String status;
+ @XmlElement(name = "rqst-date")
+ protected String rqstDate;
+ @XmlElement(name = "resp-date")
+ protected String respDate;
+ @XmlElement(name = "source-id")
+ protected String sourceId;
+ @XmlElement(name = "resource-id")
+ protected String resourceId;
+ @XmlElement(name = "resource-type")
+ protected String resourceType;
+ @XmlElement(name = "rqst-buf")
+ protected String rqstBuf;
+ @XmlElement(name = "resp-buf")
+ protected String respBuf;
+ @XmlElement(name = "notification-payload")
+ protected String notificationPayload;
+ @XmlElement(name = "notification-id")
+ protected String notificationId;
+ @XmlElement(name = "notification-status")
+ protected String notificationStatus;
+ @XmlElement(name = "notification-topic")
+ private String notificationTopic;
+ @XmlElement(name = "notification-entity-link")
+ private String notificationEntityLink;
+ @XmlElement(name = "notification-action")
+ private String notificationAction;
+
+ /**
+ * Gets the value of the transcationLogEntryId property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getTransactionLogEntryId() {
+ return transactionLogEntryId;
+ }
+
+ /**
+ * Sets the value of the transactionLogEntryId property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setTransactionLogEntryId(String value) {
+ this.transactionLogEntryId = value;
+ }
+
+ /**
+ * Gets the value of the status property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getStatus() {
+ return status;
+ }
+
+ /**
+ * Sets the value of the status property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setStatus(String value) {
+ this.status = value;
+ }
+
+ /**
+ * Gets the value of the rqstDate property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+
+ public String getRqstDate() {
+ return rqstDate;
+ }
+
+ /**
+ * Sets the value of the rqstDate property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setRqstDate(String value) {
+ this.rqstDate = value;
+ }
+
+ /**
+ * Gets the value of the respDate property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+
+ public String getRespDate() {
+ return respDate;
+ }
+
+ /**
+ * Sets the value of the respDate property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setRespDate(String value) {
+ this.respDate = value;
+ }
+
+ /**
+ * Gets the value of the sourceId property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getSourceId() {
+ return sourceId;
+ }
+
+ /**
+ * Sets the value of the sourceId property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setSourceId(String value) {
+ this.sourceId = value;
+ }
+
+ /**
+ * Gets the value of the resourceId property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getResourceId() {
+ return resourceId;
+ }
+
+ /**
+ * Sets the value of the resourceId property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setResourceId(String value) {
+ this.resourceId = value;
+ }
+
+ /**
+ * Gets the value of the resourceType property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getResourceType() {
+ return resourceType;
+ }
+
+ /**
+ * Sets the value of the resourceType property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setResourceType(String value) {
+ this.resourceType = value;
+ }
+
+ /**
+ * Gets the value of the rqstBuf property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getRqstBuf() {
+ return rqstBuf;
+ }
+
+ /**
+ * Sets the value of the rqstBuf property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ @XmlCDATA
+ public void setRqstBuf(String value) {
+ this.rqstBuf = value;
+ }
+
+ /**
+ * Gets the value of the respBuf property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getrespBuf() {
+ return respBuf;
+ }
+
+ /**
+ * Sets the value of the respBuf property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ @XmlCDATA
+ public void setrespBuf(String value) {
+ this.respBuf = value;
+ }
+
+ /**
+ * Gets the value of the notificationPayload property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getNotificationPayload() {
+ return notificationPayload;
+ }
+
+ /**
+ * Sets the value of the notificationPayload property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ @XmlCDATA
+ public void setNotificationPayload(String value) {
+ this.notificationPayload = value;
+ }
+
+ /**
+ * Gets the value of the notificationId property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getNotificationId() {
+ return notificationId;
+ }
+
+ /**
+ * Sets the value of the notificationId property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setNotificationId(String value) {
+ this.notificationId = value;
+ }
+
+ /**
+ * Gets the value of the notificationId property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getNotificationStatus() {
+ return notificationStatus;
+ }
+
+ /**
+ * Sets the value of the notificationId property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setNotificationStatus(String value) {
+ this.notificationStatus = value;
+ }
+
+ /**
+ * Gets the value of the notificationTopic property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getNotificationTopic() {
+ return notificationTopic;
+ }
+
+ /**
+ * Sets the value of the notificationTopic property.
+ *
+ * @param topic the new notification topic
+ */
+ public void setNotificationTopic(String topic) {
+ this.notificationTopic = topic;
+ }
+
+ /**
+ * Gets the value of the notificationEntityLink property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getNotificationEntityLink() {
+ return notificationEntityLink;
+ }
+
+ /**
+ * Sets the value of the notificationEntityLink property.
+ *
+ * @param entityLink the new notification entity link
+ */
+ public void setNotificationEntityLink(String entityLink) {
+ this.notificationEntityLink = entityLink;
+ }
+
+ /**
+ * Sets the value of the notificationAction property.
+ *
+ * @return the notification action
+ */
+ public String getNotificationAction() {
+ return notificationAction;
+ }
+
+ /**
+ * Sets the value of the notificationAction property.
+ *
+ * @param action the new notification action
+ */
+ public void setNotificationAction(String action) {
+ this.notificationAction = action;
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/exceptions/AAIException.java b/aai-core/src/main/java/org/onap/aai/exceptions/AAIException.java
index 0851e719..bca4b48c 100644
--- a/aai-core/src/main/java/org/onap/aai/exceptions/AAIException.java
+++ b/aai-core/src/main/java/org/onap/aai/exceptions/AAIException.java
@@ -19,6 +19,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.exceptions;
import java.util.Collection;
@@ -30,8 +31,10 @@ import org.onap.aai.logging.ErrorObjectNotFoundException;
public class AAIException extends Exception {
- private static final String UPDATE_ERROR_PROPERTIES_BEFORE_USING_THIS_EXCEPTION_CODE = " - update error.properties before using this exception code";
- private static final String FAILED_TO_INSTANTIATE_AAI_EXCEPTION_WITH_CODE = "Failed to instantiate AAIException with code=";
+ private static final String UPDATE_ERROR_PROPERTIES_BEFORE_USING_THIS_EXCEPTION_CODE =
+ " - update error.properties before using this exception code";
+ private static final String FAILED_TO_INSTANTIATE_AAI_EXCEPTION_WITH_CODE =
+ "Failed to instantiate AAIException with code=";
public static final String DEFAULT_EXCEPTION_CODE = "AAI_4000";
private static final long serialVersionUID = 1L;
@@ -45,13 +48,13 @@ public class AAIException extends Exception {
public AAIException() {
super();
this.code = DEFAULT_EXCEPTION_CODE;
- this.templateVars = new LinkedList<String> ();
+ this.templateVars = new LinkedList<String>();
try {
this.errorObject = ErrorLogHelper.getErrorObject(getCode());
} catch (ErrorObjectNotFoundException e) {
throw new RuntimeException(FAILED_TO_INSTANTIATE_AAI_EXCEPTION_WITH_CODE + getCode()
- + UPDATE_ERROR_PROPERTIES_BEFORE_USING_THIS_EXCEPTION_CODE);
+ + UPDATE_ERROR_PROPERTIES_BEFORE_USING_THIS_EXCEPTION_CODE);
}
}
@@ -64,16 +67,16 @@ public class AAIException extends Exception {
super();
this.code = code;
- this.templateVars = new LinkedList<String> ();
+ this.templateVars = new LinkedList<String>();
try {
this.errorObject = ErrorLogHelper.getErrorObject(getCode());
} catch (ErrorObjectNotFoundException e) {
throw new RuntimeException(FAILED_TO_INSTANTIATE_AAI_EXCEPTION_WITH_CODE + getCode()
- + UPDATE_ERROR_PROPERTIES_BEFORE_USING_THIS_EXCEPTION_CODE);
+ + UPDATE_ERROR_PROPERTIES_BEFORE_USING_THIS_EXCEPTION_CODE);
}
}
-
+
/**
* Instantiates a new AAI exception.
*
@@ -84,14 +87,14 @@ public class AAIException extends Exception {
super(details);
this.code = code;
- this.templateVars = new LinkedList<String> ();
+ this.templateVars = new LinkedList<String>();
try {
this.errorObject = ErrorLogHelper.getErrorObject(getCode());
errorObject.setDetails(details);
} catch (ErrorObjectNotFoundException e) {
throw new RuntimeException(FAILED_TO_INSTANTIATE_AAI_EXCEPTION_WITH_CODE + getCode()
- + UPDATE_ERROR_PROPERTIES_BEFORE_USING_THIS_EXCEPTION_CODE);
+ + UPDATE_ERROR_PROPERTIES_BEFORE_USING_THIS_EXCEPTION_CODE);
}
}
@@ -105,16 +108,16 @@ public class AAIException extends Exception {
super(cause);
this.code = code;
- this.templateVars = new LinkedList<String> ();
+ this.templateVars = new LinkedList<String>();
try {
this.errorObject = ErrorLogHelper.getErrorObject(getCode());
} catch (ErrorObjectNotFoundException e) {
throw new RuntimeException(FAILED_TO_INSTANTIATE_AAI_EXCEPTION_WITH_CODE + getCode()
- + UPDATE_ERROR_PROPERTIES_BEFORE_USING_THIS_EXCEPTION_CODE);
+ + UPDATE_ERROR_PROPERTIES_BEFORE_USING_THIS_EXCEPTION_CODE);
}
}
-
+
/**
* Instantiates a new AAI exception.
*
@@ -126,16 +129,16 @@ public class AAIException extends Exception {
super(details, cause);
this.code = code;
- this.templateVars = new LinkedList<String> ();
+ this.templateVars = new LinkedList<String>();
try {
this.errorObject = ErrorLogHelper.getErrorObject(getCode());
} catch (ErrorObjectNotFoundException e) {
throw new RuntimeException(FAILED_TO_INSTANTIATE_AAI_EXCEPTION_WITH_CODE + getCode()
- + UPDATE_ERROR_PROPERTIES_BEFORE_USING_THIS_EXCEPTION_CODE);
+ + UPDATE_ERROR_PROPERTIES_BEFORE_USING_THIS_EXCEPTION_CODE);
}
}
-
+
public String getCode() {
return code;
}
diff --git a/aai-core/src/main/java/org/onap/aai/exceptions/AAIExceptionWithInfo.java b/aai-core/src/main/java/org/onap/aai/exceptions/AAIExceptionWithInfo.java
index 3a75ee95..e7f2901e 100644
--- a/aai-core/src/main/java/org/onap/aai/exceptions/AAIExceptionWithInfo.java
+++ b/aai-core/src/main/java/org/onap/aai/exceptions/AAIExceptionWithInfo.java
@@ -17,117 +17,119 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.exceptions;
import java.util.HashMap;
public class AAIExceptionWithInfo extends AAIException {
- HashMap<String, Object> infoHash;
- String info;
+ HashMap<String, Object> infoHash;
+ String info;
+
+ /**
+ * Instantiates a new AAI exception with info.
+ *
+ * @param infoHash the info hash
+ * @param info the info
+ */
+ public AAIExceptionWithInfo(HashMap<String, Object> infoHash, String info) {
+ super();
+ setInfoHash(infoHash);
+ setInfo(info);
+ }
+
+ /**
+ * Instantiates a new AAI exception with info.
+ *
+ * @param code the code
+ * @param infoHash the info hash
+ * @param info the info
+ */
+ public AAIExceptionWithInfo(String code, HashMap<String, Object> infoHash, String info) {
+ super(code);
+ setInfoHash(infoHash);
+ setInfo(info);
+ }
+
+ /**
+ * Instantiates a new AAI exception with info.
+ *
+ * @param code the code
+ * @param details the details
+ * @param infoHash the info hash
+ * @param info the info
+ */
+ public AAIExceptionWithInfo(String code, String details, HashMap<String, Object> infoHash, String info) {
+ super(code, details);
+ setInfoHash(infoHash);
+ setInfo(info);
+ }
+
+ /**
+ * Instantiates a new AAI exception with info.
+ *
+ * @param code the code
+ * @param cause the cause
+ * @param infoHash the info hash
+ * @param info the info
+ */
+ public AAIExceptionWithInfo(String code, Throwable cause, HashMap<String, Object> infoHash, String info) {
+ super(code, cause);
+ setInfoHash(infoHash);
+ setInfo(info);
+ }
- /**
- * Instantiates a new AAI exception with info.
- *
- * @param infoHash the info hash
- * @param info the info
- */
- public AAIExceptionWithInfo(HashMap<String, Object> infoHash, String info) {
- super();
- setInfoHash(infoHash);
- setInfo(info);
- }
+ /**
+ * Instantiates a new AAI exception with info.
+ *
+ * @param code the code
+ * @param cause the cause
+ * @param details the details
+ * @param infoHash the info hash
+ * @param info the info
+ */
+ public AAIExceptionWithInfo(String code, Throwable cause, String details, HashMap<String, Object> infoHash,
+ String info) {
+ super(code, cause, details);
+ setInfoHash(infoHash);
+ setInfo(info);
+ }
- /**
- * Instantiates a new AAI exception with info.
- *
- * @param code the code
- * @param infoHash the info hash
- * @param info the info
- */
- public AAIExceptionWithInfo(String code, HashMap<String, Object> infoHash, String info) {
- super(code);
- setInfoHash(infoHash);
- setInfo(info);
- }
-
- /**
- * Instantiates a new AAI exception with info.
- *
- * @param code the code
- * @param details the details
- * @param infoHash the info hash
- * @param info the info
- */
- public AAIExceptionWithInfo(String code, String details, HashMap<String, Object> infoHash, String info) {
- super(code, details);
- setInfoHash(infoHash);
- setInfo(info);
- }
+ /**
+ * Gets the info hash.
+ *
+ * @return the info hash
+ */
+ public HashMap<String, Object> getInfoHash() {
+ return infoHash;
+ }
- /**
- * Instantiates a new AAI exception with info.
- *
- * @param code the code
- * @param cause the cause
- * @param infoHash the info hash
- * @param info the info
- */
- public AAIExceptionWithInfo(String code, Throwable cause, HashMap<String, Object> infoHash, String info) {
- super(code, cause);
- setInfoHash(infoHash);
- setInfo(info);
- }
-
- /**
- * Instantiates a new AAI exception with info.
- *
- * @param code the code
- * @param cause the cause
- * @param details the details
- * @param infoHash the info hash
- * @param info the info
- */
- public AAIExceptionWithInfo(String code, Throwable cause, String details, HashMap<String, Object> infoHash, String info) {
- super(code, cause, details);
- setInfoHash(infoHash);
- setInfo(info);
- }
-
- /**
- * Gets the info hash.
- *
- * @return the info hash
- */
- public HashMap<String, Object> getInfoHash() {
- return infoHash;
- }
+ /**
+ * Sets the info hash.
+ *
+ * @param infoHash the info hash
+ */
+ public void setInfoHash(HashMap<String, Object> infoHash) {
+ this.infoHash = infoHash;
+ }
- /**
- * Sets the info hash.
- *
- * @param infoHash the info hash
- */
- public void setInfoHash(HashMap<String, Object> infoHash) {
- this.infoHash = infoHash;
- }
+ /**
+ * Gets the info.
+ *
+ * @return the info
+ */
+ public String getInfo() {
+ return info;
+ }
- /**
- * Gets the info.
- *
- * @return the info
- */
- public String getInfo() {
- return info;
- }
+ /**
+ * Sets the info.
+ *
+ * @param info the new info
+ */
+ public void setInfo(String info) {
+ this.info = info;
+ }
- /**
- * Sets the info.
- *
- * @param info the new info
- */
- public void setInfo(String info) {
- this.info = info;
- }
-
}
diff --git a/aai-core/src/main/java/org/onap/aai/extensions/AAIExtensionMap.java b/aai-core/src/main/java/org/onap/aai/extensions/AAIExtensionMap.java
index 7b125496..a6d7ac17 100644
--- a/aai-core/src/main/java/org/onap/aai/extensions/AAIExtensionMap.java
+++ b/aai-core/src/main/java/org/onap/aai/extensions/AAIExtensionMap.java
@@ -17,8 +17,17 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.extensions;
+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;
@@ -28,797 +37,791 @@ 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
- // =======================================================================
- // message | java.lang.String (RW)
- // ----------------------------------------------------------------------
- // templateVars | java.lang.ArrayList<String> (RW)
- // -----------------------------------------------------------------------
- // preExtException | java.lang.Exception (RW)
- // -----------------------------------------------------------------------
- // preExtErrorCallback | java.lang.reflect.Method (RW)
- // -----------------------------------------------------------------------
- // postExtException | java.lang.Exception (RW)
- // -----------------------------------------------------------------------
- // postExtErrorCallback | java.lang.reflect.Method (RW)
- // -----------------------------------------------------------------------
- // servletRequest | javax.servlet.http.HttpServletRequest (RO)
- // -----------------------------------------------------------------------
- // headers | javax.ws.rs.core.HttpHeaders (RO)
- // -----------------------------------------------------------------------
- // objFromRequestType | String (ex. ?org.onap.aai.domain.yang.Vce?) (RO)
- // -----------------------------------------------------------------------
- // objFromRequest | $TYPE {ObjFromRequestType) (RO)
- // -----------------------------------------------------------------------
- // preExtFailOnError | java.lang.Boolean (RW)
- // -----------------------------------------------------------------------
- // postExtFailOnError | java.lang.Boolean (RW)
- // -----------------------------------------------------------------------
- // preExtSkipErrorCallback | java.lang.Boolean (RW)
- // -----------------------------------------------------------------------
- // postExtSkipErrorCallback | java.lang.Boolean (RW)
- // -----------------------------------------------------------------------
- // graph | org.janusgraph.core.JanusGraph (RW)
- // -----------------------------------------------------------------------
- // objectFromResponse | Object
- // -----------------------------------------------------------------------
- // precheckAddedList | java.util.HashMap
- // -----------------------------------------------------------------------
- // precheckResponseMessages | org.onap.aai.extensions.AAIResponseMessages
- // =======================================================================
-
- private String message;
- private ArrayList<String> templateVars;
- private Exception preExtException;
- private Exception postExtException;
- private Method preExtErrorCallback;
- private Method postExtErrorCallback;
- private HttpServletRequest servletRequest;
- private HttpHeaders httpHeaders;
- private String objectFromRequestType;
- private Object objectFromRequest;
- private boolean preExtFailOnError = true;
- private boolean postExtFailOnError = true;
- private boolean preExtSkipErrorCallback = true;
- private boolean postExtSkipErrorCallback = true;
- private String fromAppId;
- private String transId;
- private Graph graph;
- private Object objectFromResponse;
- private HashMap<String, Object> lookupHashMap;
- private HashMap<String, ArrayList<String>> precheckAddedList;
- private AAIResponseMessages precheckResponseMessages;
- private HashMap<String, Object> topology;
- private HashMap<String, Vertex> vertexCache;
- private String baseObject;
- private String namespace;
- private String fullResourceName;
- private String topObjectFullResourceName;
- private String uri;
- private String notificationUri;
- private String apiVersion;
- private long startTime;
- private long checkpointTime;
- private DynamicJAXBContext jaxbContext;
- private String objectFromResponseType;
- private String eventAction;
- private TransactionalGraphEngine dbEngine;
- private Loader loader;
- private UriInfo uriInfo;
- private DBRequest dbRequest;
- private HttpEntry httpEntry;
- /**
- * Sets the message.
- *
- * @param _message the new message
- */
- public void setMessage(String _message) {
- this.message = _message;
- }
-
- /**
- * Sets the template vars.
- *
- * @param _templateVars the new template vars
- */
- public void setTemplateVars(ArrayList<String> _templateVars) {
- this.templateVars = _templateVars;
- }
-
- /**
- * Sets the pre ext exception.
- *
- * @param _exception the new pre ext exception
- */
- public void setPreExtException(Exception _exception) {
- this.preExtException = _exception;
- }
-
- /**
- * Sets the pre ext error callback.
- *
- * @param _errorCallback the new pre ext error callback
- */
- public void setPreExtErrorCallback(Method _errorCallback) {
- this.preExtErrorCallback = _errorCallback;
- }
-
- /**
- * Sets the post ext exception.
- *
- * @param _exception the new post ext exception
- */
- public void setPostExtException(Exception _exception) {
- this.postExtException = _exception;
- }
-
- /**
- * Sets the post ext error callback.
- *
- * @param _errorCallback the new post ext error callback
- */
- public void setPostExtErrorCallback(Method _errorCallback) {
- this.postExtErrorCallback = _errorCallback;
- }
-
- /**
- * Sets the servlet request.
- *
- * @param _httpServletRequest the new servlet request
- */
- public void setServletRequest(HttpServletRequest _httpServletRequest) {
- this.servletRequest = _httpServletRequest;
- }
-
- /**
- * Sets the http headers.
- *
- * @param _httpHeaders the new http headers
- */
- public void setHttpHeaders(HttpHeaders _httpHeaders) {
- this.httpHeaders = _httpHeaders;
- }
-
- /**
- * Sets the object from request type.
- *
- * @param _objectFromRequestType the new object from request type
- */
- public void setObjectFromRequestType(String _objectFromRequestType) {
- this.objectFromRequestType = _objectFromRequestType;
- }
-
- /**
- * Sets the object from request.
- *
- * @param _objectFromRequest the new object from request
- */
- public void setObjectFromRequest(Object _objectFromRequest) {
- this.objectFromRequest = _objectFromRequest;
- }
-
- /**
- * Sets the object from response type.
- *
- * @param resourceClassName the new object from response type
- */
- public void setObjectFromResponseType(String resourceClassName) {
- // TODO Auto-generated method stub
- this.objectFromResponseType = resourceClassName;
- }
-
- /**
- * Gets the object from response type.
- *
- * @return the object from response type
- */
- public String getObjectFromResponseType() {
- // TODO Auto-generated method stub
- return this.objectFromResponseType;
- }
-
- /**
- * Sets the pre ext fail on error.
- *
- * @param _failOnError the new pre ext fail on error
- */
- public void setPreExtFailOnError(boolean _failOnError) {
- this.preExtFailOnError = _failOnError;
- }
-
- /**
- * Sets the post ext fail on error.
- *
- * @param _failOnError the new post ext fail on error
- */
- public void setPostExtFailOnError(boolean _failOnError) {
- this.postExtFailOnError = _failOnError;
- }
-
- /**
- * Gets the message.
- *
- * @return the message
- */
- public String getMessage() {
- return this.message;
- }
-
- /**
- * Gets the template vars.
- *
- * @return the template vars
- */
- public ArrayList<String> getTemplateVars() {
- if (this.templateVars == null) {
- this.templateVars = new ArrayList<String>();
- }
- return this.templateVars;
- }
-
- /**
- * Gets the pre ext exception.
- *
- * @return the pre ext exception
- */
- public Exception getPreExtException() {
- return this.preExtException;
- }
-
- /**
- * Gets the pre ext error callback.
- *
- * @return the pre ext error callback
- */
- public Method getPreExtErrorCallback() {
- return this.preExtErrorCallback;
- }
-
- /**
- * Gets the post ext exception.
- *
- * @return the post ext exception
- */
- public Exception getPostExtException() {
- return this.postExtException;
- }
-
- /**
- * Gets the post ext error callback.
- *
- * @return the post ext error callback
- */
- public Method getPostExtErrorCallback() {
- return this.postExtErrorCallback;
- }
-
- /**
- * Gets the http servlet request.
- *
- * @return the http servlet request
- */
- public HttpServletRequest getHttpServletRequest() {
- return this.servletRequest;
- }
-
- /**
- * Gets the http headers.
- *
- * @return the http headers
- */
- public HttpHeaders getHttpHeaders() {
- return this.httpHeaders;
- }
-
- /**
- * Gets the object from request type.
- *
- * @return the object from request type
- */
- public String getObjectFromRequestType() {
- return this.objectFromRequestType;
- }
-
- /**
- * Gets the object from request.
- *
- * @return the object from request
- */
- public Object getObjectFromRequest() {
- return this.objectFromRequest;
- }
-
- /**
- * Gets the pre ext fail on error.
- *
- * @return the pre ext fail on error
- */
- public boolean getPreExtFailOnError() {
- return this.preExtFailOnError;
- }
-
- /**
- * Gets the post ext fail on error.
- *
- * @return the post ext fail on error
- */
- public boolean getPostExtFailOnError() {
- return this.postExtFailOnError;
- }
-
- /**
- * Gets the from app id.
- *
- * @return the from app id
- */
- public String getFromAppId() {
- return this.fromAppId;
- }
-
- /**
- * Sets the from app id.
- *
- * @param fromAppId the new from app id
- */
- public void setFromAppId(String fromAppId) {
- this.fromAppId = fromAppId;
- }
-
- /**
- * Gets the trans id.
- *
- * @return the trans id
- */
- public String getTransId() {
- return this.transId;
- }
-
- /**
- * Sets the trans id.
- *
- * @param transId the new trans id
- */
- public void setTransId(String transId) {
- this.transId = transId;
- }
-
- /**
- * Gets the pre ext skip error callback.
- *
- * @return the pre ext skip error callback
- */
- public boolean getPreExtSkipErrorCallback() {
- return preExtSkipErrorCallback;
- }
-
- /**
- * Sets the pre ext skip error callback.
- *
- * @param preExtSkipErrorCallback the new pre ext skip error callback
- */
- public void setPreExtSkipErrorCallback(boolean preExtSkipErrorCallback) {
- this.preExtSkipErrorCallback = preExtSkipErrorCallback;
- }
-
- /**
- * Gets the post ext skip error callback.
- *
- * @return the post ext skip error callback
- */
- public boolean getPostExtSkipErrorCallback() {
- return postExtSkipErrorCallback;
- }
-
- /**
- * Sets the post ext skip error callback.
- *
- * @param postExtSkipErrorCallback the new post ext skip error callback
- */
- public void setPostExtSkipErrorCallback(boolean postExtSkipErrorCallback) {
- this.postExtSkipErrorCallback = postExtSkipErrorCallback;
- }
-
- /**
- * Gets the graph.
- *
- * @return the graph
- */
- public Graph getGraph() {
- return graph;
- }
-
- /**
- * Sets the graph.
- *
- * @param graph the new graph
- */
- public void setGraph(Graph graph) {
- this.graph = graph;
- }
-
- /**
- * Gets the object from response.
- *
- * @return the object from response
- */
- public Object getObjectFromResponse() {
- return objectFromResponse;
- }
-
- /**
- * Sets the object from response.
- *
- * @param objectFromResponse the new object from response
- */
- public void setObjectFromResponse(Object objectFromResponse) {
- this.objectFromResponse = objectFromResponse;
- }
-
- /**
- * Gets the lookup hash map.
- *
- * @return the lookup hash map
- */
- public HashMap<String, Object> getLookupHashMap() {
- if (this.lookupHashMap == null) {
- this.lookupHashMap = new HashMap<String, Object>();
- }
- return this.lookupHashMap;
- }
-
- /**
- * Sets the lookup hash map.
- *
- * @param lookupHashMap the lookup hash map
- */
- public void setLookupHashMap(HashMap<String, Object> lookupHashMap) {
- this.lookupHashMap = lookupHashMap;
- }
-
- /**
- * Gets the precheck added list.
- *
- * @return the precheck added list
- */
- public HashMap<String, ArrayList<String>> getPrecheckAddedList() {
- if (this.precheckAddedList == null) {
- this.precheckAddedList = new HashMap<String, ArrayList<String>>();
- }
- return precheckAddedList;
- }
-
- /**
- * Sets the precheck added list.
- *
- * @param precheckAddedList the precheck added list
- */
- public void setPrecheckAddedList(HashMap<String, ArrayList<String>> precheckAddedList) {
- this.precheckAddedList = precheckAddedList;
- }
-
- /**
- * Gets the precheck response messages.
- *
- * @return the precheck response messages
- */
- public AAIResponseMessages getPrecheckResponseMessages() {
- if (this.precheckResponseMessages == null) {
- this.precheckResponseMessages = new AAIResponseMessages();
- }
- return precheckResponseMessages;
- }
-
- /**
- * Sets the precheck response messages.
- *
- * @param precheckResponseData the new precheck response messages
- */
- public void setPrecheckResponseMessages(AAIResponseMessages precheckResponseData) {
- this.precheckResponseMessages = precheckResponseData;
- }
-
- /**
- * Gets the topology.
- *
- * @return the topology
- */
- public HashMap<String, Object> getTopology() {
- if (this.topology == null) {
- this.topology = new HashMap<String, Object>();
- }
- return topology;
- }
-
- /**
- * Gets the vertex cache.
- *
- * @return the vertex cache
- */
- public HashMap<String, Vertex> getVertexCache() {
- if (this.vertexCache == null) {
- this.vertexCache = new HashMap<String, Vertex>();
- }
- return vertexCache;
- }
-
- /**
- * Gets the base object.
- *
- * @return the base object
- */
- public String getBaseObject() {
- return baseObject;
- }
-
- /**
- * Sets the base object.
- *
- * @param baseObject the new base object
- */
- public void setBaseObject(String baseObject) {
- this.baseObject = baseObject;
- }
-
- /**
- * Gets the namespace.
- *
- * @return the namespace
- */
- public String getNamespace() {
- return namespace;
- }
-
- /**
- * Sets the namespace.
- *
- * @param namespace the new namespace
- */
- public void setNamespace(String namespace) {
- this.namespace = namespace;
- }
-
- /**
- * Gets the full resource name.
- *
- * @return the full resource name
- */
- public String getFullResourceName() {
- return fullResourceName;
- }
-
- /**
- * Sets the full resource name.
- *
- * @param fullResourceName the new full resource name
- */
- public void setFullResourceName(String fullResourceName) {
- this.fullResourceName = fullResourceName;
- }
-
- /**
- * Gets the top object full resource name.
- *
- * @return the top object full resource name
- */
- public String getTopObjectFullResourceName() {
- return topObjectFullResourceName;
- }
-
- /**
- * Sets the top object full resource name.
- *
- * @param topObjectFullResourceName the new top object full resource name
- */
- public void setTopObjectFullResourceName(String topObjectFullResourceName) {
- this.topObjectFullResourceName = topObjectFullResourceName;
- }
-
- /**
- * Gets the uri.
- *
- * @return the uri
- */
- public String getUri() {
- return uri;
- }
-
- /**
- * Sets the uri.
- *
- * @param uri the new uri
- */
- public void setUri(String uri) {
- this.uri = uri;
- }
-
- /**
- * Gets the api version.
- *
- * @return the api version
- */
- public String getApiVersion() {
- return apiVersion;
- }
-
- /**
- * Sets the api version.
- *
- * @param apiVersion the new api version
- */
- public void setApiVersion(String apiVersion) {
- this.apiVersion = apiVersion;
- }
-
- /**
- * Sets the notification uri.
- *
- * @param uri the new notification uri
- */
- public void setNotificationUri(String uri) {
- this.notificationUri = uri;
-
- }
-
- /**
- * Gets the notification uri.
- *
- * @return the notification uri
- */
- public String getNotificationUri() {
- return this.notificationUri;
-
- }
-
- /**
- * Gets the start time.
- *
- * @return the start time
- */
- public long getStartTime() {
- return startTime;
- }
-
- /**
- * Sets the start time.
- *
- * @param startTime the new start time
- */
- public void setStartTime(long startTime) {
- this.startTime = startTime;
- }
-
- /**
- * Gets the checkpoint time.
- *
- * @return the checkpoint time
- */
- public long getCheckpointTime() {
- return checkpointTime;
- }
-
- /**
- * Sets the checkpoint time.
- *
- * @param checkpointTime the new checkpoint time
- */
- public void setCheckpointTime(long checkpointTime) {
- this.checkpointTime = checkpointTime;
- }
-
- /**
- * Gets the jaxb context.
- *
- * @return the jaxb context
- */
- public DynamicJAXBContext getJaxbContext() {
- return jaxbContext;
- }
-
- /**
- * Sets the jaxb context.
- *
- * @param jaxbContext the new jaxb context
- */
- public void setJaxbContext(DynamicJAXBContext jaxbContext) {
- this.jaxbContext = jaxbContext;
- }
-
- /**
- * Sets the event action.
- *
- * @param eventAction the new event action
- */
- public void setEventAction(String eventAction) {
- this.eventAction = eventAction;
- }
-
- /**
- * Gets the event action.
- *
- * @return the event action
- */
- public String getEventAction() {
- return this.eventAction;
- }
-
- /**
- * Gets the transactional graph engine.
- *
- * @return the transactional graph engine
- */
- public TransactionalGraphEngine getTransactionalGraphEngine() {
- return this.dbEngine;
-
- }
-
- /**
- * Sets the transactional graph engine.
- *
- * @param dbEngine the new transactional graph engine
- */
- public void setTransactionalGraphEngine(TransactionalGraphEngine dbEngine) {
- this.dbEngine = dbEngine;
-
- }
-
- /**
- * Gets the loader.
- *
- * @return the loader
- */
- public Loader getLoader() {
- return loader;
- }
-
- /**
- * Sets the loader.
- *
- * @param loader the new loader
- */
- public void setLoader(Loader loader) {
- this.loader = loader;
- }
-
- /**
- * Gets the uri info.
- *
- * @return the uri info
- */
- public UriInfo getUriInfo() {
- return uriInfo;
- }
-
- /**
- * Sets the uri info.
- *
- * @param uriInfo the new uri info
- */
- public void setUriInfo(UriInfo uriInfo) {
- this.uriInfo = uriInfo;
- }
-
- public DBRequest getDbRequest() {
- return dbRequest;
- }
-
- public void setDbRequest(DBRequest dbRequest) {
- this.dbRequest = dbRequest;
- }
-
- public HttpEntry getHttpEntry() {
- return httpEntry;
- }
-
- public void setHttpEntry(HttpEntry httpEntry) {
- this.httpEntry = httpEntry;
- }
+ // =======================================================================
+ // Attribute | Type
+ // =======================================================================
+ // message | java.lang.String (RW)
+ // ----------------------------------------------------------------------
+ // templateVars | java.lang.ArrayList<String> (RW)
+ // -----------------------------------------------------------------------
+ // preExtException | java.lang.Exception (RW)
+ // -----------------------------------------------------------------------
+ // preExtErrorCallback | java.lang.reflect.Method (RW)
+ // -----------------------------------------------------------------------
+ // postExtException | java.lang.Exception (RW)
+ // -----------------------------------------------------------------------
+ // postExtErrorCallback | java.lang.reflect.Method (RW)
+ // -----------------------------------------------------------------------
+ // servletRequest | javax.servlet.http.HttpServletRequest (RO)
+ // -----------------------------------------------------------------------
+ // headers | javax.ws.rs.core.HttpHeaders (RO)
+ // -----------------------------------------------------------------------
+ // objFromRequestType | String (ex. ?org.onap.aai.domain.yang.Vce?) (RO)
+ // -----------------------------------------------------------------------
+ // objFromRequest | $TYPE {ObjFromRequestType) (RO)
+ // -----------------------------------------------------------------------
+ // preExtFailOnError | java.lang.Boolean (RW)
+ // -----------------------------------------------------------------------
+ // postExtFailOnError | java.lang.Boolean (RW)
+ // -----------------------------------------------------------------------
+ // preExtSkipErrorCallback | java.lang.Boolean (RW)
+ // -----------------------------------------------------------------------
+ // postExtSkipErrorCallback | java.lang.Boolean (RW)
+ // -----------------------------------------------------------------------
+ // graph | org.janusgraph.core.JanusGraph (RW)
+ // -----------------------------------------------------------------------
+ // objectFromResponse | Object
+ // -----------------------------------------------------------------------
+ // precheckAddedList | java.util.HashMap
+ // -----------------------------------------------------------------------
+ // precheckResponseMessages | org.onap.aai.extensions.AAIResponseMessages
+ // =======================================================================
+
+ private String message;
+ private ArrayList<String> templateVars;
+ private Exception preExtException;
+ private Exception postExtException;
+ private Method preExtErrorCallback;
+ private Method postExtErrorCallback;
+ private HttpServletRequest servletRequest;
+ private HttpHeaders httpHeaders;
+ private String objectFromRequestType;
+ private Object objectFromRequest;
+ private boolean preExtFailOnError = true;
+ private boolean postExtFailOnError = true;
+ private boolean preExtSkipErrorCallback = true;
+ private boolean postExtSkipErrorCallback = true;
+ private String fromAppId;
+ private String transId;
+ private Graph graph;
+ private Object objectFromResponse;
+ private HashMap<String, Object> lookupHashMap;
+ private HashMap<String, ArrayList<String>> precheckAddedList;
+ private AAIResponseMessages precheckResponseMessages;
+ private HashMap<String, Object> topology;
+ private HashMap<String, Vertex> vertexCache;
+ private String baseObject;
+ private String namespace;
+ private String fullResourceName;
+ private String topObjectFullResourceName;
+ private String uri;
+ private String notificationUri;
+ private String apiVersion;
+ private long startTime;
+ private long checkpointTime;
+ private DynamicJAXBContext jaxbContext;
+ private String objectFromResponseType;
+ private String eventAction;
+ private TransactionalGraphEngine dbEngine;
+ private Loader loader;
+ private UriInfo uriInfo;
+ private DBRequest dbRequest;
+ private HttpEntry httpEntry;
+
+ /**
+ * Sets the message.
+ *
+ * @param _message the new message
+ */
+ public void setMessage(String _message) {
+ this.message = _message;
+ }
+
+ /**
+ * Sets the template vars.
+ *
+ * @param _templateVars the new template vars
+ */
+ public void setTemplateVars(ArrayList<String> _templateVars) {
+ this.templateVars = _templateVars;
+ }
+
+ /**
+ * Sets the pre ext exception.
+ *
+ * @param _exception the new pre ext exception
+ */
+ public void setPreExtException(Exception _exception) {
+ this.preExtException = _exception;
+ }
+
+ /**
+ * Sets the pre ext error callback.
+ *
+ * @param _errorCallback the new pre ext error callback
+ */
+ public void setPreExtErrorCallback(Method _errorCallback) {
+ this.preExtErrorCallback = _errorCallback;
+ }
+
+ /**
+ * Sets the post ext exception.
+ *
+ * @param _exception the new post ext exception
+ */
+ public void setPostExtException(Exception _exception) {
+ this.postExtException = _exception;
+ }
+
+ /**
+ * Sets the post ext error callback.
+ *
+ * @param _errorCallback the new post ext error callback
+ */
+ public void setPostExtErrorCallback(Method _errorCallback) {
+ this.postExtErrorCallback = _errorCallback;
+ }
+
+ /**
+ * Sets the servlet request.
+ *
+ * @param _httpServletRequest the new servlet request
+ */
+ public void setServletRequest(HttpServletRequest _httpServletRequest) {
+ this.servletRequest = _httpServletRequest;
+ }
+
+ /**
+ * Sets the http headers.
+ *
+ * @param _httpHeaders the new http headers
+ */
+ public void setHttpHeaders(HttpHeaders _httpHeaders) {
+ this.httpHeaders = _httpHeaders;
+ }
+
+ /**
+ * Sets the object from request type.
+ *
+ * @param _objectFromRequestType the new object from request type
+ */
+ public void setObjectFromRequestType(String _objectFromRequestType) {
+ this.objectFromRequestType = _objectFromRequestType;
+ }
+
+ /**
+ * Sets the object from request.
+ *
+ * @param _objectFromRequest the new object from request
+ */
+ public void setObjectFromRequest(Object _objectFromRequest) {
+ this.objectFromRequest = _objectFromRequest;
+ }
+
+ /**
+ * Sets the object from response type.
+ *
+ * @param resourceClassName the new object from response type
+ */
+ public void setObjectFromResponseType(String resourceClassName) {
+ // TODO Auto-generated method stub
+ this.objectFromResponseType = resourceClassName;
+ }
+
+ /**
+ * Gets the object from response type.
+ *
+ * @return the object from response type
+ */
+ public String getObjectFromResponseType() {
+ // TODO Auto-generated method stub
+ return this.objectFromResponseType;
+ }
+
+ /**
+ * Sets the pre ext fail on error.
+ *
+ * @param _failOnError the new pre ext fail on error
+ */
+ public void setPreExtFailOnError(boolean _failOnError) {
+ this.preExtFailOnError = _failOnError;
+ }
+
+ /**
+ * Sets the post ext fail on error.
+ *
+ * @param _failOnError the new post ext fail on error
+ */
+ public void setPostExtFailOnError(boolean _failOnError) {
+ this.postExtFailOnError = _failOnError;
+ }
+
+ /**
+ * Gets the message.
+ *
+ * @return the message
+ */
+ public String getMessage() {
+ return this.message;
+ }
+
+ /**
+ * Gets the template vars.
+ *
+ * @return the template vars
+ */
+ public ArrayList<String> getTemplateVars() {
+ if (this.templateVars == null) {
+ this.templateVars = new ArrayList<String>();
+ }
+ return this.templateVars;
+ }
+
+ /**
+ * Gets the pre ext exception.
+ *
+ * @return the pre ext exception
+ */
+ public Exception getPreExtException() {
+ return this.preExtException;
+ }
+
+ /**
+ * Gets the pre ext error callback.
+ *
+ * @return the pre ext error callback
+ */
+ public Method getPreExtErrorCallback() {
+ return this.preExtErrorCallback;
+ }
+
+ /**
+ * Gets the post ext exception.
+ *
+ * @return the post ext exception
+ */
+ public Exception getPostExtException() {
+ return this.postExtException;
+ }
+
+ /**
+ * Gets the post ext error callback.
+ *
+ * @return the post ext error callback
+ */
+ public Method getPostExtErrorCallback() {
+ return this.postExtErrorCallback;
+ }
+
+ /**
+ * Gets the http servlet request.
+ *
+ * @return the http servlet request
+ */
+ public HttpServletRequest getHttpServletRequest() {
+ return this.servletRequest;
+ }
+
+ /**
+ * Gets the http headers.
+ *
+ * @return the http headers
+ */
+ public HttpHeaders getHttpHeaders() {
+ return this.httpHeaders;
+ }
+
+ /**
+ * Gets the object from request type.
+ *
+ * @return the object from request type
+ */
+ public String getObjectFromRequestType() {
+ return this.objectFromRequestType;
+ }
+
+ /**
+ * Gets the object from request.
+ *
+ * @return the object from request
+ */
+ public Object getObjectFromRequest() {
+ return this.objectFromRequest;
+ }
+
+ /**
+ * Gets the pre ext fail on error.
+ *
+ * @return the pre ext fail on error
+ */
+ public boolean getPreExtFailOnError() {
+ return this.preExtFailOnError;
+ }
+
+ /**
+ * Gets the post ext fail on error.
+ *
+ * @return the post ext fail on error
+ */
+ public boolean getPostExtFailOnError() {
+ return this.postExtFailOnError;
+ }
+
+ /**
+ * Gets the from app id.
+ *
+ * @return the from app id
+ */
+ public String getFromAppId() {
+ return this.fromAppId;
+ }
+
+ /**
+ * Sets the from app id.
+ *
+ * @param fromAppId the new from app id
+ */
+ public void setFromAppId(String fromAppId) {
+ this.fromAppId = fromAppId;
+ }
+
+ /**
+ * Gets the trans id.
+ *
+ * @return the trans id
+ */
+ public String getTransId() {
+ return this.transId;
+ }
+
+ /**
+ * Sets the trans id.
+ *
+ * @param transId the new trans id
+ */
+ public void setTransId(String transId) {
+ this.transId = transId;
+ }
+
+ /**
+ * Gets the pre ext skip error callback.
+ *
+ * @return the pre ext skip error callback
+ */
+ public boolean getPreExtSkipErrorCallback() {
+ return preExtSkipErrorCallback;
+ }
+
+ /**
+ * Sets the pre ext skip error callback.
+ *
+ * @param preExtSkipErrorCallback the new pre ext skip error callback
+ */
+ public void setPreExtSkipErrorCallback(boolean preExtSkipErrorCallback) {
+ this.preExtSkipErrorCallback = preExtSkipErrorCallback;
+ }
+
+ /**
+ * Gets the post ext skip error callback.
+ *
+ * @return the post ext skip error callback
+ */
+ public boolean getPostExtSkipErrorCallback() {
+ return postExtSkipErrorCallback;
+ }
+
+ /**
+ * Sets the post ext skip error callback.
+ *
+ * @param postExtSkipErrorCallback the new post ext skip error callback
+ */
+ public void setPostExtSkipErrorCallback(boolean postExtSkipErrorCallback) {
+ this.postExtSkipErrorCallback = postExtSkipErrorCallback;
+ }
+
+ /**
+ * Gets the graph.
+ *
+ * @return the graph
+ */
+ public Graph getGraph() {
+ return graph;
+ }
+
+ /**
+ * Sets the graph.
+ *
+ * @param graph the new graph
+ */
+ public void setGraph(Graph graph) {
+ this.graph = graph;
+ }
+
+ /**
+ * Gets the object from response.
+ *
+ * @return the object from response
+ */
+ public Object getObjectFromResponse() {
+ return objectFromResponse;
+ }
+
+ /**
+ * Sets the object from response.
+ *
+ * @param objectFromResponse the new object from response
+ */
+ public void setObjectFromResponse(Object objectFromResponse) {
+ this.objectFromResponse = objectFromResponse;
+ }
+
+ /**
+ * Gets the lookup hash map.
+ *
+ * @return the lookup hash map
+ */
+ public HashMap<String, Object> getLookupHashMap() {
+ if (this.lookupHashMap == null) {
+ this.lookupHashMap = new HashMap<String, Object>();
+ }
+ return this.lookupHashMap;
+ }
+
+ /**
+ * Sets the lookup hash map.
+ *
+ * @param lookupHashMap the lookup hash map
+ */
+ public void setLookupHashMap(HashMap<String, Object> lookupHashMap) {
+ this.lookupHashMap = lookupHashMap;
+ }
+
+ /**
+ * Gets the precheck added list.
+ *
+ * @return the precheck added list
+ */
+ public HashMap<String, ArrayList<String>> getPrecheckAddedList() {
+ if (this.precheckAddedList == null) {
+ this.precheckAddedList = new HashMap<String, ArrayList<String>>();
+ }
+ return precheckAddedList;
+ }
+
+ /**
+ * Sets the precheck added list.
+ *
+ * @param precheckAddedList the precheck added list
+ */
+ public void setPrecheckAddedList(HashMap<String, ArrayList<String>> precheckAddedList) {
+ this.precheckAddedList = precheckAddedList;
+ }
+
+ /**
+ * Gets the precheck response messages.
+ *
+ * @return the precheck response messages
+ */
+ public AAIResponseMessages getPrecheckResponseMessages() {
+ if (this.precheckResponseMessages == null) {
+ this.precheckResponseMessages = new AAIResponseMessages();
+ }
+ return precheckResponseMessages;
+ }
+
+ /**
+ * Sets the precheck response messages.
+ *
+ * @param precheckResponseData the new precheck response messages
+ */
+ public void setPrecheckResponseMessages(AAIResponseMessages precheckResponseData) {
+ this.precheckResponseMessages = precheckResponseData;
+ }
+
+ /**
+ * Gets the topology.
+ *
+ * @return the topology
+ */
+ public HashMap<String, Object> getTopology() {
+ if (this.topology == null) {
+ this.topology = new HashMap<String, Object>();
+ }
+ return topology;
+ }
+
+ /**
+ * Gets the vertex cache.
+ *
+ * @return the vertex cache
+ */
+ public HashMap<String, Vertex> getVertexCache() {
+ if (this.vertexCache == null) {
+ this.vertexCache = new HashMap<String, Vertex>();
+ }
+ return vertexCache;
+ }
+
+ /**
+ * Gets the base object.
+ *
+ * @return the base object
+ */
+ public String getBaseObject() {
+ return baseObject;
+ }
+
+ /**
+ * Sets the base object.
+ *
+ * @param baseObject the new base object
+ */
+ public void setBaseObject(String baseObject) {
+ this.baseObject = baseObject;
+ }
+
+ /**
+ * Gets the namespace.
+ *
+ * @return the namespace
+ */
+ public String getNamespace() {
+ return namespace;
+ }
+
+ /**
+ * Sets the namespace.
+ *
+ * @param namespace the new namespace
+ */
+ public void setNamespace(String namespace) {
+ this.namespace = namespace;
+ }
+
+ /**
+ * Gets the full resource name.
+ *
+ * @return the full resource name
+ */
+ public String getFullResourceName() {
+ return fullResourceName;
+ }
+
+ /**
+ * Sets the full resource name.
+ *
+ * @param fullResourceName the new full resource name
+ */
+ public void setFullResourceName(String fullResourceName) {
+ this.fullResourceName = fullResourceName;
+ }
+
+ /**
+ * Gets the top object full resource name.
+ *
+ * @return the top object full resource name
+ */
+ public String getTopObjectFullResourceName() {
+ return topObjectFullResourceName;
+ }
+
+ /**
+ * Sets the top object full resource name.
+ *
+ * @param topObjectFullResourceName the new top object full resource name
+ */
+ public void setTopObjectFullResourceName(String topObjectFullResourceName) {
+ this.topObjectFullResourceName = topObjectFullResourceName;
+ }
+
+ /**
+ * Gets the uri.
+ *
+ * @return the uri
+ */
+ public String getUri() {
+ return uri;
+ }
+
+ /**
+ * Sets the uri.
+ *
+ * @param uri the new uri
+ */
+ public void setUri(String uri) {
+ this.uri = uri;
+ }
+
+ /**
+ * Gets the api version.
+ *
+ * @return the api version
+ */
+ public String getApiVersion() {
+ return apiVersion;
+ }
+
+ /**
+ * Sets the api version.
+ *
+ * @param apiVersion the new api version
+ */
+ public void setApiVersion(String apiVersion) {
+ this.apiVersion = apiVersion;
+ }
+
+ /**
+ * Sets the notification uri.
+ *
+ * @param uri the new notification uri
+ */
+ public void setNotificationUri(String uri) {
+ this.notificationUri = uri;
+
+ }
+
+ /**
+ * Gets the notification uri.
+ *
+ * @return the notification uri
+ */
+ public String getNotificationUri() {
+ return this.notificationUri;
+
+ }
+
+ /**
+ * Gets the start time.
+ *
+ * @return the start time
+ */
+ public long getStartTime() {
+ return startTime;
+ }
+
+ /**
+ * Sets the start time.
+ *
+ * @param startTime the new start time
+ */
+ public void setStartTime(long startTime) {
+ this.startTime = startTime;
+ }
+
+ /**
+ * Gets the checkpoint time.
+ *
+ * @return the checkpoint time
+ */
+ public long getCheckpointTime() {
+ return checkpointTime;
+ }
+
+ /**
+ * Sets the checkpoint time.
+ *
+ * @param checkpointTime the new checkpoint time
+ */
+ public void setCheckpointTime(long checkpointTime) {
+ this.checkpointTime = checkpointTime;
+ }
+
+ /**
+ * Gets the jaxb context.
+ *
+ * @return the jaxb context
+ */
+ public DynamicJAXBContext getJaxbContext() {
+ return jaxbContext;
+ }
+
+ /**
+ * Sets the jaxb context.
+ *
+ * @param jaxbContext the new jaxb context
+ */
+ public void setJaxbContext(DynamicJAXBContext jaxbContext) {
+ this.jaxbContext = jaxbContext;
+ }
+
+ /**
+ * Sets the event action.
+ *
+ * @param eventAction the new event action
+ */
+ public void setEventAction(String eventAction) {
+ this.eventAction = eventAction;
+ }
+
+ /**
+ * Gets the event action.
+ *
+ * @return the event action
+ */
+ public String getEventAction() {
+ return this.eventAction;
+ }
+
+ /**
+ * Gets the transactional graph engine.
+ *
+ * @return the transactional graph engine
+ */
+ public TransactionalGraphEngine getTransactionalGraphEngine() {
+ return this.dbEngine;
+
+ }
+
+ /**
+ * Sets the transactional graph engine.
+ *
+ * @param dbEngine the new transactional graph engine
+ */
+ public void setTransactionalGraphEngine(TransactionalGraphEngine dbEngine) {
+ this.dbEngine = dbEngine;
+
+ }
+
+ /**
+ * Gets the loader.
+ *
+ * @return the loader
+ */
+ public Loader getLoader() {
+ return loader;
+ }
+
+ /**
+ * Sets the loader.
+ *
+ * @param loader the new loader
+ */
+ public void setLoader(Loader loader) {
+ this.loader = loader;
+ }
+
+ /**
+ * Gets the uri info.
+ *
+ * @return the uri info
+ */
+ public UriInfo getUriInfo() {
+ return uriInfo;
+ }
+
+ /**
+ * Sets the uri info.
+ *
+ * @param uriInfo the new uri info
+ */
+ public void setUriInfo(UriInfo uriInfo) {
+ this.uriInfo = uriInfo;
+ }
+
+ public DBRequest getDbRequest() {
+ return dbRequest;
+ }
+
+ public void setDbRequest(DBRequest dbRequest) {
+ this.dbRequest = dbRequest;
+ }
+
+ public HttpEntry getHttpEntry() {
+ return httpEntry;
+ }
+
+ public void setHttpEntry(HttpEntry httpEntry) {
+ this.httpEntry = httpEntry;
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/extensions/ExtensionController.java b/aai-core/src/main/java/org/onap/aai/extensions/ExtensionController.java
index 8959a04e..13c2de94 100644
--- a/aai-core/src/main/java/org/onap/aai/extensions/ExtensionController.java
+++ b/aai-core/src/main/java/org/onap/aai/extensions/ExtensionController.java
@@ -17,128 +17,120 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.extensions;
import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
-import org.onap.aai.exceptions.AAIException;
-import org.onap.aai.util.AAIConfig;
import java.lang.reflect.Method;
+import org.onap.aai.exceptions.AAIException;
+import org.onap.aai.util.AAIConfig;
+
public class ExtensionController {
- private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(ExtensionController.class);
-
- /**
- * Run extension.
- *
- * @param apiVersion the api version
- * @param namespace the namespace
- * @param resourceName the resource name
- * @param methodName the method name
- * @param aaiExtMap the aai ext map
- * @param isPreExtension the is pre extension
- * @throws AAIException the AAI exception
- */
- public void runExtension(String apiVersion, String namespace,
- String resourceName, String methodName, AAIExtensionMap aaiExtMap,
- boolean isPreExtension) throws AAIException {
- String extensionClassName = "org.onap.aai.extensions."
- + apiVersion.toLowerCase() + "." + namespace + "."
- + resourceName + "Extension";
- String defaultErrorCallback = resourceName + "ExtensionErrorCallback";
-
- String configOption = "aai.extensions." + apiVersion.toLowerCase()
- + "." + namespace.toLowerCase() + "."
- + resourceName.toLowerCase() + ".enabled";
-
- try {
-
- String extensionEnabled = AAIConfig.get(configOption, "true");
- if (extensionEnabled.equalsIgnoreCase("false")) {
- return;
- }
-
- Class<?> clazz = Class.forName(extensionClassName);
-
- Method extension = clazz.getMethod(methodName,
- new Class[] { AAIExtensionMap.class });
- if (extension != null) {
-
- Object ret = extension.invoke(clazz.newInstance(), aaiExtMap);
-
- if (ret instanceof Integer) {
- Exception e = null;
-
- if (isPreExtension == true) {
- e = aaiExtMap.getPreExtException();
- } else {
- e = aaiExtMap.getPostExtException();
- }
-
- boolean failOnError = true;
- if (isPreExtension == true) {
- failOnError = aaiExtMap.getPreExtFailOnError();
- } else {
- failOnError = aaiExtMap.getPostExtFailOnError();
- }
-
- if (e != null) {
- boolean handleException = true;
- if (isPreExtension == true) {
- if (aaiExtMap.getPreExtSkipErrorCallback() == true) {
- handleException = false;
- }
- } else {
- if (aaiExtMap.getPostExtSkipErrorCallback() == true) {
- handleException = false;
- }
- }
- if (handleException == true) {
- Method errorCallback = null;
- if (isPreExtension == true) {
- errorCallback = aaiExtMap
- .getPreExtErrorCallback();
- } else {
- errorCallback = aaiExtMap
- .getPostExtErrorCallback();
- }
-
- if (errorCallback != null) {
- errorCallback.invoke(clazz.newInstance(),
- aaiExtMap);
- } else {
- Method defaultErrorCallbackExtension = clazz
- .getMethod(
- defaultErrorCallback,
- new Class[] { AAIExtensionMap.class });
- defaultErrorCallbackExtension.invoke(
- clazz.newInstance(), aaiExtMap);
- }
- }
- }
-
- if (failOnError == true && e != null) {
- throw e;
- } else if (failOnError == false && e != null) { // in this
- // case, we
- // just note
- // the error
- // without
- // stopping
- LOGGER.warn("Error while processing extension - " + aaiExtMap.getMessage());
- }
- }
- }
- } catch (ClassNotFoundException ex) {
- LOGGER.debug("Extension class not found: " + extensionClassName + ", method: " + methodName + ".");
- } catch (NoSuchMethodException e) {
- LOGGER.debug("Method " + methodName + " does not exist for class " + extensionClassName);
- } catch (AAIException e) {
- throw e;
- } catch (Exception e) {
- throw new AAIException("AAI_5105", e);
- }
- }
+ private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(ExtensionController.class);
+
+ /**
+ * Run extension.
+ *
+ * @param apiVersion the api version
+ * @param namespace the namespace
+ * @param resourceName the resource name
+ * @param methodName the method name
+ * @param aaiExtMap the aai ext map
+ * @param isPreExtension the is pre extension
+ * @throws AAIException the AAI exception
+ */
+ public void runExtension(String apiVersion, String namespace, String resourceName, String methodName,
+ AAIExtensionMap aaiExtMap, boolean isPreExtension) throws AAIException {
+ String extensionClassName = "org.onap.aai.extensions." + apiVersion.toLowerCase() + "." + namespace + "."
+ + resourceName + "Extension";
+ String defaultErrorCallback = resourceName + "ExtensionErrorCallback";
+
+ String configOption = "aai.extensions." + apiVersion.toLowerCase() + "." + namespace.toLowerCase() + "."
+ + resourceName.toLowerCase() + ".enabled";
+
+ try {
+
+ String extensionEnabled = AAIConfig.get(configOption, "true");
+ if (extensionEnabled.equalsIgnoreCase("false")) {
+ return;
+ }
+
+ Class<?> clazz = Class.forName(extensionClassName);
+
+ Method extension = clazz.getMethod(methodName, new Class[] {AAIExtensionMap.class});
+ if (extension != null) {
+
+ Object ret = extension.invoke(clazz.newInstance(), aaiExtMap);
+
+ if (ret instanceof Integer) {
+ Exception e = null;
+
+ if (isPreExtension == true) {
+ e = aaiExtMap.getPreExtException();
+ } else {
+ e = aaiExtMap.getPostExtException();
+ }
+
+ boolean failOnError = true;
+ if (isPreExtension == true) {
+ failOnError = aaiExtMap.getPreExtFailOnError();
+ } else {
+ failOnError = aaiExtMap.getPostExtFailOnError();
+ }
+
+ if (e != null) {
+ boolean handleException = true;
+ if (isPreExtension == true) {
+ if (aaiExtMap.getPreExtSkipErrorCallback() == true) {
+ handleException = false;
+ }
+ } else {
+ if (aaiExtMap.getPostExtSkipErrorCallback() == true) {
+ handleException = false;
+ }
+ }
+ if (handleException == true) {
+ Method errorCallback = null;
+ if (isPreExtension == true) {
+ errorCallback = aaiExtMap.getPreExtErrorCallback();
+ } else {
+ errorCallback = aaiExtMap.getPostExtErrorCallback();
+ }
+
+ if (errorCallback != null) {
+ errorCallback.invoke(clazz.newInstance(), aaiExtMap);
+ } else {
+ Method defaultErrorCallbackExtension =
+ clazz.getMethod(defaultErrorCallback, new Class[] {AAIExtensionMap.class});
+ defaultErrorCallbackExtension.invoke(clazz.newInstance(), aaiExtMap);
+ }
+ }
+ }
+
+ if (failOnError == true && e != null) {
+ throw e;
+ } else if (failOnError == false && e != null) { // in this
+ // case, we
+ // just note
+ // the error
+ // without
+ // stopping
+ LOGGER.warn("Error while processing extension - " + aaiExtMap.getMessage());
+ }
+ }
+ }
+ } catch (ClassNotFoundException ex) {
+ LOGGER.debug("Extension class not found: " + extensionClassName + ", method: " + methodName + ".");
+ } catch (NoSuchMethodException e) {
+ LOGGER.debug("Method " + methodName + " does not exist for class " + extensionClassName);
+ } catch (AAIException e) {
+ throw e;
+ } catch (Exception e) {
+ throw new AAIException("AAI_5105", e);
+ }
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/extensions/OrphanLInterfaceHandler.java b/aai-core/src/main/java/org/onap/aai/extensions/OrphanLInterfaceHandler.java
index 128945d3..094e7cee 100644
--- a/aai-core/src/main/java/org/onap/aai/extensions/OrphanLInterfaceHandler.java
+++ b/aai-core/src/main/java/org/onap/aai/extensions/OrphanLInterfaceHandler.java
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.extensions;
import java.io.UnsupportedEncodingException;
@@ -26,6 +27,7 @@ import java.util.ArrayList;
import java.util.List;
import org.apache.tinkerpop.gremlin.structure.Vertex;
+import org.onap.aai.edges.enums.EdgeType;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.introspection.Introspector;
import org.onap.aai.introspection.Loader;
@@ -34,77 +36,80 @@ import org.onap.aai.parsers.query.QueryParser;
import org.onap.aai.query.builder.QueryBuilder;
import org.onap.aai.rest.db.DBRequest;
import org.onap.aai.restcore.HttpMethod;
-import org.onap.aai.edges.enums.EdgeType;
public class OrphanLInterfaceHandler {
-
- private QueryBuilder<Vertex> createLInterfaceQuery(AAIExtensionMap aaiReqMap, Introspector newvceObj) throws AAIException {
- Introspector uplinkLInterfaceTraversalIntro = aaiReqMap.getLoader().introspectorFromName("l-interface");
-
- Introspector customerUplinkLInterfaceTraversalIntro = aaiReqMap.getLoader().introspectorFromName("l-interface");
-
- Introspector logLinkIntroForTraversal = aaiReqMap.getLoader().introspectorFromName("logical-link");
-
- QueryBuilder<Vertex> query = aaiReqMap.getTransactionalGraphEngine().getQueryBuilder()
- .exactMatchQuery(newvceObj)
- .createEdgeTraversal(EdgeType.TREE, newvceObj, uplinkLInterfaceTraversalIntro)
- .getVerticesByProperty("interface-role", "UPLINK")
- .createEdgeTraversal(EdgeType.COUSIN, uplinkLInterfaceTraversalIntro, logLinkIntroForTraversal)
- .createEdgeTraversal(EdgeType.COUSIN, logLinkIntroForTraversal, customerUplinkLInterfaceTraversalIntro)
- .getVerticesByProperty("interface-role", "CUSTOMER-UPLINK").dedup();
- return query;
- }
-
- private URI buildLInterfaceURI(Vertex linterface, AAIExtensionMap aaiReqMap) throws UnsupportedEncodingException, AAIException, URISyntaxException {
- Loader loader = aaiReqMap.getLoader();
- Introspector lint = loader.introspectorFromName("l-interface");
- lint.setValue("interface-name", (String)linterface.property("interface-name").value());
- String lintSegment = lint.getURI();
-
- Introspector lagInterfaceForTrav = loader.introspectorFromName("lag-interface");
- QueryBuilder<Vertex> lagIntQuery = aaiReqMap.getTransactionalGraphEngine().getQueryBuilder()
- .exactMatchQuery(lint)
- .createEdgeTraversal(EdgeType.TREE, linterface, lagInterfaceForTrav).dedup();
- List<Vertex> lagInterfaces = lagIntQuery.toList();
- if (lagInterfaces.isEmpty()) {
- throw new AAIException("AAI_6114");
- } else if (lagInterfaces.size() > 1) {
- throw new AAIException("AAI_6140");
- }
- Vertex lagInt = lagInterfaces.get(0);
- lagInterfaceForTrav.setValue("interface-name", (String)lagInt.property("interface-name").value());
- String lagSegment = lagInterfaceForTrav.getURI();
-
- Introspector gvVPEforTrav = loader.introspectorFromName("generic-vnf");
- QueryBuilder<Vertex> gvVPEquery = aaiReqMap.getTransactionalGraphEngine().getQueryBuilder()
- .exactMatchQuery(lagInterfaceForTrav)
- .createEdgeTraversal(EdgeType.TREE, lagInterfaceForTrav, gvVPEforTrav).dedup();
- List<Vertex> genvnfs = gvVPEquery.toList();
- if (genvnfs.isEmpty()) {
- throw new AAIException("AAI_6114");
- } else if (genvnfs.size() > 1) {
- throw new AAIException("AAI_6140");
- }
- Vertex genvnf = genvnfs.get(0);
- gvVPEforTrav.setValue("vnf-id", (String)genvnf.property("vnf-id").value());
- String gvSegment = gvVPEforTrav.getURI();
-
- return new URI(gvSegment + lagSegment + lintSegment);
- }
- public List<DBRequest> createOrphanLInterfaceDelRequests(AAIExtensionMap aaiReqMap, Introspector newvce) throws AAIException, UnsupportedEncodingException, URISyntaxException{
- List<DBRequest> requests = new ArrayList<>();
- QueryBuilder<Vertex> query = createLInterfaceQuery(aaiReqMap, newvce);
- List<Vertex> linterfaces = query.toList();
-
- for (Vertex lint : linterfaces) {
- URI lintURI = buildLInterfaceURI(lint, aaiReqMap);
- QueryParser parser = createLInterfaceQuery(aaiReqMap, newvce).createQueryFromObjectName("l-interface");
- DBRequest originalDbRequest = aaiReqMap.getDbRequest();
- DBRequest request = new DBRequest.Builder(HttpMethod.DELETE, lintURI, parser, newvce, originalDbRequest.getHeaders(), originalDbRequest.getInfo(), originalDbRequest.getTransactionId()).build();
- requests.add(request);
- }
-
- return requests;
- }
+ private QueryBuilder<Vertex> createLInterfaceQuery(AAIExtensionMap aaiReqMap, Introspector newvceObj)
+ throws AAIException {
+ Introspector uplinkLInterfaceTraversalIntro = aaiReqMap.getLoader().introspectorFromName("l-interface");
+
+ Introspector customerUplinkLInterfaceTraversalIntro = aaiReqMap.getLoader().introspectorFromName("l-interface");
+
+ Introspector logLinkIntroForTraversal = aaiReqMap.getLoader().introspectorFromName("logical-link");
+
+ QueryBuilder<Vertex> query = aaiReqMap.getTransactionalGraphEngine().getQueryBuilder()
+ .exactMatchQuery(newvceObj)
+ .createEdgeTraversal(EdgeType.TREE, newvceObj, uplinkLInterfaceTraversalIntro)
+ .getVerticesByProperty("interface-role", "UPLINK")
+ .createEdgeTraversal(EdgeType.COUSIN, uplinkLInterfaceTraversalIntro, logLinkIntroForTraversal)
+ .createEdgeTraversal(EdgeType.COUSIN, logLinkIntroForTraversal, customerUplinkLInterfaceTraversalIntro)
+ .getVerticesByProperty("interface-role", "CUSTOMER-UPLINK").dedup();
+ return query;
+ }
+
+ private URI buildLInterfaceURI(Vertex linterface, AAIExtensionMap aaiReqMap)
+ throws UnsupportedEncodingException, AAIException, URISyntaxException {
+ Loader loader = aaiReqMap.getLoader();
+ Introspector lint = loader.introspectorFromName("l-interface");
+ lint.setValue("interface-name", (String) linterface.property("interface-name").value());
+ String lintSegment = lint.getURI();
+
+ Introspector lagInterfaceForTrav = loader.introspectorFromName("lag-interface");
+ QueryBuilder<Vertex> lagIntQuery = aaiReqMap.getTransactionalGraphEngine().getQueryBuilder()
+ .exactMatchQuery(lint).createEdgeTraversal(EdgeType.TREE, linterface, lagInterfaceForTrav).dedup();
+ List<Vertex> lagInterfaces = lagIntQuery.toList();
+ if (lagInterfaces.isEmpty()) {
+ throw new AAIException("AAI_6114");
+ } else if (lagInterfaces.size() > 1) {
+ throw new AAIException("AAI_6140");
+ }
+ Vertex lagInt = lagInterfaces.get(0);
+ lagInterfaceForTrav.setValue("interface-name", (String) lagInt.property("interface-name").value());
+ String lagSegment = lagInterfaceForTrav.getURI();
+
+ Introspector gvVPEforTrav = loader.introspectorFromName("generic-vnf");
+ QueryBuilder<Vertex> gvVPEquery =
+ aaiReqMap.getTransactionalGraphEngine().getQueryBuilder().exactMatchQuery(lagInterfaceForTrav)
+ .createEdgeTraversal(EdgeType.TREE, lagInterfaceForTrav, gvVPEforTrav).dedup();
+ List<Vertex> genvnfs = gvVPEquery.toList();
+ if (genvnfs.isEmpty()) {
+ throw new AAIException("AAI_6114");
+ } else if (genvnfs.size() > 1) {
+ throw new AAIException("AAI_6140");
+ }
+ Vertex genvnf = genvnfs.get(0);
+ gvVPEforTrav.setValue("vnf-id", (String) genvnf.property("vnf-id").value());
+ String gvSegment = gvVPEforTrav.getURI();
+
+ return new URI(gvSegment + lagSegment + lintSegment);
+ }
+
+ public List<DBRequest> createOrphanLInterfaceDelRequests(AAIExtensionMap aaiReqMap, Introspector newvce)
+ throws AAIException, UnsupportedEncodingException, URISyntaxException {
+ List<DBRequest> requests = new ArrayList<>();
+ QueryBuilder<Vertex> query = createLInterfaceQuery(aaiReqMap, newvce);
+ List<Vertex> linterfaces = query.toList();
+
+ for (Vertex lint : linterfaces) {
+ URI lintURI = buildLInterfaceURI(lint, aaiReqMap);
+ QueryParser parser = createLInterfaceQuery(aaiReqMap, newvce).createQueryFromObjectName("l-interface");
+ DBRequest originalDbRequest = aaiReqMap.getDbRequest();
+ DBRequest request =
+ new DBRequest.Builder(HttpMethod.DELETE, lintURI, parser, newvce, originalDbRequest.getHeaders(),
+ originalDbRequest.getInfo(), originalDbRequest.getTransactionId()).build();
+ requests.add(request);
+ }
+
+ return requests;
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/ingestModel/CreateWidgetModels.java b/aai-core/src/main/java/org/onap/aai/ingestModel/CreateWidgetModels.java
index 5f641025..62cadab3 100644
--- a/aai-core/src/main/java/org/onap/aai/ingestModel/CreateWidgetModels.java
+++ b/aai-core/src/main/java/org/onap/aai/ingestModel/CreateWidgetModels.java
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.ingestModel;
import java.io.File;
@@ -42,116 +43,115 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext
/**
* The Class CreateWidgetModels.
*/
-public class CreateWidgetModels
-{
- /**
- * The main method.
- *
- * @param args the arguments
- * @throws Exception the exception
- */
- public static void main(String[] args) throws Exception {
-
- String _apiVersion = AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP);
- String widgetJsonDir = null;
- String modelVersion = null;
- 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 (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);
- Loader loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, new SchemaVersion(_apiVersion));
-
- // iterate the collection of resources
-
- ArrayList<String> processedWidgets = new ArrayList<String>();
- for (Entry<String, Introspector> aaiResEnt : loader.getAllObjects().entrySet()) {
- Introspector meObject = loader.introspectorFromName("model");
- // 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;
- }
-
- Set<String> introspectorProperties = aaiRes.getProperties();
-
- if(!(introspectorProperties.contains("model-version-id") && introspectorProperties.contains("model-invariant-id"))){
- System.out.println(aaiRes.getDbName() + " does not contain model properties so skipping");
- }
- processedWidgets.add(resource);
-
- String widgetName = resource;
- String filePathString = widgetJsonDir + "/" + widgetName + "-" + modelVersion + ".json";
- File f = new File(filePathString);
-
- String filePathString2 = widgetJsonDir + "/../widget-model-json-old/" + widgetName + "-" + modelVersion + ".json";
- File f2 = new File(filePathString2);
-
- if(!f.exists() && !f.isDirectory()) {
-
- if (f2.exists()) {
- System.out.println("Using old file for " + resource + ".");
-
- meObject = loader.unmarshal("model", new StreamSource(f2).getReader().toString());
- // override, some of them are wrong
- meObject.setValue("model-version", modelVersion);
- } else {
- System.out.println("Making new file for " + resource + ".");
- meObject.setValue("model-invariant-id", UUID.randomUUID().toString());
- meObject.setValue("model-type", "widget");
- Introspector mevObject = loader.introspectorFromName("model-ver");
- Introspector mevsObject = loader.introspectorFromName("model-vers");
- mevObject.setValue("model-version-id", UUID.randomUUID().toString());
- mevObject.setValue("model-version", modelVersion);
- mevObject.setValue("model-Name", widgetName);
- // make a list of dynamic Entities
- List<Object> mevsList = new ArrayList<>();
- // add this one, it will be the only one in the list in this case
- mevsList.add(mevObject.getUnderlyingObject());
- mevsObject.setValue("model-ver", mevsList);
- // Have to figure out how to add my mev object to the mevsObject,
- // the modelVers is a list of dynamic entities so we can just attach the array here
- meObject.setValue("model-vers",mevsObject.getUnderlyingObject());
- }
-
- // put it out as JSON
-
- PrintWriter out = new PrintWriter(f);
- out.println(meObject.marshal(true));
- out.close();
-
- } else {
- System.out.println("File already exists for " + resource + ". Skipping.");
- }
- }
- }
- System.exit(0);
- }
+public class CreateWidgetModels {
+ /**
+ * The main method.
+ *
+ * @param args the arguments
+ * @throws Exception the exception
+ */
+ public static void main(String[] args) throws Exception {
+
+ String _apiVersion = AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP);
+ String widgetJsonDir = null;
+ String modelVersion = null;
+ 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 (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);
+ Loader loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, new SchemaVersion(_apiVersion));
+
+ // iterate the collection of resources
+
+ ArrayList<String> processedWidgets = new ArrayList<String>();
+ for (Entry<String, Introspector> aaiResEnt : loader.getAllObjects().entrySet()) {
+ Introspector meObject = loader.introspectorFromName("model");
+ // 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;
+ }
+
+ Set<String> introspectorProperties = aaiRes.getProperties();
+
+ if (!(introspectorProperties.contains("model-version-id")
+ && introspectorProperties.contains("model-invariant-id"))) {
+ System.out.println(aaiRes.getDbName() + " does not contain model properties so skipping");
+ }
+ processedWidgets.add(resource);
+
+ String widgetName = resource;
+ String filePathString = widgetJsonDir + "/" + widgetName + "-" + modelVersion + ".json";
+ File f = new File(filePathString);
+
+ String filePathString2 =
+ widgetJsonDir + "/../widget-model-json-old/" + widgetName + "-" + modelVersion + ".json";
+ File f2 = new File(filePathString2);
+
+ if (!f.exists() && !f.isDirectory()) {
+
+ if (f2.exists()) {
+ System.out.println("Using old file for " + resource + ".");
+
+ meObject = loader.unmarshal("model", new StreamSource(f2).getReader().toString());
+ // override, some of them are wrong
+ meObject.setValue("model-version", modelVersion);
+ } else {
+ System.out.println("Making new file for " + resource + ".");
+ meObject.setValue("model-invariant-id", UUID.randomUUID().toString());
+ meObject.setValue("model-type", "widget");
+ Introspector mevObject = loader.introspectorFromName("model-ver");
+ Introspector mevsObject = loader.introspectorFromName("model-vers");
+ mevObject.setValue("model-version-id", UUID.randomUUID().toString());
+ mevObject.setValue("model-version", modelVersion);
+ mevObject.setValue("model-Name", widgetName);
+ // make a list of dynamic Entities
+ List<Object> mevsList = new ArrayList<>();
+ // add this one, it will be the only one in the list in this case
+ mevsList.add(mevObject.getUnderlyingObject());
+ mevsObject.setValue("model-ver", mevsList);
+ // Have to figure out how to add my mev object to the mevsObject,
+ // the modelVers is a list of dynamic entities so we can just attach the array here
+ meObject.setValue("model-vers", mevsObject.getUnderlyingObject());
+ }
+
+ // put it out as JSON
+
+ PrintWriter out = new PrintWriter(f);
+ out.println(meObject.marshal(true));
+ out.close();
+
+ } else {
+ System.out.println("File already exists for " + resource + ". Skipping.");
+ }
+ }
+ }
+ System.exit(0);
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/introspection/Introspector.java b/aai-core/src/main/java/org/onap/aai/introspection/Introspector.java
index 21299f79..9e599a64 100644
--- a/aai-core/src/main/java/org/onap/aai/introspection/Introspector.java
+++ b/aai-core/src/main/java/org/onap/aai/introspection/Introspector.java
@@ -17,11 +17,18 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.introspection;
import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
import com.google.common.base.CaseFormat;
+
+import java.io.UnsupportedEncodingException;
+import java.lang.reflect.InvocationTargetException;
+import java.util.*;
+import java.util.stream.Collectors;
+
import org.apache.commons.lang.ClassUtils;
import org.eclipse.persistence.exceptions.DynamicException;
import org.onap.aai.config.SpringContextAware;
@@ -36,608 +43,615 @@ import org.onap.aai.schema.enums.PropertyMetadata;
import org.onap.aai.setup.SchemaVersion;
import org.onap.aai.workarounds.NamingExceptions;
-import java.io.UnsupportedEncodingException;
-import java.lang.reflect.InvocationTargetException;
-import java.util.*;
-import java.util.stream.Collectors;
-
-
public abstract class Introspector implements Cloneable {
- private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(Introspector.class);
+ private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(Introspector.class);
- protected String className;
- protected String uriChain = "";
- protected Loader loader;
- protected final NamingExceptions namingException = NamingExceptions.getInstance();
- private Set<String> uniqueProperties = null;
- private Set<String> indexedProperties = null;
- private Set<String> allKeys = null;
+ protected String className;
+ protected String uriChain = "";
+ protected Loader loader;
+ protected final NamingExceptions namingException = NamingExceptions.getInstance();
+ private Set<String> uniqueProperties = null;
+ private Set<String> indexedProperties = null;
+ private Set<String> allKeys = null;
protected CaseFormatStore caseFormatStore = null;
protected NodeIngestor nodeIngestor;
- protected Introspector(Object obj) {
- this.nodeIngestor = SpringContextAware.getBean(NodeIngestor.class);
+ protected Introspector(Object obj) {
+ this.nodeIngestor = SpringContextAware.getBean(NodeIngestor.class);
this.caseFormatStore = nodeIngestor.getCaseFormatStore();
- }
+ }
+
+ public abstract boolean hasProperty(String name);
+
+ protected String convertPropertyName(String name) {
+ return caseFormatStore.fromLowerHyphenToLowerCamel(name).orElseGet(() -> {
+ LOGGER.debug("Unable to find {} in the store from lower hyphen to lower camel", name);
+ return CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, name);
+ });
+ }
- public abstract boolean hasProperty(String name);
+ protected abstract Object get(String name);
+
+ protected abstract void set(String name, Object value);
+
+ /**
+ *
+ * @param name the property name you'd like to retrieve the value for
+ * @return the value of the property
+ */
+ public <T> T getValue(String name) {
+ String convertedName = convertPropertyName(name);
+ Object result = null;
+
+ if (this.hasProperty(name)) {
+ result = this.get(convertedName);
+ } else {
+ /* property not found - slightly ambiguous */
+ return null;
+ }
+
+ Class<?> clazz = this.getClass(name);
+ if (this.isListType(name) && result == null) {
+ try {
+ this.set(convertedName, clazz.newInstance());
+ result = this.get(convertedName);
+ } catch (DynamicException | InstantiationException | IllegalAccessException e) {
+ LOGGER.warn(e.getMessage(), e);
+ }
+ }
+
+ return (T) result;
+ }
+
+ public Introspector getWrappedValue(String name) {
+ String convertedName = convertPropertyName(name);
+ Object value = null;
+
+ if (this.hasProperty(name)) {
+ value = this.get(convertedName);
+ } else {
+ /* property not found - slightly ambiguous */
+ return null;
+ }
+
+ Class<?> clazz = this.getClass(name);
+ if (this.isListType(name) && value == null) {
+ try {
+ this.set(convertedName, clazz.newInstance());
+ value = this.get(convertedName);
+ } catch (DynamicException | InstantiationException | IllegalAccessException e) {
+ LOGGER.warn(e.getMessage(), e);
+ }
+ }
+ if (value != null) {
+ return IntrospectorFactory.newInstance(this.getModelType(), value);
+ } else {
+ // no value
+ return null;
+ }
+
+ }
+
+ public List<Introspector> getWrappedListValue(String name) {
+ String convertedName = convertPropertyName(name);
+ Object value = null;
+ List<Introspector> resultList = new ArrayList<>();
+ if (this.hasProperty(name)) {
+ value = this.get(convertedName);
+ } else {
+ /* property not found - slightly ambiguous */
+ return null;
+ }
+ boolean isListType = this.isListType(name);
+ if (!this.isListType(name)) {
+ return null;
+ }
+ Class<?> clazz = this.getClass(name);
+ if (isListType && value == null) {
+ try {
+ this.set(convertedName, clazz.newInstance());
+ value = this.get(convertedName);
+ } catch (DynamicException | InstantiationException | IllegalAccessException e) {
+ LOGGER.warn(e.getMessage(), e);
+ }
+ }
+
+ List<Object> valueList = (List<Object>) value;
+
+ for (Object item : valueList) {
+ resultList.add(IntrospectorFactory.newInstance(this.getModelType(), item));
+ }
+
+ return resultList;
- protected String convertPropertyName (String name) {
- return caseFormatStore
- .fromLowerHyphenToLowerCamel(name)
- .orElseGet(
- () -> {
- LOGGER.debug("Unable to find {} in the store from lower hyphen to lower camel", name);
- return CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, name);
+ }
+
+ public Object castValueAccordingToSchema(String name, Object obj) {
+ Object result = obj;
+ Class<?> nameClass = this.getClass(name);
+ if (nameClass == null) {
+ throw new IllegalArgumentException("property: " + name + " does not exist on " + this.getDbName());
+ }
+ if (obj != null) {
+
+ try {
+ if (!obj.getClass().getName().equals(nameClass.getName())) {
+ if (nameClass.isPrimitive()) {
+ nameClass = ClassUtils.primitiveToWrapper(nameClass);
+ result = nameClass.getConstructor(String.class).newInstance(obj.toString());
+ }
+ if (obj instanceof String) {
+ result = nameClass.getConstructor(String.class).newInstance(obj);
+ } else if (!this.isListType(name) && !this.isComplexType(name)) {
+ // box = obj.toString();
+ result = nameClass.getConstructor(String.class).newInstance(obj.toString());
+ }
}
- );
- }
-
- protected abstract Object get(String name);
- protected abstract void set(String name, Object value);
- /**
- *
- * @param name the property name you'd like to retrieve the value for
- * @return the value of the property
- */
- public <T> T getValue(String name) {
- String convertedName = convertPropertyName(name);
- Object result = null;
-
- if (this.hasProperty(name)) {
- result = this.get(convertedName);
- } else {
- /* property not found - slightly ambiguous */
- return null;
- }
-
- Class<?> clazz = this.getClass(name);
- if (this.isListType(name) && result == null) {
- try {
- this.set(convertedName, clazz.newInstance());
- result = this.get(convertedName);
- } catch (DynamicException | InstantiationException | IllegalAccessException e) {
- LOGGER.warn(e.getMessage(),e);
- }
- }
-
- return (T)result;
- }
-
- public Introspector getWrappedValue(String name) {
- String convertedName = convertPropertyName(name);
- Object value = null;
-
- if (this.hasProperty(name)) {
- value = this.get(convertedName);
- } else {
- /* property not found - slightly ambiguous */
- return null;
- }
-
- Class<?> clazz = this.getClass(name);
- if (this.isListType(name) && value == null) {
- try {
- this.set(convertedName, clazz.newInstance());
- value = this.get(convertedName);
- } catch (DynamicException | InstantiationException | IllegalAccessException e) {
- LOGGER.warn(e.getMessage(),e);
- }
- }
- if (value != null) {
- return IntrospectorFactory.newInstance(this.getModelType(), value);
- } else {
- //no value
- return null;
- }
-
- }
-
- public List<Introspector> getWrappedListValue(String name) {
- String convertedName = convertPropertyName(name);
- Object value = null;
- List<Introspector> resultList = new ArrayList<>();
- if (this.hasProperty(name)) {
- value = this.get(convertedName);
- } else {
- /* property not found - slightly ambiguous */
- return null;
- }
- boolean isListType = this.isListType(name);
- if (!this.isListType(name)) {
- return null;
- }
- Class<?> clazz = this.getClass(name);
- if (isListType && value == null) {
- try {
- this.set(convertedName, clazz.newInstance());
- value = this.get(convertedName);
- } catch (DynamicException | InstantiationException | IllegalAccessException e) {
- LOGGER.warn(e.getMessage(),e);
- }
- }
-
- List<Object> valueList = (List<Object>)value;
-
- for (Object item : valueList) {
- resultList.add(IntrospectorFactory.newInstance(this.getModelType(), item));
- }
-
- return resultList;
-
- }
-
- public Object castValueAccordingToSchema(String name, Object obj) {
- Object result = obj;
- Class<?> nameClass = this.getClass(name);
- if (nameClass == null) {
- throw new IllegalArgumentException("property: " + name + " does not exist on " + this.getDbName());
- }
- if (obj != null) {
-
- try {
- if (!obj.getClass().getName().equals(nameClass.getName())) {
- if (nameClass.isPrimitive()) {
- nameClass = ClassUtils.primitiveToWrapper(nameClass);
- result = nameClass.getConstructor(String.class).newInstance(obj.toString());
- }
- if (obj instanceof String) {
- result = nameClass.getConstructor(String.class).newInstance(obj);
- } else if (!this.isListType(name) && !this.isComplexType(name)){
- //box = obj.toString();
- result = nameClass.getConstructor(String.class).newInstance(obj.toString());
- }
- }
- } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
- | InvocationTargetException | NoSuchMethodException | SecurityException e) {
- ErrorLogHelper.logError("AAI_4017", e.getMessage());
- }
- }
- return result;
- }
-
- public List<Object> castValueAccordingToSchema(String name, List<?> objs) {
- List<Object> result = new ArrayList<>();
-
- for (Object item : objs) {
- result.add(this.castValueAccordingToSchema(name, item));
- }
-
- return result;
-
- }
- /**
- *
- * @param name the property name you'd like to set the value of
- * @param obj the value to be set
- * @return
- */
- public void setValue(String name, Object obj) {
- Object box = this.castValueAccordingToSchema(name, obj);
-
- name = convertPropertyName(name);
- this.set(name, box);
- }
- /**
- *
- * @return a list of all the properties available on the object
- */
- public abstract Set<String> getProperties();
-
- public Set<String> getProperties(PropertyPredicate<Introspector, String> p) {
- final Set<String> temp = new LinkedHashSet<>();
- this.getProperties().stream().filter(item -> {
- return p.test(this, item);
- }).forEach(item -> {
- temp.add(item);
- });
- final Set<String> result = Collections.unmodifiableSet(temp);
-
- return result;
-
- }
-
- public Set<String> getSimpleProperties(PropertyPredicate<Introspector, String> p){
- return this.getProperties()
- .stream()
- .filter(item -> p.test(this, item))
- .filter(this::isSimpleType)
- .collect(Collectors.toSet());
- }
- /**
- *
- * @return a list of the required properties on the object
- */
- public abstract Set<String> getRequiredProperties();
- /**
- *
- * @return a list of the properties that can be used to query the object in the db
- */
- public abstract Set<String> getKeys();
- /**
- *
- * @return a list of the all key properties for this object
- */
- public Set<String> getAllKeys() {
- Set<String> result = null;
- if (this.allKeys == null) {
- Set<String> keys = this.getKeys();
- result = new LinkedHashSet<>();
- result.addAll(keys);
- String altKeys = this.getMetadata(ObjectMetadata.ALTERNATE_KEYS_1);
- if (altKeys != null) {
- String[] altKeysArray = altKeys.split(",");
- for (String altKey : altKeysArray) {
- result.add(altKey);
- }
- }
- result = Collections.unmodifiableSet(result);
- this.allKeys = result;
- }
- result = this.allKeys;
- return result;
- }
-
- public Set<String> getIndexedProperties() {
- Set<String> result = null;
-
- if (this.indexedProperties == null) {
- result = new LinkedHashSet<>();
- Set<String> keys = this.getKeys();
- result.addAll(keys);
- String altKeys = this.getMetadata(ObjectMetadata.INDEXED_PROPS);
- if (altKeys != null) {
- String[] altKeysArray = altKeys.split(",");
- for (String altKey : altKeysArray) {
- result.add(altKey);
- }
- }
- this.indexedProperties = Collections.unmodifiableSet(result);
- }
- result = this.indexedProperties;
- return result;
- }
-
- public Set<String> getUniqueProperties() {
- Set<String> result = null;
- if (this.uniqueProperties == null) {
- String altKeys = this.getMetadata(ObjectMetadata.UNIQUE_PROPS);
- result = new LinkedHashSet<>();
- if (altKeys != null) {
- String[] altKeysArray = altKeys.split(",");
- for (String altKey : altKeysArray) {
- result.add(altKey);
- }
- }
- this.uniqueProperties = Collections.unmodifiableSet(result);
-
- }
- result = this.uniqueProperties;
- return result;
- }
-
- public Set<String> getDependentOn() {
- String dependentOn = this.getMetadata(ObjectMetadata.DEPENDENT_ON);
- if (dependentOn == null) {
- return new LinkedHashSet<>();
- }
- return new LinkedHashSet<>(Arrays.asList(dependentOn.split(",")));
- }
- /**
- *
- * @param name
- * @return the string name of the java class of the named property
- */
- public String getType(String name) {
- Class<?> resultClass = this.getClass(name);
- String result = "";
-
- if (resultClass != null) {
- result = resultClass.getName();
- if (result.equals("java.util.ArrayList")) {
- result = "java.util.List";
- }
- }
-
- return result;
- }
- /**
- * This will returned the generic parameterized type of the underlying
- * object if it exists
- * @param name
- * @return the generic type of the java class of the underlying object
- */
- public String getGenericType(String name) {
- Class<?> resultClass = this.getGenericTypeClass(name);
- String result = "";
-
- if (resultClass != null) {
- result = resultClass.getName();
- }
-
- return result;
- }
- /**
- *
- * @return the string name of the java class of the underlying object
- */
- public abstract String getJavaClassName();
-
- /**
- *
- * @param name the property name
- * @return the Class object
- */
- public abstract Class<?> getClass(String name);
-
- public abstract Class<?> getGenericTypeClass(String name);
-
- /**
- *
- * @param name the property name
- * @return a new instance of the underlying type of this property
- * @throws AAIUnknownObjectException
- */
- public Object newInstanceOfProperty(String name) throws AAIUnknownObjectException {
- String type = this.getType(name);
- return loader.objectFromName(type);
- }
-
- public Object newInstanceOfNestedProperty(String name) throws AAIUnknownObjectException {
- String type = this.getGenericType(name);
- return loader.objectFromName(type);
- }
-
-
- public Introspector newIntrospectorInstanceOfProperty(String name) throws AAIUnknownObjectException {
-
- Introspector result = IntrospectorFactory.newInstance(this.getModelType(), this.newInstanceOfProperty(name));
-
- return result;
-
- }
-
- public Introspector newIntrospectorInstanceOfNestedProperty(String name) throws AAIUnknownObjectException {
-
- Introspector result = IntrospectorFactory.newInstance(this.getModelType(), this.newInstanceOfNestedProperty(name));
-
- return result;
-
- }
- /**
- * Is this type not a Java String or primitive
- * @param name
- * @return
- */
- public boolean isComplexType(String name) {
- String result = this.getType(name);
-
- if (result.contains("aai") || result.equals("java.lang.Object")) {
- return true;
- } else {
- return false;
- }
- }
-
- public boolean isComplexGenericType(String name) {
- String result = this.getGenericType(name);
-
- if (result.contains("aai")) {
- return true;
- } else {
- return false;
- }
- }
-
- public boolean isSimpleType(String name) {
- return !(this.isComplexType(name) || this.isListType(name));
- }
-
- public boolean isSimpleGenericType(String name) {
- return !this.isComplexGenericType(name);
- }
-
- public boolean isListType(String name) {
- String result = this.getType(name);
-
- if (result.contains("java.util.List")) {
- return true;
- } else {
- return false;
- }
- }
-
- public boolean isContainer() {
- Set<String> props = this.getProperties();
- boolean result = false;
- if (props.size() == 1 && this.isListType(props.iterator().next())) {
- result = true;
- }
-
- return result;
- }
-
- public abstract String getChildName();
- public String getChildDBName() {
- String result = this.getChildName();
-
- result = namingException.getDBName(result);
- return result;
- }
- public abstract String getName();
-
- public String getDbName() {
- String lowerHyphen = this.getName();
-
- lowerHyphen = namingException.getDBName(lowerHyphen);
-
- return lowerHyphen;
- }
-
- public abstract ModelType getModelType();
-
- public boolean hasChild(Introspector child) {
- boolean result = false;
- //check all inheriting types for this child
- if ("true".equals(this.getMetadata(ObjectMetadata.ABSTRACT))) {
- String[] inheritors = this.getMetadata(ObjectMetadata.INHERITORS).split(",");
- for (String inheritor : inheritors) {
- try {
- Introspector temp = this.loader.introspectorFromName(inheritor);
- result = temp.hasProperty(child.getName());
- if (result) {
- break;
- }
- } catch (AAIUnknownObjectException e) {
- LOGGER.warn("Skipping inheritor " + inheritor + " (Unknown Object) " + LogFormatTools.getStackTop(e));
- }
- }
- } else {
- result = this.hasProperty(child.getName());
- }
- return result;
- }
-
- public void setURIChain(String uri) {
- this.uriChain = uri;
- }
- public abstract String getObjectId() throws UnsupportedEncodingException;
-
- public String getURI() throws UnsupportedEncodingException {
- //String result = this.uriChain;
- String result = "";
- String namespace = this.getMetadata(ObjectMetadata.NAMESPACE);
- String container = this.getMetadata(ObjectMetadata.CONTAINER);
- if (this.isContainer()) {
- result += "/" + this.getName();
- } else {
-
- if (container != null) {
- result += "/" + container;
- }
- result += "/" + this.getDbName() + "/" + this.findKey();
-
- if (namespace != null && !namespace.equals("")) {
- result = "/" + namespace + result;
- }
- }
-
-
- return result;
- }
-
- public String getGenericURI() {
- String result = "";
- if (this.isContainer()) {
- result += "/" + this.getName();
- } else {
- result += "/" + this.getDbName();
- for (String key : this.getKeys()) {
- result += "/{" + this.getDbName() + "-" + key + "}";
- }
- }
-
- return result;
- }
-
- public String getFullGenericURI() {
- String result = "";
- String namespace = this.getMetadata(ObjectMetadata.NAMESPACE);
- String container = this.getMetadata(ObjectMetadata.CONTAINER);
- if (this.isContainer()) {
- result += "/" + this.getName();
- } else {
-
-
- if (container != null) {
- result += "/" + container;
- }
- result += "/" + this.getDbName();
-
- for (String key : this.getKeys()) {
- result += "/{" + this.getDbName() + "-" + key + "}";
- }
- if (namespace != null && !namespace.equals("")) {
- result = "/" + namespace + result;
- }
-
- }
-
- return result;
- }
-
- public abstract String preProcessKey(String key);
-
- protected abstract String findKey() throws UnsupportedEncodingException;
-
- public abstract String marshal(MarshallerProperties properties);
-
- public abstract Object getUnderlyingObject();
-
- public String marshal(boolean formatted) {
- MarshallerProperties properties =
- new MarshallerProperties.Builder(MediaType.APPLICATION_JSON_TYPE).formatted(formatted).build();
-
- return marshal(properties);
- }
- public String makeSingular(String word) {
-
- String result = word;
- result = result.replaceAll("(?:([ho])es|s)$", "");
-
- if (result.equals("ClassesOfService")) {
- result = "ClassOfService";
- } else if (result.equals("CvlanTag")) {
- result = "CvlanTagEntry";
- } else if (result.equals("Metadata")) {
- result = "Metadatum";
- }
- return result;
- }
-
- protected String makePlural(String word) {
- String result = word;
-
- if (result.equals("cvlan-tag-entry")) {
- return "cvlan-tags";
- } else if (result.equals("class-of-service")) {
- return "classes-of-service";
- } else if (result.equals("metadatum")) {
- return "metadata";
- }
- result = result.replaceAll("([a-z])$", "$1s");
- result = result.replaceAll("([hox])s$", "$1es");
- /*
- if (result.equals("classes-of-services")) {
- result = "classes-of-service";
- }*/
-
- return result;
- }
-
- public abstract String getMetadata(ObjectMetadata metadataName);
- public abstract Map<PropertyMetadata, String> getPropertyMetadata(String propName);
- public Optional<String> getPropertyMetadata(String propName, PropertyMetadata metadataName) {
- final String resultValue = this.getPropertyMetadata(propName).getOrDefault(metadataName, "");
- Optional<String> result = Optional.empty();
-
- if (!resultValue.isEmpty()) {
- result = Optional.of(resultValue);
- }
- return result;
-
- }
-
- public abstract SchemaVersion getVersion();
- public Loader getLoader() {
- return this.loader;
- }
-
- public boolean isTopLevel() {
-
- return this.getMetadata(ObjectMetadata.NAMESPACE) != null;
- }
+ } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
+ | InvocationTargetException | NoSuchMethodException | SecurityException e) {
+ ErrorLogHelper.logError("AAI_4017", e.getMessage());
+ }
+ }
+ return result;
+ }
+
+ public List<Object> castValueAccordingToSchema(String name, List<?> objs) {
+ List<Object> result = new ArrayList<>();
+
+ for (Object item : objs) {
+ result.add(this.castValueAccordingToSchema(name, item));
+ }
+
+ return result;
+
+ }
+
+ /**
+ *
+ * @param name the property name you'd like to set the value of
+ * @param obj the value to be set
+ * @return
+ */
+ public void setValue(String name, Object obj) {
+ Object box = this.castValueAccordingToSchema(name, obj);
+
+ name = convertPropertyName(name);
+ this.set(name, box);
+ }
+
+ /**
+ *
+ * @return a list of all the properties available on the object
+ */
+ public abstract Set<String> getProperties();
+
+ public Set<String> getProperties(PropertyPredicate<Introspector, String> p) {
+ final Set<String> temp = new LinkedHashSet<>();
+ this.getProperties().stream().filter(item -> {
+ return p.test(this, item);
+ }).forEach(item -> {
+ temp.add(item);
+ });
+ final Set<String> result = Collections.unmodifiableSet(temp);
+
+ return result;
+
+ }
+
+ public Set<String> getSimpleProperties(PropertyPredicate<Introspector, String> p) {
+ return this.getProperties().stream().filter(item -> p.test(this, item)).filter(this::isSimpleType)
+ .collect(Collectors.toSet());
+ }
+
+ /**
+ *
+ * @return a list of the required properties on the object
+ */
+ public abstract Set<String> getRequiredProperties();
+
+ /**
+ *
+ * @return a list of the properties that can be used to query the object in the db
+ */
+ public abstract Set<String> getKeys();
+
+ /**
+ *
+ * @return a list of the all key properties for this object
+ */
+ public Set<String> getAllKeys() {
+ Set<String> result = null;
+ if (this.allKeys == null) {
+ Set<String> keys = this.getKeys();
+ result = new LinkedHashSet<>();
+ result.addAll(keys);
+ String altKeys = this.getMetadata(ObjectMetadata.ALTERNATE_KEYS_1);
+ if (altKeys != null) {
+ String[] altKeysArray = altKeys.split(",");
+ for (String altKey : altKeysArray) {
+ result.add(altKey);
+ }
+ }
+ result = Collections.unmodifiableSet(result);
+ this.allKeys = result;
+ }
+ result = this.allKeys;
+ return result;
+ }
+
+ public Set<String> getIndexedProperties() {
+ Set<String> result = null;
+
+ if (this.indexedProperties == null) {
+ result = new LinkedHashSet<>();
+ Set<String> keys = this.getKeys();
+ result.addAll(keys);
+ String altKeys = this.getMetadata(ObjectMetadata.INDEXED_PROPS);
+ if (altKeys != null) {
+ String[] altKeysArray = altKeys.split(",");
+ for (String altKey : altKeysArray) {
+ result.add(altKey);
+ }
+ }
+ this.indexedProperties = Collections.unmodifiableSet(result);
+ }
+ result = this.indexedProperties;
+ return result;
+ }
+
+ public Set<String> getUniqueProperties() {
+ Set<String> result = null;
+ if (this.uniqueProperties == null) {
+ String altKeys = this.getMetadata(ObjectMetadata.UNIQUE_PROPS);
+ result = new LinkedHashSet<>();
+ if (altKeys != null) {
+ String[] altKeysArray = altKeys.split(",");
+ for (String altKey : altKeysArray) {
+ result.add(altKey);
+ }
+ }
+ this.uniqueProperties = Collections.unmodifiableSet(result);
+
+ }
+ result = this.uniqueProperties;
+ return result;
+ }
+
+ public Set<String> getDependentOn() {
+ String dependentOn = this.getMetadata(ObjectMetadata.DEPENDENT_ON);
+ if (dependentOn == null) {
+ return new LinkedHashSet<>();
+ }
+ return new LinkedHashSet<>(Arrays.asList(dependentOn.split(",")));
+ }
+
+ /**
+ *
+ * @param name
+ * @return the string name of the java class of the named property
+ */
+ public String getType(String name) {
+ Class<?> resultClass = this.getClass(name);
+ String result = "";
+
+ if (resultClass != null) {
+ result = resultClass.getName();
+ if (result.equals("java.util.ArrayList")) {
+ result = "java.util.List";
+ }
+ }
+
+ return result;
+ }
+
+ /**
+ * This will returned the generic parameterized type of the underlying
+ * object if it exists
+ *
+ * @param name
+ * @return the generic type of the java class of the underlying object
+ */
+ public String getGenericType(String name) {
+ Class<?> resultClass = this.getGenericTypeClass(name);
+ String result = "";
+
+ if (resultClass != null) {
+ result = resultClass.getName();
+ }
+
+ return result;
+ }
+
+ /**
+ *
+ * @return the string name of the java class of the underlying object
+ */
+ public abstract String getJavaClassName();
+
+ /**
+ *
+ * @param name the property name
+ * @return the Class object
+ */
+ public abstract Class<?> getClass(String name);
+
+ public abstract Class<?> getGenericTypeClass(String name);
+
+ /**
+ *
+ * @param name the property name
+ * @return a new instance of the underlying type of this property
+ * @throws AAIUnknownObjectException
+ */
+ public Object newInstanceOfProperty(String name) throws AAIUnknownObjectException {
+ String type = this.getType(name);
+ return loader.objectFromName(type);
+ }
+
+ public Object newInstanceOfNestedProperty(String name) throws AAIUnknownObjectException {
+ String type = this.getGenericType(name);
+ return loader.objectFromName(type);
+ }
+
+ public Introspector newIntrospectorInstanceOfProperty(String name) throws AAIUnknownObjectException {
+
+ Introspector result = IntrospectorFactory.newInstance(this.getModelType(), this.newInstanceOfProperty(name));
+
+ return result;
+
+ }
+
+ public Introspector newIntrospectorInstanceOfNestedProperty(String name) throws AAIUnknownObjectException {
+
+ Introspector result =
+ IntrospectorFactory.newInstance(this.getModelType(), this.newInstanceOfNestedProperty(name));
+
+ return result;
+
+ }
+
+ /**
+ * Is this type not a Java String or primitive
+ *
+ * @param name
+ * @return
+ */
+ public boolean isComplexType(String name) {
+ String result = this.getType(name);
+
+ if (result.contains("aai") || result.equals("java.lang.Object")) {
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ public boolean isComplexGenericType(String name) {
+ String result = this.getGenericType(name);
+
+ if (result.contains("aai")) {
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ public boolean isSimpleType(String name) {
+ return !(this.isComplexType(name) || this.isListType(name));
+ }
+
+ public boolean isSimpleGenericType(String name) {
+ return !this.isComplexGenericType(name);
+ }
+
+ public boolean isListType(String name) {
+ String result = this.getType(name);
+
+ if (result.contains("java.util.List")) {
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ public boolean isContainer() {
+ Set<String> props = this.getProperties();
+ boolean result = false;
+ if (props.size() == 1 && this.isListType(props.iterator().next())) {
+ result = true;
+ }
+
+ return result;
+ }
+
+ public abstract String getChildName();
+
+ public String getChildDBName() {
+ String result = this.getChildName();
+
+ result = namingException.getDBName(result);
+ return result;
+ }
+
+ public abstract String getName();
+
+ public String getDbName() {
+ String lowerHyphen = this.getName();
+
+ lowerHyphen = namingException.getDBName(lowerHyphen);
+
+ return lowerHyphen;
+ }
+
+ public abstract ModelType getModelType();
+
+ public boolean hasChild(Introspector child) {
+ boolean result = false;
+ // check all inheriting types for this child
+ if ("true".equals(this.getMetadata(ObjectMetadata.ABSTRACT))) {
+ String[] inheritors = this.getMetadata(ObjectMetadata.INHERITORS).split(",");
+ for (String inheritor : inheritors) {
+ try {
+ Introspector temp = this.loader.introspectorFromName(inheritor);
+ result = temp.hasProperty(child.getName());
+ if (result) {
+ break;
+ }
+ } catch (AAIUnknownObjectException e) {
+ LOGGER.warn(
+ "Skipping inheritor " + inheritor + " (Unknown Object) " + LogFormatTools.getStackTop(e));
+ }
+ }
+ } else {
+ result = this.hasProperty(child.getName());
+ }
+ return result;
+ }
+
+ public void setURIChain(String uri) {
+ this.uriChain = uri;
+ }
+
+ public abstract String getObjectId() throws UnsupportedEncodingException;
+
+ public String getURI() throws UnsupportedEncodingException {
+ // String result = this.uriChain;
+ String result = "";
+ String namespace = this.getMetadata(ObjectMetadata.NAMESPACE);
+ String container = this.getMetadata(ObjectMetadata.CONTAINER);
+ if (this.isContainer()) {
+ result += "/" + this.getName();
+ } else {
+
+ if (container != null) {
+ result += "/" + container;
+ }
+ result += "/" + this.getDbName() + "/" + this.findKey();
+
+ if (namespace != null && !namespace.equals("")) {
+ result = "/" + namespace + result;
+ }
+ }
+
+ return result;
+ }
+
+ public String getGenericURI() {
+ String result = "";
+ if (this.isContainer()) {
+ result += "/" + this.getName();
+ } else {
+ result += "/" + this.getDbName();
+ for (String key : this.getKeys()) {
+ result += "/{" + this.getDbName() + "-" + key + "}";
+ }
+ }
+
+ return result;
+ }
+
+ public String getFullGenericURI() {
+ String result = "";
+ String namespace = this.getMetadata(ObjectMetadata.NAMESPACE);
+ String container = this.getMetadata(ObjectMetadata.CONTAINER);
+ if (this.isContainer()) {
+ result += "/" + this.getName();
+ } else {
+
+ if (container != null) {
+ result += "/" + container;
+ }
+ result += "/" + this.getDbName();
+
+ for (String key : this.getKeys()) {
+ result += "/{" + this.getDbName() + "-" + key + "}";
+ }
+ if (namespace != null && !namespace.equals("")) {
+ result = "/" + namespace + result;
+ }
+
+ }
+
+ return result;
+ }
+
+ public abstract String preProcessKey(String key);
+
+ protected abstract String findKey() throws UnsupportedEncodingException;
+
+ public abstract String marshal(MarshallerProperties properties);
+
+ public abstract Object getUnderlyingObject();
+
+ public String marshal(boolean formatted) {
+ MarshallerProperties properties =
+ new MarshallerProperties.Builder(MediaType.APPLICATION_JSON_TYPE).formatted(formatted).build();
+
+ return marshal(properties);
+ }
+
+ public String makeSingular(String word) {
+
+ String result = word;
+ result = result.replaceAll("(?:([ho])es|s)$", "");
+
+ if (result.equals("ClassesOfService")) {
+ result = "ClassOfService";
+ } else if (result.equals("CvlanTag")) {
+ result = "CvlanTagEntry";
+ } else if (result.equals("Metadata")) {
+ result = "Metadatum";
+ }
+ return result;
+ }
+
+ protected String makePlural(String word) {
+ String result = word;
+
+ if (result.equals("cvlan-tag-entry")) {
+ return "cvlan-tags";
+ } else if (result.equals("class-of-service")) {
+ return "classes-of-service";
+ } else if (result.equals("metadatum")) {
+ return "metadata";
+ }
+ result = result.replaceAll("([a-z])$", "$1s");
+ result = result.replaceAll("([hox])s$", "$1es");
+ /*
+ * if (result.equals("classes-of-services")) {
+ * result = "classes-of-service";
+ * }
+ */
+
+ return result;
+ }
+
+ public abstract String getMetadata(ObjectMetadata metadataName);
+
+ public abstract Map<PropertyMetadata, String> getPropertyMetadata(String propName);
+
+ public Optional<String> getPropertyMetadata(String propName, PropertyMetadata metadataName) {
+ final String resultValue = this.getPropertyMetadata(propName).getOrDefault(metadataName, "");
+ Optional<String> result = Optional.empty();
+
+ if (!resultValue.isEmpty()) {
+ result = Optional.of(resultValue);
+ }
+ return result;
+
+ }
+
+ public abstract SchemaVersion getVersion();
+
+ public Loader getLoader() {
+ return this.loader;
+ }
+
+ public boolean isTopLevel() {
+
+ return this.getMetadata(ObjectMetadata.NAMESPACE) != null;
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/introspection/IntrospectorFactory.java b/aai-core/src/main/java/org/onap/aai/introspection/IntrospectorFactory.java
index 93cd2ee1..9b161e36 100644
--- a/aai-core/src/main/java/org/onap/aai/introspection/IntrospectorFactory.java
+++ b/aai-core/src/main/java/org/onap/aai/introspection/IntrospectorFactory.java
@@ -17,42 +17,43 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.introspection;
public class IntrospectorFactory {
- /**
- * New instance.
- *
- * @param type the type
- * @param o the o
- * @return the introspector
- */
- public static Introspector newInstance(ModelType type, Object o) {
-
- if (type.equals(ModelType.MOXY)) {
- return new MoxyStrategy(o);
- } else {
- throw new IllegalArgumentException("Unknown class type: " + type);
- }
-
- }
-
- /**
- * New instance.
- *
- * @param type the type
- * @param o the o
- * @param namedType the named type
- * @return the introspector
- */
- public static Introspector newInstance(ModelType type, Object o, String namedType) {
-
- if (type.equals(ModelType.JSON)) {
- return new JSONStrategy(o, namedType);
- } else {
- throw new IllegalArgumentException("Unknown class type: " + type);
- }
-
- }
+ /**
+ * New instance.
+ *
+ * @param type the type
+ * @param o the o
+ * @return the introspector
+ */
+ public static Introspector newInstance(ModelType type, Object o) {
+
+ if (type.equals(ModelType.MOXY)) {
+ return new MoxyStrategy(o);
+ } else {
+ throw new IllegalArgumentException("Unknown class type: " + type);
+ }
+
+ }
+
+ /**
+ * New instance.
+ *
+ * @param type the type
+ * @param o the o
+ * @param namedType the named type
+ * @return the introspector
+ */
+ public static Introspector newInstance(ModelType type, Object o, String namedType) {
+
+ if (type.equals(ModelType.JSON)) {
+ return new JSONStrategy(o, namedType);
+ } else {
+ throw new IllegalArgumentException("Unknown class type: " + type);
+ }
+
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/introspection/IntrospectorWalker.java b/aai-core/src/main/java/org/onap/aai/introspection/IntrospectorWalker.java
index e406b0a6..aa5ae156 100644
--- a/aai-core/src/main/java/org/onap/aai/introspection/IntrospectorWalker.java
+++ b/aai-core/src/main/java/org/onap/aai/introspection/IntrospectorWalker.java
@@ -17,177 +17,181 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.introspection;
import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
-import org.onap.aai.exceptions.AAIException;
-import org.onap.aai.introspection.exceptions.AAIUnknownObjectException;
-import org.onap.aai.logging.LogFormatTools;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
+import org.onap.aai.exceptions.AAIException;
+import org.onap.aai.introspection.exceptions.AAIUnknownObjectException;
+import org.onap.aai.logging.LogFormatTools;
+
public class IntrospectorWalker {
- private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(IntrospectorWalker.class);
-
- private Wanderer w = null;
- private Set<String> blacklist = null;
- private boolean preventCycles = false;
- private final PropertyPredicate<Introspector, String> propVisibility;
-
- /**
- * Instantiates a new introspector walker.
- *
- * @param w the w
- * @param llBuilder the ll builder
- */
- public IntrospectorWalker(Wanderer w) {
- this.w = w;
- this.blacklist = new HashSet<>();
- this.propVisibility = null;
- }
-
- public IntrospectorWalker(Wanderer w, PropertyPredicate<Introspector, String> p) {
- this.w = w;
- this.blacklist = new HashSet<>();
- this.propVisibility = p;
- }
-
-
- /**
- * Sets the blacklist.
- *
- * @param list the new blacklist
- */
- public void setBlacklist(List<String> list) {
- blacklist.addAll(list);
- }
-
- /**
- * Prevent cycles.
- *
- * @param prevent the prevent
- */
- public void preventCycles(boolean prevent) {
- this.preventCycles = prevent;
- }
-
- /**
- * Walk.
- *
- * @param obj the obj
- * @throws AAIException
- */
- public void walk(Introspector obj) throws AAIException {
- Set<String> visited = new HashSet<>();
-
- walk(obj, null, visited);
- }
-
- /**
- * Walk.
- *
- * @param obj the obj
- * @param parent the parent
- * @throws AAIException
- */
- private void walk(Introspector obj, Introspector parent, Set<String> visited) throws AAIException {
- boolean stopRecursion = false;
- Set<String> localVisited = new HashSet<>();
- localVisited.addAll(visited);
- if (preventCycles) {
- if (visited.contains(obj.getName())) {
- stopRecursion = true;
- }
- if (!obj.isContainer()) {
- localVisited.add(obj.getName()); //so we don't recurse while walking its children
- }
- }
- Set<String> props;
- //props must duplicate the result from getProperties because
- //it is unmodifiable
- if (this.propVisibility == null) {
- props = new LinkedHashSet<>(obj.getProperties());
- } else {
- props = new LinkedHashSet<>(obj.getProperties(this.propVisibility));
- }
-
- w.processComplexObj(obj);
- props.removeAll(blacklist);
- if (!obj.isContainer()) {
- parent = obj;
- }
- for (String prop : props) {
-
- if (obj.isSimpleType(prop)) {
-
- w.processPrimitive(prop, obj);
- } else if (obj.isListType(prop) && !stopRecursion) {
-
- List<Object> listReference = obj.getValue(prop);
- boolean isComplexType = obj.isComplexGenericType(prop);
- if (isComplexType) {
- List<Introspector> list = obj.getWrappedListValue(prop);
- try {
- Introspector child = obj.newIntrospectorInstanceOfNestedProperty(prop);
- w.modifyComplexList(list, listReference, parent, child);
- for (Object item : listReference) {
- child = IntrospectorFactory.newInstance(obj.getModelType(), item);
- walk(child, parent, localVisited);
- }
- } catch (AAIUnknownObjectException e) {
- LOGGER.warn("Skipping property " + prop + " (Unknown Object) " + LogFormatTools.getStackTop(e));
- }
- } else {
- w.processPrimitiveList(prop, obj);
- }
- if (listReference.size() == 0) {
- if (isComplexType) {
- try {
- Introspector child = obj.newIntrospectorInstanceOfNestedProperty(prop);
- int size = w.createComplexListSize(parent, child);
- for (int i = 0; i < size; i++) {
- child = obj.newIntrospectorInstanceOfNestedProperty(prop);
- walk(child, parent, localVisited);
- listReference.add(child.getUnderlyingObject());
- }
-
- obj.setValue(prop, listReference);
- } catch (AAIUnknownObjectException e) {
- LOGGER.warn("Skipping property " + prop + " (Unknown Object) " + LogFormatTools.getStackTop(e));
- }
- } else if (!isComplexType){
- w.processPrimitiveList(prop, obj);
- }
- }
-
- } else if (obj.isComplexType(prop) && !stopRecursion) {
- Introspector child = null;
- if (obj.getValue(prop) != null) {
- child = IntrospectorFactory.newInstance(obj.getModelType(), obj.getValue(prop));
- } else {
- if (w.createComplexObjIfNull()) {
- try {
- child = obj.newIntrospectorInstanceOfProperty(prop);
- obj.setValue(prop, child.getUnderlyingObject());
- } catch (AAIUnknownObjectException e) {
- LOGGER.warn("Skipping property " + prop + " (Unknown Object) " + LogFormatTools.getStackTop(e));
- }
- }
- }
- if (child != null) {
- walk(child, obj, localVisited);
- }
- }
-
- }
- /*
- if (preventCycles && !obj.isContainer()) {
- visited.remove(obj.getName()); //so we can see it down another path that isn't in danger of recursing over it
- }*/
- }
+ private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(IntrospectorWalker.class);
+
+ private Wanderer w = null;
+ private Set<String> blacklist = null;
+ private boolean preventCycles = false;
+ private final PropertyPredicate<Introspector, String> propVisibility;
+
+ /**
+ * Instantiates a new introspector walker.
+ *
+ * @param w the w
+ * @param llBuilder the ll builder
+ */
+ public IntrospectorWalker(Wanderer w) {
+ this.w = w;
+ this.blacklist = new HashSet<>();
+ this.propVisibility = null;
+ }
+
+ public IntrospectorWalker(Wanderer w, PropertyPredicate<Introspector, String> p) {
+ this.w = w;
+ this.blacklist = new HashSet<>();
+ this.propVisibility = p;
+ }
+
+ /**
+ * Sets the blacklist.
+ *
+ * @param list the new blacklist
+ */
+ public void setBlacklist(List<String> list) {
+ blacklist.addAll(list);
+ }
+
+ /**
+ * Prevent cycles.
+ *
+ * @param prevent the prevent
+ */
+ public void preventCycles(boolean prevent) {
+ this.preventCycles = prevent;
+ }
+
+ /**
+ * Walk.
+ *
+ * @param obj the obj
+ * @throws AAIException
+ */
+ public void walk(Introspector obj) throws AAIException {
+ Set<String> visited = new HashSet<>();
+
+ walk(obj, null, visited);
+ }
+
+ /**
+ * Walk.
+ *
+ * @param obj the obj
+ * @param parent the parent
+ * @throws AAIException
+ */
+ private void walk(Introspector obj, Introspector parent, Set<String> visited) throws AAIException {
+ boolean stopRecursion = false;
+ Set<String> localVisited = new HashSet<>();
+ localVisited.addAll(visited);
+ if (preventCycles) {
+ if (visited.contains(obj.getName())) {
+ stopRecursion = true;
+ }
+ if (!obj.isContainer()) {
+ localVisited.add(obj.getName()); // so we don't recurse while walking its children
+ }
+ }
+ Set<String> props;
+ // props must duplicate the result from getProperties because
+ // it is unmodifiable
+ if (this.propVisibility == null) {
+ props = new LinkedHashSet<>(obj.getProperties());
+ } else {
+ props = new LinkedHashSet<>(obj.getProperties(this.propVisibility));
+ }
+
+ w.processComplexObj(obj);
+ props.removeAll(blacklist);
+ if (!obj.isContainer()) {
+ parent = obj;
+ }
+ for (String prop : props) {
+
+ if (obj.isSimpleType(prop)) {
+
+ w.processPrimitive(prop, obj);
+ } else if (obj.isListType(prop) && !stopRecursion) {
+
+ List<Object> listReference = obj.getValue(prop);
+ boolean isComplexType = obj.isComplexGenericType(prop);
+ if (isComplexType) {
+ List<Introspector> list = obj.getWrappedListValue(prop);
+ try {
+ Introspector child = obj.newIntrospectorInstanceOfNestedProperty(prop);
+ w.modifyComplexList(list, listReference, parent, child);
+ for (Object item : listReference) {
+ child = IntrospectorFactory.newInstance(obj.getModelType(), item);
+ walk(child, parent, localVisited);
+ }
+ } catch (AAIUnknownObjectException e) {
+ LOGGER.warn("Skipping property " + prop + " (Unknown Object) " + LogFormatTools.getStackTop(e));
+ }
+ } else {
+ w.processPrimitiveList(prop, obj);
+ }
+ if (listReference.size() == 0) {
+ if (isComplexType) {
+ try {
+ Introspector child = obj.newIntrospectorInstanceOfNestedProperty(prop);
+ int size = w.createComplexListSize(parent, child);
+ for (int i = 0; i < size; i++) {
+ child = obj.newIntrospectorInstanceOfNestedProperty(prop);
+ walk(child, parent, localVisited);
+ listReference.add(child.getUnderlyingObject());
+ }
+
+ obj.setValue(prop, listReference);
+ } catch (AAIUnknownObjectException e) {
+ LOGGER.warn(
+ "Skipping property " + prop + " (Unknown Object) " + LogFormatTools.getStackTop(e));
+ }
+ } else if (!isComplexType) {
+ w.processPrimitiveList(prop, obj);
+ }
+ }
+
+ } else if (obj.isComplexType(prop) && !stopRecursion) {
+ Introspector child = null;
+ if (obj.getValue(prop) != null) {
+ child = IntrospectorFactory.newInstance(obj.getModelType(), obj.getValue(prop));
+ } else {
+ if (w.createComplexObjIfNull()) {
+ try {
+ child = obj.newIntrospectorInstanceOfProperty(prop);
+ obj.setValue(prop, child.getUnderlyingObject());
+ } catch (AAIUnknownObjectException e) {
+ LOGGER.warn(
+ "Skipping property " + prop + " (Unknown Object) " + LogFormatTools.getStackTop(e));
+ }
+ }
+ }
+ if (child != null) {
+ walk(child, obj, localVisited);
+ }
+ }
+
+ }
+ /*
+ * if (preventCycles && !obj.isContainer()) {
+ * visited.remove(obj.getName()); //so we can see it down another path that isn't in danger of recursing over it
+ * }
+ */
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/introspection/JSONStrategy.java b/aai-core/src/main/java/org/onap/aai/introspection/JSONStrategy.java
index d54a9833..55580dc3 100644
--- a/aai-core/src/main/java/org/onap/aai/introspection/JSONStrategy.java
+++ b/aai-core/src/main/java/org/onap/aai/introspection/JSONStrategy.java
@@ -17,12 +17,8 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-package org.onap.aai.introspection;
-import org.json.simple.JSONObject;
-import org.onap.aai.schema.enums.ObjectMetadata;
-import org.onap.aai.schema.enums.PropertyMetadata;
-import org.onap.aai.setup.SchemaVersion;
+package org.onap.aai.introspection;
import java.io.UnsupportedEncodingException;
import java.util.List;
@@ -30,330 +26,341 @@ import java.util.Map;
import java.util.Set;
import java.util.UUID;
+import org.json.simple.JSONObject;
+import org.onap.aai.schema.enums.ObjectMetadata;
+import org.onap.aai.schema.enums.PropertyMetadata;
+import org.onap.aai.setup.SchemaVersion;
+
public class JSONStrategy extends Introspector {
- private JSONObject json = null;
- private String namedType = "";
- protected JSONStrategy(Object o) {
- super(o);
- json = (JSONObject)o;
- //Assumes you provide a wrapper
- Set<String> keySet = json.keySet();
- if (keySet.size() == 1) {
- namedType = keySet.iterator().next();
- json = (JSONObject)json.get(namedType);
- } else {
- throw new IllegalArgumentException("This object has no named type.");
- }
- }
-
- protected JSONStrategy(Object o, String namedType) {
- super(o);
- json = (JSONObject)o;
- this.namedType = namedType;
-
- }
-
- @Override
- public boolean hasProperty(String name) {
- //TODO
- return true;
- }
- @Override
- public Object getValue(String name) {
- Object result = "";
- result = json.get(name);
-
- return result;
- }
-
- @Override
- public void setValue(String name, Object obj) {
- json.put(name, obj);
-
- }
- @Override
- public Object getUnderlyingObject() {
- return this.json;
- }
-
- @Override
- public Set<String> getProperties() {
- Set<String> result = json.keySet();
- return result;
- }
-
- @Override
- public Set<String> getRequiredProperties() {
- //unknowable
-
- return this.getProperties();
- }
-
- @Override
- public Set<String> getKeys() {
- //unknowable
- return this.getProperties();
- }
-
- @Override
- public Set<String> getAllKeys() {
- //unknowable
- return this.getProperties();
- }
-
- @Override
- public String getType(String name) {
- String result = "";
- Class<?> resultClass = this.getClass(name);
- if (resultClass != null) {
- result = resultClass.getName();
- }
-
- if (result.equals("org.json.simple.JSONArray")) {
- result = "java.util.List";
- }
-
- return result;
- }
-
- @Override
- public String getGenericType(String name) {
- String result = "";
- Class<?> resultClass = this.getGenericTypeClass(name);
- if (resultClass != null) {
- result = resultClass.getName();
- }
- return result;
- }
-
- @Override
- public String getJavaClassName() {
- return json.getClass().getName();
- }
-
- @Override
- public Class<?> getClass(String name) {
- Class<?> result = null;
- result = json.get(name).getClass();
-
- return result;
- }
-
- @Override
- public Class<?> getGenericTypeClass(String name) {
- Object resultObject = null;
- Class<?> resultClass = null;
- resultObject = this.getValue(name);
- if (resultObject.getClass().getName().equals("org.json.simple.JSONArray")) {
- resultClass = ((List)resultObject).get(0).getClass();
- }
-
- return resultClass;
- }
-
- @Override
- public Object newInstanceOfProperty(String name) {
- try {
- return this.getClass(name).newInstance();
- } catch (InstantiationException | IllegalAccessException e) {
- return null;
- }
- }
-
- @Override
- public Object newInstanceOfNestedProperty(String name) {
- try {
- return this.getGenericTypeClass(name).newInstance();
- } catch (InstantiationException | IllegalAccessException e) {
- return null;
- }
- }
-
- @Override
- public boolean isComplexType(String name) {
- String result = this.getType(name);
-
- if (result.contains("JSONObject")) {
- return true;
- } else {
- return false;
- }
-
- }
-
- @Override
- public boolean isComplexGenericType(String name) {
- String result = this.getGenericType(name);
-
- if (result.contains("JSONObject")) {
- return true;
- } else {
- return false;
- }
-
- }
-
- @Override
- public boolean isListType(String name) {
- String result = this.getType(name);
-
- if (result.contains("java.util.List")) {
- return true;
- } else {
- return false;
- }
-
- }
-
- @Override
- public boolean isContainer() {
- Set<String> props = this.getProperties();
- boolean result = false;
- if (props.size() == 1 && this.isListType(props.iterator().next())) {
- result = true;
- }
-
- return result;
- }
- @Override
- protected String findKey() {
- return "";
- }
-
- @Override
- public String getName() {
- return this.namedType;
- }
-
- @Override
- public String getDbName() {
- return this.getName();
- }
-
- @Override
- public String getURI() {
-
- // use a UUID for now
- return UUID.randomUUID().toString();
- }
-
- @Override
- public String getGenericURI() {
-
- //there is none defined for this
- return "";
- }
-
- @Override
- public String preProcessKey (String key) {
-
- // don't do anything with it
- return key;
-
- }
-
- @Override
- public String marshal(MarshallerProperties properties) {
- //TODO
- return null;
- }
-
- @Override
- public Object clone() {
- //TODO
- return null;
- }
-
- /*@Override
- public String findEdgeName(String parent, String child) {
-
- // Always has for now
- return "has";
-
- }*/
-
- @Override
- public ModelType getModelType() {
- return ModelType.JSON;
- }
-
- @Override
- public Set<String> getIndexedProperties() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public String getChildName() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public boolean hasChild(Introspector child) {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- public boolean isSimpleType(String name) {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- public boolean isSimpleGenericType(String name) {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- public Map<PropertyMetadata, String> getPropertyMetadata(String prop) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public String getMetadata(ObjectMetadata metadataName) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public String getChildDBName() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public String getFullGenericURI() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- protected Object get(String name) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- protected void set(String name, Object value) {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public String getObjectId() throws UnsupportedEncodingException {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public SchemaVersion getVersion() {
- // TODO Auto-generated method stub
- return null;
- }
+ private JSONObject json = null;
+ private String namedType = "";
+
+ protected JSONStrategy(Object o) {
+ super(o);
+ json = (JSONObject) o;
+ // Assumes you provide a wrapper
+ Set<String> keySet = json.keySet();
+ if (keySet.size() == 1) {
+ namedType = keySet.iterator().next();
+ json = (JSONObject) json.get(namedType);
+ } else {
+ throw new IllegalArgumentException("This object has no named type.");
+ }
+ }
+
+ protected JSONStrategy(Object o, String namedType) {
+ super(o);
+ json = (JSONObject) o;
+ this.namedType = namedType;
+
+ }
+
+ @Override
+ public boolean hasProperty(String name) {
+ // TODO
+ return true;
+ }
+
+ @Override
+ public Object getValue(String name) {
+ Object result = "";
+ result = json.get(name);
+
+ return result;
+ }
+
+ @Override
+ public void setValue(String name, Object obj) {
+ json.put(name, obj);
+
+ }
+
+ @Override
+ public Object getUnderlyingObject() {
+ return this.json;
+ }
+
+ @Override
+ public Set<String> getProperties() {
+ Set<String> result = json.keySet();
+ return result;
+ }
+
+ @Override
+ public Set<String> getRequiredProperties() {
+ // unknowable
+
+ return this.getProperties();
+ }
+
+ @Override
+ public Set<String> getKeys() {
+ // unknowable
+ return this.getProperties();
+ }
+
+ @Override
+ public Set<String> getAllKeys() {
+ // unknowable
+ return this.getProperties();
+ }
+
+ @Override
+ public String getType(String name) {
+ String result = "";
+ Class<?> resultClass = this.getClass(name);
+ if (resultClass != null) {
+ result = resultClass.getName();
+ }
+
+ if (result.equals("org.json.simple.JSONArray")) {
+ result = "java.util.List";
+ }
+
+ return result;
+ }
+
+ @Override
+ public String getGenericType(String name) {
+ String result = "";
+ Class<?> resultClass = this.getGenericTypeClass(name);
+ if (resultClass != null) {
+ result = resultClass.getName();
+ }
+ return result;
+ }
+
+ @Override
+ public String getJavaClassName() {
+ return json.getClass().getName();
+ }
+
+ @Override
+ public Class<?> getClass(String name) {
+ Class<?> result = null;
+ result = json.get(name).getClass();
+
+ return result;
+ }
+
+ @Override
+ public Class<?> getGenericTypeClass(String name) {
+ Object resultObject = null;
+ Class<?> resultClass = null;
+ resultObject = this.getValue(name);
+ if (resultObject.getClass().getName().equals("org.json.simple.JSONArray")) {
+ resultClass = ((List) resultObject).get(0).getClass();
+ }
+
+ return resultClass;
+ }
+
+ @Override
+ public Object newInstanceOfProperty(String name) {
+ try {
+ return this.getClass(name).newInstance();
+ } catch (InstantiationException | IllegalAccessException e) {
+ return null;
+ }
+ }
+
+ @Override
+ public Object newInstanceOfNestedProperty(String name) {
+ try {
+ return this.getGenericTypeClass(name).newInstance();
+ } catch (InstantiationException | IllegalAccessException e) {
+ return null;
+ }
+ }
+
+ @Override
+ public boolean isComplexType(String name) {
+ String result = this.getType(name);
+
+ if (result.contains("JSONObject")) {
+ return true;
+ } else {
+ return false;
+ }
+
+ }
+
+ @Override
+ public boolean isComplexGenericType(String name) {
+ String result = this.getGenericType(name);
+
+ if (result.contains("JSONObject")) {
+ return true;
+ } else {
+ return false;
+ }
+
+ }
+
+ @Override
+ public boolean isListType(String name) {
+ String result = this.getType(name);
+
+ if (result.contains("java.util.List")) {
+ return true;
+ } else {
+ return false;
+ }
+
+ }
+
+ @Override
+ public boolean isContainer() {
+ Set<String> props = this.getProperties();
+ boolean result = false;
+ if (props.size() == 1 && this.isListType(props.iterator().next())) {
+ result = true;
+ }
+
+ return result;
+ }
+
+ @Override
+ protected String findKey() {
+ return "";
+ }
+
+ @Override
+ public String getName() {
+ return this.namedType;
+ }
+
+ @Override
+ public String getDbName() {
+ return this.getName();
+ }
+
+ @Override
+ public String getURI() {
+
+ // use a UUID for now
+ return UUID.randomUUID().toString();
+ }
+
+ @Override
+ public String getGenericURI() {
+
+ // there is none defined for this
+ return "";
+ }
+
+ @Override
+ public String preProcessKey(String key) {
+
+ // don't do anything with it
+ return key;
+
+ }
+
+ @Override
+ public String marshal(MarshallerProperties properties) {
+ // TODO
+ return null;
+ }
+
+ @Override
+ public Object clone() {
+ // TODO
+ return null;
+ }
+
+ /*
+ * @Override
+ * public String findEdgeName(String parent, String child) {
+ *
+ * // Always has for now
+ * return "has";
+ *
+ * }
+ */
+
+ @Override
+ public ModelType getModelType() {
+ return ModelType.JSON;
+ }
+
+ @Override
+ public Set<String> getIndexedProperties() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public String getChildName() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public boolean hasChild(Introspector child) {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ @Override
+ public boolean isSimpleType(String name) {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ @Override
+ public boolean isSimpleGenericType(String name) {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ @Override
+ public Map<PropertyMetadata, String> getPropertyMetadata(String prop) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public String getMetadata(ObjectMetadata metadataName) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public String getChildDBName() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public String getFullGenericURI() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ protected Object get(String name) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ protected void set(String name, Object value) {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public String getObjectId() throws UnsupportedEncodingException {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public SchemaVersion getVersion() {
+ // TODO Auto-generated method stub
+ return null;
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/introspection/Loader.java b/aai-core/src/main/java/org/onap/aai/introspection/Loader.java
index cae4cbb7..1da041dc 100644
--- a/aai-core/src/main/java/org/onap/aai/introspection/Loader.java
+++ b/aai-core/src/main/java/org/onap/aai/introspection/Loader.java
@@ -17,98 +17,99 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.introspection;
+import java.util.Map;
+import java.util.Set;
+
import org.onap.aai.introspection.exceptions.AAIUnknownObjectException;
import org.onap.aai.introspection.exceptions.AAIUnmarshallingException;
import org.onap.aai.restcore.MediaType;
import org.onap.aai.setup.SchemaVersion;
-import java.util.Map;
-import java.util.Set;
-
public abstract class Loader {
- private final SchemaVersion version;
- private final ModelType modelType;
-
- /**
- * Instantiates a new loader.
- *
- * @param version the version
- * @param modelType the model type
- */
- public Loader (SchemaVersion version, ModelType modelType) {
- this.version = version;
- this.modelType = modelType;
- }
+ private final SchemaVersion version;
+ private final ModelType modelType;
- /**
- * Process.
- *
- * @param version the version
- */
- protected abstract void process(SchemaVersion version);
+ /**
+ * Instantiates a new loader.
+ *
+ * @param version the version
+ * @param modelType the model type
+ */
+ public Loader(SchemaVersion version, ModelType modelType) {
+ this.version = version;
+ this.modelType = modelType;
+ }
- /**
- * Object from name.
- *
- * @param name the name
- * @return the object
- * @throws AAIUnknownObjectException
- */
- public abstract Object objectFromName(String name) throws AAIUnknownObjectException;
+ /**
+ * Process.
+ *
+ * @param version the version
+ */
+ protected abstract void process(SchemaVersion version);
- /**
- * Introspector from name.
- *
- * @param name the name
- * @return the introspector
- * @throws AAIUnknownObjectException
- */
- public abstract Introspector introspectorFromName(String name) throws AAIUnknownObjectException;
+ /**
+ * Object from name.
+ *
+ * @param name the name
+ * @return the object
+ * @throws AAIUnknownObjectException
+ */
+ public abstract Object objectFromName(String name) throws AAIUnknownObjectException;
- /**
- * Unmarshal.
- *
- * @param type the type
- * @param json the json
- * @param mediaType the media type
- * @return the introspector
- */
- public abstract Introspector unmarshal(String type, String json, MediaType mediaType) throws AAIUnmarshallingException;
+ /**
+ * Introspector from name.
+ *
+ * @param name the name
+ * @return the introspector
+ * @throws AAIUnknownObjectException
+ */
+ public abstract Introspector introspectorFromName(String name) throws AAIUnknownObjectException;
- /**
- * Unmarshal.
- *
- * @param type the type
- * @param json the json
- * @return the introspector
- */
- public Introspector unmarshal(String type, String json) throws AAIUnmarshallingException {
- return unmarshal(type, json, MediaType.APPLICATION_JSON_TYPE);
- }
+ /**
+ * Unmarshal.
+ *
+ * @param type the type
+ * @param json the json
+ * @param mediaType the media type
+ * @return the introspector
+ */
+ public abstract Introspector unmarshal(String type, String json, MediaType mediaType)
+ throws AAIUnmarshallingException;
+ /**
+ * Unmarshal.
+ *
+ * @param type the type
+ * @param json the json
+ * @return the introspector
+ */
+ public Introspector unmarshal(String type, String json) throws AAIUnmarshallingException {
+ return unmarshal(type, json, MediaType.APPLICATION_JSON_TYPE);
+ }
- /**
- * Gets the model type.
- *
- * @return the model type
- */
- public ModelType getModelType() {
- return this.modelType;
- }
+ /**
+ * Gets the model type.
+ *
+ * @return the model type
+ */
+ public ModelType getModelType() {
+ return this.modelType;
+ }
- /**
- * Gets the version.
- *
- * @return the version
- */
- public SchemaVersion getVersion() {
- return this.version;
- }
+ /**
+ * Gets the version.
+ *
+ * @return the version
+ */
+ public SchemaVersion getVersion() {
+ return this.version;
+ }
- public abstract Map<String, Introspector> getAllObjects();
+ public abstract Map<String, Introspector> getAllObjects();
public abstract Set<String> getNamedPropNodes();
}
diff --git a/aai-core/src/main/java/org/onap/aai/introspection/LoaderFactory.java b/aai-core/src/main/java/org/onap/aai/introspection/LoaderFactory.java
index 96fd7dbd..dd1bc0f0 100644
--- a/aai-core/src/main/java/org/onap/aai/introspection/LoaderFactory.java
+++ b/aai-core/src/main/java/org/onap/aai/introspection/LoaderFactory.java
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.introspection;
import java.util.Map;
@@ -26,49 +27,49 @@ import org.springframework.beans.factory.annotation.Autowired;
public class LoaderFactory {
- @Autowired
- public Map<SchemaVersion, MoxyLoader> moxyLoaderInstance;
+ @Autowired
+ public Map<SchemaVersion, MoxyLoader> moxyLoaderInstance;
- public LoaderFactory(Map<SchemaVersion, MoxyLoader> moxyLoaderInstance) {
- this.moxyLoaderInstance = moxyLoaderInstance;
- }
+ public LoaderFactory(Map<SchemaVersion, MoxyLoader> moxyLoaderInstance) {
+ this.moxyLoaderInstance = moxyLoaderInstance;
+ }
- /**
- * Creates a new Loader object.
- *
- * @param type
- * the type
- * @param version
- * the version
- * @param llBuilder
- * the ll builder
- * @return the loader
- */
- public Loader createLoaderForVersion(ModelType type, SchemaVersion version) {
+ /**
+ * Creates a new Loader object.
+ *
+ * @param type
+ * the type
+ * @param version
+ * the version
+ * @param llBuilder
+ * the ll builder
+ * @return the loader
+ */
+ public Loader createLoaderForVersion(ModelType type, SchemaVersion version) {
- if (type.equals(ModelType.MOXY)) {
- return getMoxyLoaderInstance().get(version);
- }
+ if (type.equals(ModelType.MOXY)) {
+ return getMoxyLoaderInstance().get(version);
+ }
- return null;
+ return null;
- }
+ }
- public Loader getLoaderStrategy(ModelType type, SchemaVersion version) {
+ public Loader getLoaderStrategy(ModelType type, SchemaVersion version) {
- if (type.equals(ModelType.MOXY)) {
- return getMoxyLoaderInstance().get(version);
- }
- return null;
+ if (type.equals(ModelType.MOXY)) {
+ return getMoxyLoaderInstance().get(version);
+ }
+ return null;
- }
+ }
- public Map<SchemaVersion, MoxyLoader> getMoxyLoaderInstance() {
- return moxyLoaderInstance;
- }
+ public Map<SchemaVersion, MoxyLoader> getMoxyLoaderInstance() {
+ return moxyLoaderInstance;
+ }
- public void setMoxyLoaderInstance(Map<SchemaVersion, MoxyLoader> moxyLoaderInstance) {
- this.moxyLoaderInstance = moxyLoaderInstance;
- }
+ public void setMoxyLoaderInstance(Map<SchemaVersion, MoxyLoader> moxyLoaderInstance) {
+ this.moxyLoaderInstance = moxyLoaderInstance;
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/introspection/LoaderUtil.java b/aai-core/src/main/java/org/onap/aai/introspection/LoaderUtil.java
index 16d87d96..173cc8b3 100644
--- a/aai-core/src/main/java/org/onap/aai/introspection/LoaderUtil.java
+++ b/aai-core/src/main/java/org/onap/aai/introspection/LoaderUtil.java
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.introspection;
import org.onap.aai.config.SpringContextAware;
@@ -24,9 +25,9 @@ import org.onap.aai.setup.SchemaVersions;
public class LoaderUtil {
- public static Loader getLatestVersion(){
+ public static Loader getLatestVersion() {
- LoaderFactory loaderFactory = SpringContextAware.getBean(LoaderFactory.class);
+ LoaderFactory loaderFactory = SpringContextAware.getBean(LoaderFactory.class);
SchemaVersions schemaVersions = (SchemaVersions) SpringContextAware.getBean("schemaVersions");
return loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getDefaultVersion());
diff --git a/aai-core/src/main/java/org/onap/aai/introspection/MarshallerProperties.java b/aai-core/src/main/java/org/onap/aai/introspection/MarshallerProperties.java
index 2824dbbe..776b07e6 100644
--- a/aai-core/src/main/java/org/onap/aai/introspection/MarshallerProperties.java
+++ b/aai-core/src/main/java/org/onap/aai/introspection/MarshallerProperties.java
@@ -17,122 +17,123 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.introspection;
import org.onap.aai.restcore.MediaType;
public class MarshallerProperties {
- private final MediaType type;
- private final boolean includeRoot;
- private final boolean wrapperAsArrayName;
- private final boolean formatted;
-
- /**
- * Instantiates a new marshaller properties.
- *
- * @param builder the builder
- */
- private MarshallerProperties(Builder builder) {
-
- this.type = builder.type;
- this.includeRoot = builder.includeRoot;
- this.wrapperAsArrayName = builder.wrapperAsArrayName;
- this.formatted = builder.formatted;
- }
-
- /**
- * Gets the media type.
- *
- * @return the media type
- */
- public MediaType getMediaType() {
- return this.type;
- }
-
- /**
- * Gets the include root.
- *
- * @return the include root
- */
- public boolean getIncludeRoot() {
- return this.includeRoot;
- }
-
- /**
- * Gets the wrapper as array name.
- *
- * @return the wrapper as array name
- */
- public boolean getWrapperAsArrayName() {
- return this.wrapperAsArrayName;
- }
-
- /**
- * Gets the formatted.
- *
- * @return the formatted
- */
- public boolean getFormatted() {
- return this.formatted;
- }
-
- public static class Builder {
-
- private final MediaType type;
- private boolean includeRoot = false;
- private boolean wrapperAsArrayName = true;
- private boolean formatted = false;
-
- /**
- * Instantiates a new builder.
- *
- * @param type the type
- */
- public Builder(MediaType type) {
- this.type = type;
- }
-
- /**
- * Include root.
- *
- * @param includeRoot the include root
- * @return the builder
- */
- public Builder includeRoot (boolean includeRoot) {
- this.includeRoot = includeRoot;
- return this;
- }
-
- /**
- * Wrapper as array name.
- *
- * @param wrapperAsArrayName the wrapper as array name
- * @return the builder
- */
- public Builder wrapperAsArrayName (boolean wrapperAsArrayName) {
- this.wrapperAsArrayName = wrapperAsArrayName;
- return this;
- }
-
- /**
- * Formatted.
- *
- * @param formatted the formatted
- * @return the builder
- */
- public Builder formatted (boolean formatted) {
- this.formatted = formatted;
- return this;
- }
-
- /**
- * Builds the properties.
- *
- * @return the marshaller properties
- */
- public MarshallerProperties build() {
- return new MarshallerProperties(this);
- }
- }
+ private final MediaType type;
+ private final boolean includeRoot;
+ private final boolean wrapperAsArrayName;
+ private final boolean formatted;
+
+ /**
+ * Instantiates a new marshaller properties.
+ *
+ * @param builder the builder
+ */
+ private MarshallerProperties(Builder builder) {
+
+ this.type = builder.type;
+ this.includeRoot = builder.includeRoot;
+ this.wrapperAsArrayName = builder.wrapperAsArrayName;
+ this.formatted = builder.formatted;
+ }
+
+ /**
+ * Gets the media type.
+ *
+ * @return the media type
+ */
+ public MediaType getMediaType() {
+ return this.type;
+ }
+
+ /**
+ * Gets the include root.
+ *
+ * @return the include root
+ */
+ public boolean getIncludeRoot() {
+ return this.includeRoot;
+ }
+
+ /**
+ * Gets the wrapper as array name.
+ *
+ * @return the wrapper as array name
+ */
+ public boolean getWrapperAsArrayName() {
+ return this.wrapperAsArrayName;
+ }
+
+ /**
+ * Gets the formatted.
+ *
+ * @return the formatted
+ */
+ public boolean getFormatted() {
+ return this.formatted;
+ }
+
+ public static class Builder {
+
+ private final MediaType type;
+ private boolean includeRoot = false;
+ private boolean wrapperAsArrayName = true;
+ private boolean formatted = false;
+
+ /**
+ * Instantiates a new builder.
+ *
+ * @param type the type
+ */
+ public Builder(MediaType type) {
+ this.type = type;
+ }
+
+ /**
+ * Include root.
+ *
+ * @param includeRoot the include root
+ * @return the builder
+ */
+ public Builder includeRoot(boolean includeRoot) {
+ this.includeRoot = includeRoot;
+ return this;
+ }
+
+ /**
+ * Wrapper as array name.
+ *
+ * @param wrapperAsArrayName the wrapper as array name
+ * @return the builder
+ */
+ public Builder wrapperAsArrayName(boolean wrapperAsArrayName) {
+ this.wrapperAsArrayName = wrapperAsArrayName;
+ return this;
+ }
+
+ /**
+ * Formatted.
+ *
+ * @param formatted the formatted
+ * @return the builder
+ */
+ public Builder formatted(boolean formatted) {
+ this.formatted = formatted;
+ return this;
+ }
+
+ /**
+ * Builds the properties.
+ *
+ * @return the marshaller properties
+ */
+ public MarshallerProperties build() {
+ return new MarshallerProperties(this);
+ }
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/introspection/ModelType.java b/aai-core/src/main/java/org/onap/aai/introspection/ModelType.java
index 2554c54a..9defd86e 100644
--- a/aai-core/src/main/java/org/onap/aai/introspection/ModelType.java
+++ b/aai-core/src/main/java/org/onap/aai/introspection/ModelType.java
@@ -17,8 +17,9 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.introspection;
public enum ModelType {
- MOXY, POJO, JSON
+ MOXY, POJO, JSON
}
diff --git a/aai-core/src/main/java/org/onap/aai/introspection/MoxyLoader.java b/aai-core/src/main/java/org/onap/aai/introspection/MoxyLoader.java
index 35583d7c..02254a8b 100644
--- a/aai-core/src/main/java/org/onap/aai/introspection/MoxyLoader.java
+++ b/aai-core/src/main/java/org/onap/aai/introspection/MoxyLoader.java
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.introspection;
import com.att.eelf.configuration.EELFLogger;
@@ -24,6 +25,16 @@ import com.att.eelf.configuration.EELFManager;
import com.google.common.base.CaseFormat;
import com.google.common.collect.ImmutableMap;
+import java.io.*;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import javax.xml.bind.JAXBException;
+import javax.xml.bind.Unmarshaller;
+import javax.xml.transform.stream.StreamSource;
+
import org.eclipse.persistence.dynamic.DynamicEntity;
import org.eclipse.persistence.jaxb.UnmarshallerProperties;
import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext;
@@ -38,184 +49,177 @@ import org.onap.aai.restcore.MediaType;
import org.onap.aai.schema.enums.ObjectMetadata;
import org.onap.aai.setup.SchemaVersion;
import org.onap.aai.workarounds.NamingExceptions;
-import javax.xml.bind.JAXBException;
-import javax.xml.bind.Unmarshaller;
-import javax.xml.transform.stream.StreamSource;
-import java.io.*;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
-import java.util.stream.Collectors;
public class MoxyLoader extends Loader {
private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(MoxyLoader.class);
- private DynamicJAXBContext jaxbContext = null;
- private Map<String, Introspector> allObjs = null;
+ private DynamicJAXBContext jaxbContext = null;
+ private Map<String, Introspector> allObjs = null;
- private Map<SchemaVersion, MoxyLoader> moxyLoaderFactory;
+ private Map<SchemaVersion, MoxyLoader> moxyLoaderFactory;
- private NodeIngestor nodeIngestor;
- private CaseFormatStore caseFormatStore;
+ private NodeIngestor nodeIngestor;
+ private CaseFormatStore caseFormatStore;
- private Set<String> namedProps;
+ private Set<String> namedProps;
- public MoxyLoader(SchemaVersion version, NodeIngestor nodeIngestor) {
- super(version, ModelType.MOXY);
- this.nodeIngestor = nodeIngestor;
- this.caseFormatStore = nodeIngestor.getCaseFormatStore();
- process(version);
- }
+ public MoxyLoader(SchemaVersion version, NodeIngestor nodeIngestor) {
+ super(version, ModelType.MOXY);
+ this.nodeIngestor = nodeIngestor;
+ this.caseFormatStore = nodeIngestor.getCaseFormatStore();
+ process(version);
+ }
- public MoxyLoader getMoxyLoader(SchemaVersion v) {
- return moxyLoaderFactory.get(v);
+ public MoxyLoader getMoxyLoader(SchemaVersion v) {
+ return moxyLoaderFactory.get(v);
- }
- /**
- * {@inheritDoc}
- * @throws AAIUnknownObjectException
- */
- @Override
- public Introspector introspectorFromName(String name) throws AAIUnknownObjectException {
+ }
- return IntrospectorFactory.newInstance(ModelType.MOXY, objectFromName(name));
- }
+ /**
+ * {@inheritDoc}
+ *
+ * @throws AAIUnknownObjectException
+ */
+ @Override
+ public Introspector introspectorFromName(String name) throws AAIUnknownObjectException {
- private boolean containsUpperCase(String str){
+ return IntrospectorFactory.newInstance(ModelType.MOXY, objectFromName(name));
+ }
+
+ private boolean containsUpperCase(String str) {
- for(int i = 0; i < str.length(); i++){
- if(Character.isUpperCase(str.charAt(i))){
- return true;
+ for (int i = 0; i < str.length(); i++) {
+ if (Character.isUpperCase(str.charAt(i))) {
+ return true;
}
}
return false;
}
- /**
- * {@inheritDoc}
- */
- @Override
- public Object objectFromName(String name) throws AAIUnknownObjectException {
-
- if (name == null) {
- throw new AAIUnknownObjectException("null name passed in");
- }
- final String sanitizedName = NamingExceptions.getInstance().getObjectName(name);
- final String upperCamel;
-
- //Contains any uppercase, then assume it's upper camel
- if (containsUpperCase(name)) {
- upperCamel = sanitizedName;
- } else {
- upperCamel = caseFormatStore
- .fromLowerHyphenToUpperCamel(sanitizedName)
- .orElseGet(
- () -> {
- LOGGER.debug("Unable to find {} in the store for lower hyphen to upper camel", sanitizedName);
- return CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, sanitizedName);
- }
- );
- }
-
- try {
- final DynamicEntity result = jaxbContext.newDynamicEntity(upperCamel);
-
- if (result == null) throw new AAIUnknownObjectException("Unrecognized AAI object " + name);
-
- return result;
- } catch (IllegalArgumentException e) {
- //entity does not exist
- throw new AAIUnknownObjectException("Unrecognized AAI object " + name, e);
- }
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- protected void process(SchemaVersion version) {
- /*
- * We need to have just same JaxbContext for each version
- */
- jaxbContext = nodeIngestor.getContextForVersion(version);
-
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public Introspector unmarshal(String type, String json, MediaType mediaType) throws AAIUnmarshallingException {
- try {
- final Object clazz = objectFromName(type);
- final Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
-
- if (mediaType.equals(MediaType.APPLICATION_JSON_TYPE)) {
- unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json");
- unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false);
- unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true);
- }
-
- final DynamicEntity entity = (DynamicEntity) unmarshaller.unmarshal(new StreamSource(new StringReader(json)), clazz.getClass()).getValue();
- return IntrospectorFactory.newInstance(ModelType.MOXY, entity);
- } catch (JAXBException e) {
- AAIException ex = new AAIException("AAI_4007", e);
- ErrorLogHelper.logException(ex);
- throw new AAIUnmarshallingException("Could not unmarshall: " + e.getMessage(), ex);
- } catch (AAIUnknownObjectException e) {
- throw new AAIUnmarshallingException("Could not unmarshall: " + e.getMessage(), e);
- }
- }
-
- @Override
- public Map<String, Introspector> getAllObjects() {
- if (this.allObjs != null) {
- return allObjs;
- } else {
- ImmutableMap.Builder<String, Introspector> map = new ImmutableMap.Builder<>();
- Set<String> objs = objectsInVersion();
- for (String objName : objs) {
- try {
- Introspector introspector = this.introspectorFromName(objName);
- map.put(introspector.getDbName(), introspector);
- } catch (AAIUnknownObjectException e) {
- LOGGER.warn("Unexpected AAIUnknownObjectException while running getAllObjects() " + LogFormatTools.getStackTop(e));
- }
- }
- allObjs = map.build();
- return allObjs;
- }
- }
-
- private Set<String> objectsInVersion() {
- Set<String> result = new HashSet<>();
-
- try {
- result = nodeIngestor.getObjectsInVersion(getVersion());
-
- } catch (Exception e) {
- LOGGER.warn("Exception while enumerating objects for API version " + getVersion() + " (returning partial results) " + LogFormatTools.getStackTop(e));
- }
-
- return result;
- }
-
- @Override
- public Set<String> getNamedPropNodes(){
-
- if(namedProps == null){
- namedProps = getAllObjects()
- .entrySet()
- .stream()
- .filter(
- (entry) -> entry.getValue().getMetadata(ObjectMetadata.NAME_PROPS) != null
- ).map(entry -> entry.getKey()).collect(Collectors.toSet());
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public Object objectFromName(String name) throws AAIUnknownObjectException {
+
+ if (name == null) {
+ throw new AAIUnknownObjectException("null name passed in");
+ }
+ final String sanitizedName = NamingExceptions.getInstance().getObjectName(name);
+ final String upperCamel;
+
+ // Contains any uppercase, then assume it's upper camel
+ if (containsUpperCase(name)) {
+ upperCamel = sanitizedName;
+ } else {
+ upperCamel = caseFormatStore.fromLowerHyphenToUpperCamel(sanitizedName).orElseGet(() -> {
+ LOGGER.debug("Unable to find {} in the store for lower hyphen to upper camel", sanitizedName);
+ return CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, sanitizedName);
+ });
+ }
+
+ try {
+ final DynamicEntity result = jaxbContext.newDynamicEntity(upperCamel);
+
+ if (result == null)
+ throw new AAIUnknownObjectException("Unrecognized AAI object " + name);
+
+ return result;
+ } catch (IllegalArgumentException e) {
+ // entity does not exist
+ throw new AAIUnknownObjectException("Unrecognized AAI object " + name, e);
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ protected void process(SchemaVersion version) {
+ /*
+ * We need to have just same JaxbContext for each version
+ */
+ jaxbContext = nodeIngestor.getContextForVersion(version);
+
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public Introspector unmarshal(String type, String json, MediaType mediaType) throws AAIUnmarshallingException {
+ try {
+ final Object clazz = objectFromName(type);
+ final Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
+
+ if (mediaType.equals(MediaType.APPLICATION_JSON_TYPE)) {
+ unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json");
+ unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false);
+ unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true);
+ }
+
+ final DynamicEntity entity = (DynamicEntity) unmarshaller
+ .unmarshal(new StreamSource(new StringReader(json)), clazz.getClass()).getValue();
+ return IntrospectorFactory.newInstance(ModelType.MOXY, entity);
+ } catch (JAXBException e) {
+ AAIException ex = new AAIException("AAI_4007", e);
+ ErrorLogHelper.logException(ex);
+ throw new AAIUnmarshallingException("Could not unmarshall: " + e.getMessage(), ex);
+ } catch (AAIUnknownObjectException e) {
+ throw new AAIUnmarshallingException("Could not unmarshall: " + e.getMessage(), e);
+ }
+ }
+
+ @Override
+ public Map<String, Introspector> getAllObjects() {
+ if (this.allObjs != null) {
+ return allObjs;
+ } else {
+ ImmutableMap.Builder<String, Introspector> map = new ImmutableMap.Builder<>();
+ Set<String> objs = objectsInVersion();
+ for (String objName : objs) {
+ try {
+ Introspector introspector = this.introspectorFromName(objName);
+ map.put(introspector.getDbName(), introspector);
+ } catch (AAIUnknownObjectException e) {
+ LOGGER.warn("Unexpected AAIUnknownObjectException while running getAllObjects() "
+ + LogFormatTools.getStackTop(e));
+ }
+ }
+ allObjs = map.build();
+ return allObjs;
+ }
+ }
+
+ private Set<String> objectsInVersion() {
+ Set<String> result = new HashSet<>();
+
+ try {
+ result = nodeIngestor.getObjectsInVersion(getVersion());
+
+ } catch (Exception e) {
+ LOGGER.warn("Exception while enumerating objects for API version " + getVersion()
+ + " (returning partial results) " + LogFormatTools.getStackTop(e));
+ }
+
+ return result;
+ }
+
+ @Override
+ public Set<String> getNamedPropNodes() {
+
+ if (namedProps == null) {
+ namedProps = getAllObjects().entrySet().stream()
+ .filter((entry) -> entry.getValue().getMetadata(ObjectMetadata.NAME_PROPS) != null)
+ .map(entry -> entry.getKey()).collect(Collectors.toSet());
}
return namedProps;
}
- public DynamicJAXBContext getJAXBContext() {
- return this.jaxbContext;
- }
+
+ public DynamicJAXBContext getJAXBContext() {
+ return this.jaxbContext;
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/introspection/MoxyStrategy.java b/aai-core/src/main/java/org/onap/aai/introspection/MoxyStrategy.java
index 455e7846..15311638 100644
--- a/aai-core/src/main/java/org/onap/aai/introspection/MoxyStrategy.java
+++ b/aai-core/src/main/java/org/onap/aai/introspection/MoxyStrategy.java
@@ -17,12 +17,22 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.introspection;
import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
import com.google.common.base.CaseFormat;
import com.google.common.base.Joiner;
+
+import java.io.StringWriter;
+import java.io.UnsupportedEncodingException;
+import java.util.*;
+import java.util.Map.Entry;
+
+import javax.xml.bind.JAXBException;
+import javax.xml.bind.Marshaller;
+
import org.eclipse.persistence.descriptors.ClassDescriptor;
import org.eclipse.persistence.dynamic.DynamicEntity;
import org.eclipse.persistence.dynamic.DynamicType;
@@ -42,334 +52,316 @@ import org.onap.aai.schema.enums.PropertyMetadata;
import org.onap.aai.setup.SchemaVersion;
import org.springframework.web.util.UriUtils;
-import javax.xml.bind.JAXBException;
-import javax.xml.bind.Marshaller;
-import java.io.StringWriter;
-import java.io.UnsupportedEncodingException;
-import java.util.*;
-import java.util.Map.Entry;
-
public class MoxyStrategy extends Introspector {
- private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(MoxyStrategy.class);
- private DynamicEntity internalObject = null;
- private DynamicType internalType = null;
- private DynamicJAXBContext jaxbContext = null;
- private ClassDescriptor cd = null;
- private SchemaVersion version = null;
- private Set<String> properties = null;
- private Set<String> keys = null;
- private Set<String> requiredProperties = null;
-
- private boolean isInitialized = false;
-
- protected MoxyStrategy(Object obj) {
- super(obj);
- /* must look up the correct jaxbcontext for this object */
- className = MoxyStrategy.class.getSimpleName();
- internalObject = (DynamicEntity)obj;
- version = nodeIngestor.getVersionFromClassName(internalObject.getClass().getName());
- super.loader = SpringContextAware.getBean(LoaderFactory.class).createLoaderForVersion(getModelType(), version);
- jaxbContext = nodeIngestor.getContextForVersion(version);
- String simpleName = internalObject.getClass().getName();
- internalType = jaxbContext.getDynamicType(simpleName);
-
- cd = internalType.getDescriptor();
- }
-
- private void init() {
- isInitialized = true;
-
- Set<String> props = new LinkedHashSet<>();
- for (String s : internalType.getPropertiesNames()) {
- String value = caseFormatStore
- .fromLowerCamelToLowerHyphen(s)
- .orElseGet(
- () -> {
- LOGGER.debug("Unable to find {} in the store from lower camel to lower hyphen", s);
- return CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_HYPHEN, s);
- }
- );
- props.add(value);
+ private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(MoxyStrategy.class);
+ private DynamicEntity internalObject = null;
+ private DynamicType internalType = null;
+ private DynamicJAXBContext jaxbContext = null;
+ private ClassDescriptor cd = null;
+ private SchemaVersion version = null;
+ private Set<String> properties = null;
+ private Set<String> keys = null;
+ private Set<String> requiredProperties = null;
+
+ private boolean isInitialized = false;
+
+ protected MoxyStrategy(Object obj) {
+ super(obj);
+ /* must look up the correct jaxbcontext for this object */
+ className = MoxyStrategy.class.getSimpleName();
+ internalObject = (DynamicEntity) obj;
+ version = nodeIngestor.getVersionFromClassName(internalObject.getClass().getName());
+ super.loader = SpringContextAware.getBean(LoaderFactory.class).createLoaderForVersion(getModelType(), version);
+ jaxbContext = nodeIngestor.getContextForVersion(version);
+ String simpleName = internalObject.getClass().getName();
+ internalType = jaxbContext.getDynamicType(simpleName);
+
+ cd = internalType.getDescriptor();
+ }
+
+ private void init() {
+ isInitialized = true;
+
+ Set<String> props = new LinkedHashSet<>();
+ for (String s : internalType.getPropertiesNames()) {
+ String value = caseFormatStore.fromLowerCamelToLowerHyphen(s).orElseGet(() -> {
+ LOGGER.debug("Unable to find {} in the store from lower camel to lower hyphen", s);
+ return CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_HYPHEN, s);
+ });
+ props.add(value);
+
+ }
+ props = Collections.unmodifiableSet(props);
+ this.properties = props;
+
+ Set<String> requiredProps = new LinkedHashSet<>();
+ for (DatabaseMapping dm : cd.getMappings()) {
+ if (dm.getField() instanceof XMLField) {
+ XMLField x = (XMLField) dm.getField();
+ if (x != null && x.isRequired()) {
+ requiredProps.add(this.removeXPathDescriptor(x.getName()));
+ }
+ }
+ }
+ requiredProps = Collections.unmodifiableSet(requiredProps);
+ this.requiredProperties = requiredProps;
- }
- props = Collections.unmodifiableSet(props);
- this.properties = props;
+ Set<String> keys = new LinkedHashSet<>();
- Set<String> requiredProps = new LinkedHashSet<>();
- for (DatabaseMapping dm : cd.getMappings()) {
- if (dm.getField() instanceof XMLField) {
- XMLField x = (XMLField)dm.getField();
- if (x != null && x.isRequired()) {
- requiredProps.add(this.removeXPathDescriptor(x.getName()));
- }
- }
- }
- requiredProps = Collections.unmodifiableSet(requiredProps);
- this.requiredProperties = requiredProps;
-
- Set<String> keys = new LinkedHashSet<>();
-
- for (String name : internalType.getDescriptor().getPrimaryKeyFieldNames()) {
- keys.add(this.removeXPathDescriptor(name));
- }
- keys = Collections.unmodifiableSet(keys);
- this.keys = keys;
-
-
- }
-
- @Override
- public boolean hasProperty(String name) {
- String convertedName = convertPropertyName(name);
-
- return internalType.containsProperty(convertedName);
- }
-
- @Override
- public Object get(String name) {
- return internalObject.get(name);
- }
-
- @Override
- public void set(String name, Object obj){
-
- internalObject.set(name, obj);
- }
-
- @Override
- public Set<String> getProperties() {
-
- if(!isInitialized){
- init();
- }
-
- return this.properties;
-
- }
-
- @Override
- public Set<String> getRequiredProperties() {
-
- if(!isInitialized){
- init();
- }
-
- return this.requiredProperties;
- }
-
- @Override
- public Set<String> getKeys() {
-
- if(!isInitialized){
- init();
- }
-
- return this.keys;
- }
-
- @Override
- public Map<PropertyMetadata, String> getPropertyMetadata(String prop) {
- String propName = this.convertPropertyName(prop);
- DatabaseMapping mapping = cd.getMappingForAttributeName(propName);
- Map<PropertyMetadata, String> result = new HashMap<>();
- if (mapping != null) {
- Set<Entry> entrySet = mapping.getProperties().entrySet();
- for (Entry<?,?> entry : entrySet) {
- result.put(
- PropertyMetadata.valueOf(CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, (String)entry.getKey())), (String)entry.getValue());
- }
- }
-
- return result;
- }
-
- @Override
- public String getJavaClassName() {
- return internalObject.getClass().getName();
- }
-
-
-
- @Override
- public Class<?> getClass(String name) {
- name = convertPropertyName(name);
- Class<?> resultClass = null;
- try {
- if (internalType.getPropertyType(name) == null) {
- if (cd.getMappingForAttributeName(name) instanceof XMLCompositeDirectCollectionMapping) {
- resultClass = cd.getMappingForAttributeName(name).getContainerPolicy().getContainerClass();
-
- } else if (cd.getMappingForAttributeName(name) instanceof XMLCompositeCollectionMapping) {
- resultClass = cd.getMappingForAttributeName(name).getContainerPolicy().getContainerClass();
- } else {
- ClassDescriptor referenceDiscriptor = cd.getMappingForAttributeName(name).getReferenceDescriptor();
- if (referenceDiscriptor != null) {
- resultClass = referenceDiscriptor.getJavaClass();
- } else {
- resultClass = Object.class;
- }
- }
- } else {
- resultClass = internalType.getPropertyType(name);
- }
- } catch (DynamicException e) {
- //property doesn't exist
- }
- return resultClass;
- }
-
- @Override
- public Class<?> getGenericTypeClass(String name) {
- name = convertPropertyName(name);
- Class<?> resultClass = null;
- if (internalType.getPropertyType(name) == null) {
- if (cd.getMappingForAttributeName(name) instanceof XMLCompositeDirectCollectionMapping) {
- resultClass = cd.getMappingForAttributeName(name).getFields().get(0).getType();
-
- } else if (cd.getMappingForAttributeName(name) instanceof XMLCompositeCollectionMapping) {
- resultClass = cd.getMappingForAttributeName(name).getReferenceDescriptor().getJavaClass();
- }
- }
-
- return resultClass;
- }
-
- @Override
- public Object getUnderlyingObject() {
- return this.internalObject;
- }
-
- @Override
- public String getChildName() {
-
- String className = internalObject.getClass().getSimpleName();
- String lowerHyphen = caseFormatStore
- .fromUpperCamelToLowerHyphen(className)
- .orElseGet(
- () -> {
- LOGGER.debug("Unable to find {} in the store for upper camel to lower hyphen", className);
- return CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, className);
- }
- );
+ for (String name : internalType.getDescriptor().getPrimaryKeyFieldNames()) {
+ keys.add(this.removeXPathDescriptor(name));
+ }
+ keys = Collections.unmodifiableSet(keys);
+ this.keys = keys;
- if (this.isContainer()) {
- String upperCamel = this.getGenericTypeClass(this.getProperties().iterator().next()).getSimpleName();
+ }
- lowerHyphen = caseFormatStore
- .fromUpperCamelToLowerHyphen(upperCamel)
- .orElseGet(
- () -> {
- LOGGER.debug("Unable to find {} in the store for upper camel to lower hyphen", upperCamel);
- return CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, upperCamel);
- }
- );
- }
-
- return lowerHyphen;
- }
-
- @Override
- public String getName() {
- String className = internalObject.getClass().getSimpleName();
- return caseFormatStore
- .fromUpperCamelToLowerHyphen(className)
- .orElseGet(() -> {
- LOGGER.debug("Unable to find {} in the store for upper camel to lower hyphen", className);
- return CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, className);
- });
- }
+ @Override
+ public boolean hasProperty(String name) {
+ String convertedName = convertPropertyName(name);
+
+ return internalType.containsProperty(convertedName);
+ }
- @Override
- public String getObjectId() throws UnsupportedEncodingException {
- String result = "";
- String container = this.getMetadata(ObjectMetadata.CONTAINER);
- if (this.isContainer()) {
- result += "/" + this.getName();
- } else {
+ @Override
+ public Object get(String name) {
+ return internalObject.get(name);
+ }
- if (container != null) {
- result += "/" + container;
- }
- result += "/" + this.getDbName() + "/" + this.findKey();
+ @Override
+ public void set(String name, Object obj) {
- }
+ internalObject.set(name, obj);
+ }
- return result;
- }
+ @Override
+ public Set<String> getProperties() {
- @Override
- protected String findKey() throws UnsupportedEncodingException {
- Set<String> keys = null;
- keys = this.getKeys();
- List<String> results = new ArrayList<>();
- for (String key : keys) {
- String value = UriUtils.encode(this.getValue(key).toString(), "UTF-8");
- results.add(value);
- }
+ if (!isInitialized) {
+ init();
+ }
- return Joiner.on("/").join(results);
- }
+ return this.properties;
- @Override
- public String preProcessKey (String key) {
- String result = "";
- String[] split = key.split("/");
- int i = 0;
- for (i = split.length-1; i >= 0; i--) {
+ }
- if (jaxbContext.getDynamicType(split[i]) != null) {
- break;
+ @Override
+ public Set<String> getRequiredProperties() {
- }
+ if (!isInitialized) {
+ init();
+ }
- }
- result = Joiner.on("/").join(Arrays.copyOfRange(split, 0, i));
+ return this.requiredProperties;
+ }
- return result;
+ @Override
+ public Set<String> getKeys() {
- }
+ if (!isInitialized) {
+ init();
+ }
- @Override
- public String marshal(MarshallerProperties properties) {
- StringWriter result = new StringWriter();
+ return this.keys;
+ }
+
+ @Override
+ public Map<PropertyMetadata, String> getPropertyMetadata(String prop) {
+ String propName = this.convertPropertyName(prop);
+ DatabaseMapping mapping = cd.getMappingForAttributeName(propName);
+ Map<PropertyMetadata, String> result = new HashMap<>();
+ if (mapping != null) {
+ Set<Entry> entrySet = mapping.getProperties().entrySet();
+ for (Entry<?, ?> entry : entrySet) {
+ result.put(
+ PropertyMetadata.valueOf(
+ CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, (String) entry.getKey())),
+ (String) entry.getValue());
+ }
+ }
+
+ return result;
+ }
+
+ @Override
+ public String getJavaClassName() {
+ return internalObject.getClass().getName();
+ }
+
+ @Override
+ public Class<?> getClass(String name) {
+ name = convertPropertyName(name);
+ Class<?> resultClass = null;
+ try {
+ if (internalType.getPropertyType(name) == null) {
+ if (cd.getMappingForAttributeName(name) instanceof XMLCompositeDirectCollectionMapping) {
+ resultClass = cd.getMappingForAttributeName(name).getContainerPolicy().getContainerClass();
+
+ } else if (cd.getMappingForAttributeName(name) instanceof XMLCompositeCollectionMapping) {
+ resultClass = cd.getMappingForAttributeName(name).getContainerPolicy().getContainerClass();
+ } else {
+ ClassDescriptor referenceDiscriptor = cd.getMappingForAttributeName(name).getReferenceDescriptor();
+ if (referenceDiscriptor != null) {
+ resultClass = referenceDiscriptor.getJavaClass();
+ } else {
+ resultClass = Object.class;
+ }
+ }
+ } else {
+ resultClass = internalType.getPropertyType(name);
+ }
+ } catch (DynamicException e) {
+ // property doesn't exist
+ }
+ return resultClass;
+ }
+
+ @Override
+ public Class<?> getGenericTypeClass(String name) {
+ name = convertPropertyName(name);
+ Class<?> resultClass = null;
+ if (internalType.getPropertyType(name) == null) {
+ if (cd.getMappingForAttributeName(name) instanceof XMLCompositeDirectCollectionMapping) {
+ resultClass = cd.getMappingForAttributeName(name).getFields().get(0).getType();
+
+ } else if (cd.getMappingForAttributeName(name) instanceof XMLCompositeCollectionMapping) {
+ resultClass = cd.getMappingForAttributeName(name).getReferenceDescriptor().getJavaClass();
+ }
+ }
+
+ return resultClass;
+ }
+
+ @Override
+ public Object getUnderlyingObject() {
+ return this.internalObject;
+ }
+
+ @Override
+ public String getChildName() {
+
+ String className = internalObject.getClass().getSimpleName();
+ String lowerHyphen = caseFormatStore.fromUpperCamelToLowerHyphen(className).orElseGet(() -> {
+ LOGGER.debug("Unable to find {} in the store for upper camel to lower hyphen", className);
+ return CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, className);
+ });
+
+ if (this.isContainer()) {
+ String upperCamel = this.getGenericTypeClass(this.getProperties().iterator().next()).getSimpleName();
+
+ lowerHyphen = caseFormatStore.fromUpperCamelToLowerHyphen(upperCamel).orElseGet(() -> {
+ LOGGER.debug("Unable to find {} in the store for upper camel to lower hyphen", upperCamel);
+ return CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, upperCamel);
+ });
+ }
+
+ return lowerHyphen;
+ }
+
+ @Override
+ public String getName() {
+ String className = internalObject.getClass().getSimpleName();
+ return caseFormatStore.fromUpperCamelToLowerHyphen(className).orElseGet(() -> {
+ LOGGER.debug("Unable to find {} in the store for upper camel to lower hyphen", className);
+ return CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, className);
+ });
+ }
+
+ @Override
+ public String getObjectId() throws UnsupportedEncodingException {
+ String result = "";
+ String container = this.getMetadata(ObjectMetadata.CONTAINER);
+ if (this.isContainer()) {
+ result += "/" + this.getName();
+ } else {
+
+ if (container != null) {
+ result += "/" + container;
+ }
+ result += "/" + this.getDbName() + "/" + this.findKey();
+
+ }
+
+ return result;
+ }
+
+ @Override
+ protected String findKey() throws UnsupportedEncodingException {
+ Set<String> keys = null;
+ keys = this.getKeys();
+ List<String> results = new ArrayList<>();
+ for (String key : keys) {
+ String value = UriUtils.encode(this.getValue(key).toString(), "UTF-8");
+ results.add(value);
+ }
+
+ return Joiner.on("/").join(results);
+ }
+
+ @Override
+ public String preProcessKey(String key) {
+ String result = "";
+ String[] split = key.split("/");
+ int i = 0;
+ for (i = split.length - 1; i >= 0; i--) {
+
+ if (jaxbContext.getDynamicType(split[i]) != null) {
+ break;
+
+ }
+
+ }
+ result = Joiner.on("/").join(Arrays.copyOfRange(split, 0, i));
+
+ return result;
+
+ }
+
+ @Override
+ public String marshal(MarshallerProperties properties) {
+ StringWriter result = new StringWriter();
try {
Marshaller marshaller = jaxbContext.createMarshaller();
- if (properties.getMediaType().equals(MediaType.APPLICATION_JSON_TYPE)) {
- marshaller.setProperty(org.eclipse.persistence.jaxb.MarshallerProperties.MEDIA_TYPE, "application/json");
- marshaller.setProperty(org.eclipse.persistence.jaxb.MarshallerProperties.JSON_INCLUDE_ROOT, properties.getIncludeRoot());
- marshaller.setProperty(org.eclipse.persistence.jaxb.MarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, properties.getWrapperAsArrayName());
- marshaller.setProperty(org.eclipse.persistence.jaxb.MarshallerProperties.JSON_MARSHAL_EMPTY_COLLECTIONS, false);
- }
-
- marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, properties.getFormatted());
- marshaller.marshal(this.internalObject, result);
- } catch (JAXBException e) {
+ if (properties.getMediaType().equals(MediaType.APPLICATION_JSON_TYPE)) {
+ marshaller.setProperty(org.eclipse.persistence.jaxb.MarshallerProperties.MEDIA_TYPE,
+ "application/json");
+ marshaller.setProperty(org.eclipse.persistence.jaxb.MarshallerProperties.JSON_INCLUDE_ROOT,
+ properties.getIncludeRoot());
+ marshaller.setProperty(org.eclipse.persistence.jaxb.MarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME,
+ properties.getWrapperAsArrayName());
+ marshaller.setProperty(org.eclipse.persistence.jaxb.MarshallerProperties.JSON_MARSHAL_EMPTY_COLLECTIONS,
+ false);
+ }
+
+ marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, properties.getFormatted());
+ marshaller.marshal(this.internalObject, result);
+ } catch (JAXBException e) {
LOGGER.warn("Encountered an jaxb exception during marshalling ", LogFormatTools.getStackTop(e));
- }
+ }
return result.toString();
- }
+ }
- @Override
- public ModelType getModelType() {
- return ModelType.MOXY;
- }
+ @Override
+ public ModelType getModelType() {
+ return ModelType.MOXY;
+ }
- private String removeXPathDescriptor(String name) {
+ private String removeXPathDescriptor(String name) {
- return name.replaceAll("/text\\(\\)", "");
- }
+ return name.replaceAll("/text\\(\\)", "");
+ }
- @Override
- public String getMetadata(ObjectMetadata name) {
+ @Override
+ public String getMetadata(ObjectMetadata name) {
- return (String)cd.getProperty(name.toString());
- }
+ return (String) cd.getProperty(name.toString());
+ }
- @Override
- public SchemaVersion getVersion() {
+ @Override
+ public SchemaVersion getVersion() {
- return this.version;
- }
+ return this.version;
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/introspection/PropertyPredicate.java b/aai-core/src/main/java/org/onap/aai/introspection/PropertyPredicate.java
index 1682e511..8cc7025d 100644
--- a/aai-core/src/main/java/org/onap/aai/introspection/PropertyPredicate.java
+++ b/aai-core/src/main/java/org/onap/aai/introspection/PropertyPredicate.java
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.introspection;
import java.util.function.BiPredicate;
diff --git a/aai-core/src/main/java/org/onap/aai/introspection/PropertyPredicates.java b/aai-core/src/main/java/org/onap/aai/introspection/PropertyPredicates.java
index e80bf43b..91e46d20 100644
--- a/aai-core/src/main/java/org/onap/aai/introspection/PropertyPredicates.java
+++ b/aai-core/src/main/java/org/onap/aai/introspection/PropertyPredicates.java
@@ -17,60 +17,61 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-package org.onap.aai.introspection;
-import org.onap.aai.schema.enums.PropertyMetadata;
+package org.onap.aai.introspection;
import java.util.Map;
import java.util.Set;
+import org.onap.aai.schema.enums.PropertyMetadata;
+
public final class PropertyPredicates {
- private PropertyPredicates() {
-
- }
-
- public static PropertyPredicate<Introspector, String> includeInTestGeneration() {
- return (obj, prop) -> {
- final Map<PropertyMetadata, String> map = obj.getPropertyMetadata(prop);
- if (map.containsKey(PropertyMetadata.VISIBILITY)) {
- return !(Visibility.internal.equals(Visibility.valueOf(map.get(PropertyMetadata.VISIBILITY)))
- || Visibility.deployment.equals(Visibility.valueOf(map.get(PropertyMetadata.VISIBILITY))));
- }
- if (map.containsKey("dataLocation")) {
- return false;
- }
- return true;
- };
- }
-
- public static PropertyPredicate<Introspector, String> isVisible() {
- return (obj, prop) -> {
- final Map<PropertyMetadata, String> map = obj.getPropertyMetadata(prop);
- if (map.containsKey(PropertyMetadata.VISIBILITY)) {
- return !Visibility.internal.equals(Visibility.valueOf(map.get(PropertyMetadata.VISIBILITY)));
- }
- return true;
- };
- }
-
- public static PropertyPredicate<Introspector, String> includeInExamples() {
- return (obj, prop) -> {
- final Map<PropertyMetadata, String> map = obj.getPropertyMetadata(prop);
- if (map.containsKey(PropertyMetadata.VISIBILITY)) {
- return !Visibility.internal.equals(Visibility.valueOf(map.get(PropertyMetadata.VISIBILITY)));
- }
- if (map.containsKey("dataLocation")) {
- return false;
- }
- return true;
- };
- }
-
- public static PropertyPredicate<Introspector, String> isIndexed() {
- return (obj, prop) -> {
- Set<String> indexed = obj.getIndexedProperties();
- return indexed.contains(prop);
- };
- }
+ private PropertyPredicates() {
+
+ }
+
+ public static PropertyPredicate<Introspector, String> includeInTestGeneration() {
+ return (obj, prop) -> {
+ final Map<PropertyMetadata, String> map = obj.getPropertyMetadata(prop);
+ if (map.containsKey(PropertyMetadata.VISIBILITY)) {
+ return !(Visibility.internal.equals(Visibility.valueOf(map.get(PropertyMetadata.VISIBILITY)))
+ || Visibility.deployment.equals(Visibility.valueOf(map.get(PropertyMetadata.VISIBILITY))));
+ }
+ if (map.containsKey("dataLocation")) {
+ return false;
+ }
+ return true;
+ };
+ }
+
+ public static PropertyPredicate<Introspector, String> isVisible() {
+ return (obj, prop) -> {
+ final Map<PropertyMetadata, String> map = obj.getPropertyMetadata(prop);
+ if (map.containsKey(PropertyMetadata.VISIBILITY)) {
+ return !Visibility.internal.equals(Visibility.valueOf(map.get(PropertyMetadata.VISIBILITY)));
+ }
+ return true;
+ };
+ }
+
+ public static PropertyPredicate<Introspector, String> includeInExamples() {
+ return (obj, prop) -> {
+ final Map<PropertyMetadata, String> map = obj.getPropertyMetadata(prop);
+ if (map.containsKey(PropertyMetadata.VISIBILITY)) {
+ return !Visibility.internal.equals(Visibility.valueOf(map.get(PropertyMetadata.VISIBILITY)));
+ }
+ if (map.containsKey("dataLocation")) {
+ return false;
+ }
+ return true;
+ };
+ }
+
+ public static PropertyPredicate<Introspector, String> isIndexed() {
+ return (obj, prop) -> {
+ Set<String> indexed = obj.getIndexedProperties();
+ return indexed.contains(prop);
+ };
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/introspection/Visibility.java b/aai-core/src/main/java/org/onap/aai/introspection/Visibility.java
index 71971c8a..127435a1 100644
--- a/aai-core/src/main/java/org/onap/aai/introspection/Visibility.java
+++ b/aai-core/src/main/java/org/onap/aai/introspection/Visibility.java
@@ -17,12 +17,10 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.introspection;
public enum Visibility {
- internal,
- external,
- deployment,
- all
+ internal, external, deployment, all
}
diff --git a/aai-core/src/main/java/org/onap/aai/introspection/Wanderer.java b/aai-core/src/main/java/org/onap/aai/introspection/Wanderer.java
index d97bd2d6..0f5e5f96 100644
--- a/aai-core/src/main/java/org/onap/aai/introspection/Wanderer.java
+++ b/aai-core/src/main/java/org/onap/aai/introspection/Wanderer.java
@@ -17,66 +17,68 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-package org.onap.aai.introspection;
-import org.onap.aai.exceptions.AAIException;
+package org.onap.aai.introspection;
import java.util.List;
+import org.onap.aai.exceptions.AAIException;
+
public interface Wanderer {
- /**
- * Process primitive.
- *
- * @param propName the prop name
- * @param obj the obj
- */
- public void processPrimitive(String propName, Introspector obj);
-
- /**
- * Process primitive list.
- *
- * @param propName the prop name
- * @param obj the obj
- */
- public void processPrimitiveList(String propName, Introspector obj);
-
- /**
- * Process complex obj.
- *
- * @param obj the obj
- * @throws AAIException
- */
- public void processComplexObj(Introspector obj) throws AAIException;
-
- /**
- * Modify complex list.
- *
- * @param list the list
- * @param listReference TODO
- * @param parent the parent
- * @param child the child
- */
- public void modifyComplexList(List<Introspector> list, List<Object> listReference, Introspector parent, Introspector child);
-
- /**
- * Creates the complex obj if null.
- *
- * @return true, if successful
- */
- public default boolean createComplexObjIfNull() {
- return false;
- }
-
- /**
- * Creates the complex list size.
- *
- * @param parent the parent
- * @param child the child
- * @return the int
- */
- public default int createComplexListSize(Introspector parent, Introspector child) {
- return 0;
- }
-
+ /**
+ * Process primitive.
+ *
+ * @param propName the prop name
+ * @param obj the obj
+ */
+ public void processPrimitive(String propName, Introspector obj);
+
+ /**
+ * Process primitive list.
+ *
+ * @param propName the prop name
+ * @param obj the obj
+ */
+ public void processPrimitiveList(String propName, Introspector obj);
+
+ /**
+ * Process complex obj.
+ *
+ * @param obj the obj
+ * @throws AAIException
+ */
+ public void processComplexObj(Introspector obj) throws AAIException;
+
+ /**
+ * Modify complex list.
+ *
+ * @param list the list
+ * @param listReference TODO
+ * @param parent the parent
+ * @param child the child
+ */
+ public void modifyComplexList(List<Introspector> list, List<Object> listReference, Introspector parent,
+ Introspector child);
+
+ /**
+ * Creates the complex obj if null.
+ *
+ * @return true, if successful
+ */
+ public default boolean createComplexObjIfNull() {
+ return false;
+ }
+
+ /**
+ * Creates the complex list size.
+ *
+ * @param parent the parent
+ * @param child the child
+ * @return the int
+ */
+ public default int createComplexListSize(Introspector parent, Introspector child) {
+ return 0;
+ }
+
}
diff --git a/aai-core/src/main/java/org/onap/aai/introspection/exceptions/AAIUnknownObjectException.java b/aai-core/src/main/java/org/onap/aai/introspection/exceptions/AAIUnknownObjectException.java
index 4086b3cb..9f3fbe0d 100644
--- a/aai-core/src/main/java/org/onap/aai/introspection/exceptions/AAIUnknownObjectException.java
+++ b/aai-core/src/main/java/org/onap/aai/introspection/exceptions/AAIUnknownObjectException.java
@@ -17,25 +17,27 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.introspection.exceptions;
import org.onap.aai.exceptions.AAIException;
public class AAIUnknownObjectException extends AAIException {
- private static final long serialVersionUID = -504200228742133774L;
+ private static final long serialVersionUID = -504200228742133774L;
- public AAIUnknownObjectException() {}
+ public AAIUnknownObjectException() {
+ }
- public AAIUnknownObjectException(String message) {
- super("AAI_3000", message);
- }
+ public AAIUnknownObjectException(String message) {
+ super("AAI_3000", message);
+ }
- public AAIUnknownObjectException(Throwable cause) {
- super("AAI_3000", cause);
- }
+ public AAIUnknownObjectException(Throwable cause) {
+ super("AAI_3000", cause);
+ }
- public AAIUnknownObjectException(String message, Throwable cause) {
- super("AAI_3000", cause, message);
- }
+ public AAIUnknownObjectException(String message, Throwable cause) {
+ super("AAI_3000", cause, message);
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/introspection/exceptions/AAIUnmarshallingException.java b/aai-core/src/main/java/org/onap/aai/introspection/exceptions/AAIUnmarshallingException.java
index 2eb3dad7..5dfc5d3e 100644
--- a/aai-core/src/main/java/org/onap/aai/introspection/exceptions/AAIUnmarshallingException.java
+++ b/aai-core/src/main/java/org/onap/aai/introspection/exceptions/AAIUnmarshallingException.java
@@ -17,25 +17,27 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.introspection.exceptions;
import org.onap.aai.exceptions.AAIException;
public class AAIUnmarshallingException extends AAIException {
- private static final long serialVersionUID = -5615651557821878103L;
+ private static final long serialVersionUID = -5615651557821878103L;
- public AAIUnmarshallingException() {}
+ public AAIUnmarshallingException() {
+ }
- public AAIUnmarshallingException(String message) {
- super("AAI_3000", message);
- }
+ public AAIUnmarshallingException(String message) {
+ super("AAI_3000", message);
+ }
- public AAIUnmarshallingException(Throwable cause) {
- super("AAI_3000",cause);
- }
+ public AAIUnmarshallingException(Throwable cause) {
+ super("AAI_3000", cause);
+ }
- public AAIUnmarshallingException(String message, Throwable cause) {
- super("AAI_3000", cause, message);
- }
+ public AAIUnmarshallingException(String message, Throwable cause) {
+ super("AAI_3000", cause, message);
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/introspection/generator/CreateExample.java b/aai-core/src/main/java/org/onap/aai/introspection/generator/CreateExample.java
index 3409d175..73f0a346 100644
--- a/aai-core/src/main/java/org/onap/aai/introspection/generator/CreateExample.java
+++ b/aai-core/src/main/java/org/onap/aai/introspection/generator/CreateExample.java
@@ -17,149 +17,151 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-package org.onap.aai.introspection.generator;
-import org.onap.aai.exceptions.AAIException;
-import org.onap.aai.introspection.*;
+package org.onap.aai.introspection.generator;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;
+import org.onap.aai.exceptions.AAIException;
+import org.onap.aai.introspection.*;
+
public class CreateExample implements Wanderer {
- private SecureRandom rand = new SecureRandom();
- private final long range = 100000000L;
- private Loader loader = null;
- private Introspector result = null;
- private String objectName = null;
- private List<String> blacklist = null;
-
- /**
- * Instantiates a new creates the example.
- *
- * @param loader the loader
- * @param objectName the object name
- */
- public CreateExample(Loader loader, String objectName) {
-
- this.loader = loader;
- this.objectName = objectName;
- this.blacklist = new ArrayList<>();
-
- }
-
- /**
- * Gets the example object.
- *
- * @return the example object
- * @throws AAIException
- */
- public Introspector getExampleObject() throws AAIException {
- result = loader.introspectorFromName(objectName);
- blacklist = new ArrayList<>();
- blacklist.add("any");
- blacklist.add("relationship-list");
- if (!result.isContainer()) {
- blacklist.add("resource-version");
- }
- IntrospectorWalker walker = new IntrospectorWalker(this, PropertyPredicates.includeInExamples());
-
- walker.preventCycles(true);
- walker.setBlacklist(blacklist);
- walker.walk(result);
- //this.getExampleObject(result);
-
- return result;
- }
-
- /**
- * Gets the value.
- *
- * @param property the property
- * @param type the type
- * @param suffix the suffix
- * @return the value
- */
- private Object getValue(String property, String type, String suffix) {
- long randLong = (long)(rand.nextDouble()*range);
- Integer randInt = rand.nextInt(100000);
- Integer randShrt = rand.nextInt(20000);
- short randShort = randShrt.shortValue();
-
- Object newObj = null;
- if (type.contains("java.lang.String")) {
- newObj = "example-" + property + "-val-" + randInt + suffix;
- } else if ( type.toLowerCase().equals("long") ||type.contains("java.lang.Long")) {
- newObj = randLong;
- } else if(type.toLowerCase().equals("boolean") || type.contains("java.lang.Boolean")){
- newObj = Boolean.TRUE;
- } else if ( type.toLowerCase().equals("int") || type.contains("java.lang.Integer")){
- newObj = randInt;
- } else if ( type.toLowerCase().equals("short") || type.contains("java.lang.Short")){
- newObj = randShort;
- }
-
- return newObj;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public void processPrimitive(String propName, Introspector obj) {
- String propType = obj.getType(propName);
-
- Object val = this.getValue(propName, propType, "");
- obj.setValue(propName, val);
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public void processPrimitiveList(String propName, Introspector obj) {
- int listSize = 2;
- String propType = "";
- List<Object> list = new ArrayList<>();
- for (int i = 0; i < listSize; i++) {
- propType = obj.getGenericType(propName);
- Object val = this.getValue(propName, propType, "-" + (i + 1));
- list.add(val);
- }
- obj.setValue(propName, list);
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public void processComplexObj(Introspector obj) {
-
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public void modifyComplexList(List<Introspector> list, List<Object> listReference, Introspector parent, Introspector child) {
- // TODO Auto-generated method stub
-
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean createComplexObjIfNull() {
- return true;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public int createComplexListSize(Introspector parent, Introspector child) {
- return 1;
- }
+ private SecureRandom rand = new SecureRandom();
+ private final long range = 100000000L;
+ private Loader loader = null;
+ private Introspector result = null;
+ private String objectName = null;
+ private List<String> blacklist = null;
+
+ /**
+ * Instantiates a new creates the example.
+ *
+ * @param loader the loader
+ * @param objectName the object name
+ */
+ public CreateExample(Loader loader, String objectName) {
+
+ this.loader = loader;
+ this.objectName = objectName;
+ this.blacklist = new ArrayList<>();
+
+ }
+
+ /**
+ * Gets the example object.
+ *
+ * @return the example object
+ * @throws AAIException
+ */
+ public Introspector getExampleObject() throws AAIException {
+ result = loader.introspectorFromName(objectName);
+ blacklist = new ArrayList<>();
+ blacklist.add("any");
+ blacklist.add("relationship-list");
+ if (!result.isContainer()) {
+ blacklist.add("resource-version");
+ }
+ IntrospectorWalker walker = new IntrospectorWalker(this, PropertyPredicates.includeInExamples());
+
+ walker.preventCycles(true);
+ walker.setBlacklist(blacklist);
+ walker.walk(result);
+ // this.getExampleObject(result);
+
+ return result;
+ }
+
+ /**
+ * Gets the value.
+ *
+ * @param property the property
+ * @param type the type
+ * @param suffix the suffix
+ * @return the value
+ */
+ private Object getValue(String property, String type, String suffix) {
+ long randLong = (long) (rand.nextDouble() * range);
+ Integer randInt = rand.nextInt(100000);
+ Integer randShrt = rand.nextInt(20000);
+ short randShort = randShrt.shortValue();
+
+ Object newObj = null;
+ if (type.contains("java.lang.String")) {
+ newObj = "example-" + property + "-val-" + randInt + suffix;
+ } else if (type.toLowerCase().equals("long") || type.contains("java.lang.Long")) {
+ newObj = randLong;
+ } else if (type.toLowerCase().equals("boolean") || type.contains("java.lang.Boolean")) {
+ newObj = Boolean.TRUE;
+ } else if (type.toLowerCase().equals("int") || type.contains("java.lang.Integer")) {
+ newObj = randInt;
+ } else if (type.toLowerCase().equals("short") || type.contains("java.lang.Short")) {
+ newObj = randShort;
+ }
+
+ return newObj;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public void processPrimitive(String propName, Introspector obj) {
+ String propType = obj.getType(propName);
+
+ Object val = this.getValue(propName, propType, "");
+ obj.setValue(propName, val);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public void processPrimitiveList(String propName, Introspector obj) {
+ int listSize = 2;
+ String propType = "";
+ List<Object> list = new ArrayList<>();
+ for (int i = 0; i < listSize; i++) {
+ propType = obj.getGenericType(propName);
+ Object val = this.getValue(propName, propType, "-" + (i + 1));
+ list.add(val);
+ }
+ obj.setValue(propName, list);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public void processComplexObj(Introspector obj) {
+
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public void modifyComplexList(List<Introspector> list, List<Object> listReference, Introspector parent,
+ Introspector child) {
+ // TODO Auto-generated method stub
+
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public boolean createComplexObjIfNull() {
+ return true;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public int createComplexListSize(Introspector parent, Introspector child) {
+ return 1;
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/introspection/sideeffect/DataCopy.java b/aai-core/src/main/java/org/onap/aai/introspection/sideeffect/DataCopy.java
index 8a8d74f9..6a6ee4c1 100644
--- a/aai-core/src/main/java/org/onap/aai/introspection/sideeffect/DataCopy.java
+++ b/aai-core/src/main/java/org/onap/aai/introspection/sideeffect/DataCopy.java
@@ -17,8 +17,20 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.introspection.sideeffect;
+import java.io.UnsupportedEncodingException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map.Entry;
+import java.util.Objects;
+import java.util.Optional;
+
+import javax.ws.rs.core.MultivaluedMap;
+
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.introspection.Introspector;
@@ -30,59 +42,51 @@ import org.onap.aai.schema.enums.PropertyMetadata;
import org.onap.aai.serialization.db.DBSerializer;
import org.onap.aai.serialization.engines.TransactionalGraphEngine;
-import javax.ws.rs.core.MultivaluedMap;
-import java.io.UnsupportedEncodingException;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map.Entry;
-import java.util.Objects;
-import java.util.Optional;
+public class DataCopy extends SideEffect {
+ public DataCopy(Introspector obj, Vertex self, TransactionalGraphEngine dbEngine, DBSerializer serializer) {
+ super(obj, self, dbEngine, serializer);
+ }
-public class DataCopy extends SideEffect {
+ @Override
+ protected void processURI(Optional<String> completeUri, Entry<String, String> entry)
+ throws URISyntaxException, UnsupportedEncodingException, AAIException {
+ if (completeUri.isPresent()) {
+ URI uri = new URI(completeUri.get());
+ MultivaluedMap<String, String> map = URITools.getQueryMap(uri);
+ QueryParser uriQuery = dbEngine.getQueryBuilder(this.latestLoader).createQueryFromURI(uri, map);
+ List<Vertex> results = uriQuery.getQueryBuilder().toList();
+ Introspector resultObj = this.latestLoader.introspectorFromName(uriQuery.getResultType());
+ if (results.size() == 1) {
+ serializer.dbToObject(Collections.singletonList(results.get(0)), resultObj, 0, true, "false");
+ try {
+ obj.setValue(entry.getKey(), Objects.requireNonNull(resultObj.getValue(uri.getFragment()),
+ uri.getFragment() + " was null"));
+ } catch (NullPointerException e) {
+ throw new AAIMissingRequiredPropertyException(
+ "property " + uri.getFragment() + " not found at " + uri);
+ }
+ } else {
+ if (results.isEmpty()) {
+ throw new AAIException("AAI_6114", "object located at " + uri + " not found");
+ } else if (results.size() > 1) {
+ throw new AAIMultiplePropertiesException(
+ "multiple values of " + entry.getKey() + " found when searching " + uri);
+ }
+ }
+ } else {
+ // skip processing because no required properties were specified
+ }
+ }
-
- public DataCopy(Introspector obj, Vertex self, TransactionalGraphEngine dbEngine, DBSerializer serializer) {
- super(obj, self, dbEngine, serializer);
- }
-
- @Override
- protected void processURI(Optional<String> completeUri, Entry<String, String> entry) throws URISyntaxException, UnsupportedEncodingException, AAIException {
- if (completeUri.isPresent()) {
- URI uri = new URI(completeUri.get());
- MultivaluedMap<String, String> map = URITools.getQueryMap(uri);
- QueryParser uriQuery = dbEngine.getQueryBuilder(this.latestLoader).createQueryFromURI(uri, map);
- List<Vertex> results = uriQuery.getQueryBuilder().toList();
- Introspector resultObj = this.latestLoader.introspectorFromName(uriQuery.getResultType());
- if (results.size() == 1) {
- serializer.dbToObject(Collections.singletonList(results.get(0)), resultObj, 0, true, "false");
- try {
- obj.setValue(entry.getKey(), Objects.requireNonNull(resultObj.getValue(uri.getFragment()), uri.getFragment() + " was null"));
- } catch (NullPointerException e) {
- throw new AAIMissingRequiredPropertyException("property " + uri.getFragment() + " not found at " + uri);
- }
- } else {
- if (results.isEmpty()) {
- throw new AAIException("AAI_6114", "object located at " + uri + " not found");
- } else if (results.size() > 1) {
- throw new AAIMultiplePropertiesException("multiple values of " + entry.getKey() + " found when searching " + uri);
- }
- }
- } else {
- //skip processing because no required properties were specified
- }
- }
+ @Override
+ protected PropertyMetadata getPropertyMetadata() {
+ return PropertyMetadata.DATA_COPY;
+ }
- @Override
- protected PropertyMetadata getPropertyMetadata() {
- return PropertyMetadata.DATA_COPY;
- }
+ @Override
+ protected boolean replaceWithWildcard() {
+ return false;
+ }
- @Override
- protected boolean replaceWithWildcard() {
- return false;
- }
-
}
diff --git a/aai-core/src/main/java/org/onap/aai/introspection/sideeffect/DataLinkReader.java b/aai-core/src/main/java/org/onap/aai/introspection/sideeffect/DataLinkReader.java
index 7a35910d..42b361dd 100644
--- a/aai-core/src/main/java/org/onap/aai/introspection/sideeffect/DataLinkReader.java
+++ b/aai-core/src/main/java/org/onap/aai/introspection/sideeffect/DataLinkReader.java
@@ -17,8 +17,21 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.introspection.sideeffect;
+import java.io.UnsupportedEncodingException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Optional;
+import java.util.regex.Matcher;
+
+import javax.ws.rs.core.MultivaluedMap;
+
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.onap.aai.db.props.AAIProperties;
import org.onap.aai.exceptions.AAIException;
@@ -30,67 +43,59 @@ import org.onap.aai.schema.enums.PropertyMetadata;
import org.onap.aai.serialization.db.DBSerializer;
import org.onap.aai.serialization.engines.TransactionalGraphEngine;
-import javax.ws.rs.core.MultivaluedMap;
-import java.io.UnsupportedEncodingException;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Optional;
-import java.util.regex.Matcher;
-
public class DataLinkReader extends SideEffect {
-
- public DataLinkReader(Introspector obj, Vertex self, TransactionalGraphEngine dbEngine, DBSerializer serializer) {
- super(obj, self, dbEngine, serializer);
- }
-
- @Override
- protected boolean replaceWithWildcard() {
- return true;
- }
- @Override
- protected PropertyMetadata getPropertyMetadata() {
- return PropertyMetadata.DATA_LINK;
- }
+ public DataLinkReader(Introspector obj, Vertex self, TransactionalGraphEngine dbEngine, DBSerializer serializer) {
+ super(obj, self, dbEngine, serializer);
+ }
+
+ @Override
+ protected boolean replaceWithWildcard() {
+ return true;
+ }
+
+ @Override
+ protected PropertyMetadata getPropertyMetadata() {
+ return PropertyMetadata.DATA_LINK;
+ }
+
+ @Override
+ protected void processURI(Optional<String> completeUri, Entry<String, String> entry)
+ throws URISyntaxException, UnsupportedEncodingException, AAIException {
+
+ if (completeUri.isPresent()) {
+ URI uri = new URI(completeUri.get());
+ MultivaluedMap<String, String> map = URITools.getQueryMap(uri);
+ QueryParser uriQuery = dbEngine.getQueryBuilder(this.latestLoader).createQueryFromURI(uri, map);
+ List<Vertex> results =
+ uriQuery.getQueryBuilder().getVerticesByProperty(AAIProperties.LINKED, true).toList();
+ if (results.size() == 1) {
+ if (results.get(0).<Boolean>property(AAIProperties.LINKED).orElse(false)
+ && obj.getValue(entry.getKey()) == null) {
+ obj.setValue(entry.getKey(), results.get(0).property(entry.getKey()).orElse(null));
+ }
+ } else {
+ // log something about not being able to return any values because there was more than one
+ }
+ }
+ }
- @Override
- protected void processURI(Optional<String> completeUri, Entry<String, String> entry)
- throws URISyntaxException, UnsupportedEncodingException, AAIException {
+ /**
+ * always fuzzy search on reads
+ */
+ @Override
+ protected Map<String, String> findProperties(Introspector obj, String uriString)
+ throws AAIMissingRequiredPropertyException {
- if (completeUri.isPresent()) {
- URI uri = new URI(completeUri.get());
- MultivaluedMap<String, String> map = URITools.getQueryMap(uri);
- QueryParser uriQuery = dbEngine.getQueryBuilder(this.latestLoader).createQueryFromURI(uri, map);
- List<Vertex> results = uriQuery.getQueryBuilder().getVerticesByProperty(AAIProperties.LINKED, true).toList();
- if (results.size() == 1) {
- if (results.get(0).<Boolean>property(AAIProperties.LINKED).orElse(false) && obj.getValue(entry.getKey()) == null) {
- obj.setValue(entry.getKey(), results.get(0).property(entry.getKey()).orElse(null));
- }
- } else {
- //log something about not being able to return any values because there was more than one
- }
- }
- }
-
- /**
- * always fuzzy search on reads
- */
- @Override
- protected Map<String, String> findProperties(Introspector obj, String uriString) throws AAIMissingRequiredPropertyException {
-
- final Map<String, String> result = new HashMap<>();
- Matcher m = template.matcher(uriString);
- while (m.find()) {
- String propName = m.group(1);
- if (replaceWithWildcard()) {
- result.put(propName, "*");
- }
- }
- return result;
- }
+ final Map<String, String> result = new HashMap<>();
+ Matcher m = template.matcher(uriString);
+ while (m.find()) {
+ String propName = m.group(1);
+ if (replaceWithWildcard()) {
+ result.put(propName, "*");
+ }
+ }
+ return result;
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/introspection/sideeffect/DataLinkWriter.java b/aai-core/src/main/java/org/onap/aai/introspection/sideeffect/DataLinkWriter.java
index 1c15c8b3..16f30531 100644
--- a/aai-core/src/main/java/org/onap/aai/introspection/sideeffect/DataLinkWriter.java
+++ b/aai-core/src/main/java/org/onap/aai/introspection/sideeffect/DataLinkWriter.java
@@ -17,8 +17,18 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.introspection.sideeffect;
+import java.io.UnsupportedEncodingException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.List;
+import java.util.Map.Entry;
+import java.util.Optional;
+
+import javax.ws.rs.core.MultivaluedMap;
+
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.onap.aai.db.props.AAIProperties;
import org.onap.aai.exceptions.AAIException;
@@ -31,78 +41,75 @@ import org.onap.aai.schema.enums.PropertyMetadata;
import org.onap.aai.serialization.db.DBSerializer;
import org.onap.aai.serialization.engines.TransactionalGraphEngine;
-import javax.ws.rs.core.MultivaluedMap;
-import java.io.UnsupportedEncodingException;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.util.List;
-import java.util.Map.Entry;
-import java.util.Optional;
-
public class DataLinkWriter extends SideEffect {
- public DataLinkWriter(Introspector obj, Vertex self, TransactionalGraphEngine dbEngine, DBSerializer serializer) {
- super(obj, self, dbEngine, serializer);
- }
+ public DataLinkWriter(Introspector obj, Vertex self, TransactionalGraphEngine dbEngine, DBSerializer serializer) {
+ super(obj, self, dbEngine, serializer);
+ }
+
+ @Override
+ protected PropertyMetadata getPropertyMetadata() {
+ return PropertyMetadata.DATA_LINK;
+ }
- @Override
- protected PropertyMetadata getPropertyMetadata() {
- return PropertyMetadata.DATA_LINK;
- }
+ @Override
+ protected void processURI(Optional<String> completeUri, Entry<String, String> entry)
+ throws URISyntaxException, UnsupportedEncodingException, AAIException {
+ if (completeUri.isPresent()) {
+ URI uri = new URI(completeUri.get());
+ MultivaluedMap<String, String> map = URITools.getQueryMap(uri);
+ QueryParser uriQuery = dbEngine.getQueryBuilder(this.latestLoader).createQueryFromURI(uri, map);
+ List<Vertex> results = uriQuery.getQueryBuilder().toList();
+ if (results.size() == 1) {
+ if (results.get(0).<Boolean>property(AAIProperties.LINKED).orElse(false)
+ && obj.getValue(entry.getKey()) == null) {
+ // delete vertex because property was removed
+ serializer.delete(results.get(0), "", false);
+ } else {
+ // link vertex that already exists
+ this.addLinkedProperty(results.get(0));
+ }
+ } else {
+ if (results.isEmpty()) {
+ // locate previously linked vertex
+ List<Vertex> linkedVertices = uriQuery.getQueryBuilder().getContainerQuery()
+ .getVerticesByProperty(AAIProperties.LINKED, true).toList();
+ if (!linkedVertices.isEmpty()) {
+ if (linkedVertices.size() > 1) {
+ throw new AAIMultiplePropertiesException(
+ "multiple vertices found for single cardinality propery found when searching "
+ + uri);
+ } else {
+ // found one, remove the linked property because it didn't match the uri
+ linkedVertices.get(0).property(AAIProperties.LINKED).remove();
+ }
+ }
+ if (obj.getValue(entry.getKey()) != null) {
+ // add new vertex to database if we have values
+ URIToObject parser = new URIToObject(this.latestLoader, uri);
+ Introspector resultObj = parser.getEntity();
+ Vertex newV = serializer.createNewVertex(resultObj);
+ serializer.serializeToDb(resultObj, newV, uriQuery, completeUri.get(),
+ this.latestLoader.getVersion().toString());
+ this.addLinkedProperty(newV);
+ }
+ } else if (results.size() > 1) {
+ throw new AAIMultiplePropertiesException(
+ "multiple values of " + entry.getKey() + " found when searching " + uri);
+ }
+ }
+ } else {
+ // skip processing because no required properties were specified
+ }
+ }
- @Override
- protected void processURI(Optional<String> completeUri, Entry<String, String> entry)
- throws URISyntaxException, UnsupportedEncodingException, AAIException {
- if (completeUri.isPresent()) {
- URI uri = new URI(completeUri.get());
- MultivaluedMap<String, String> map = URITools.getQueryMap(uri);
- QueryParser uriQuery = dbEngine.getQueryBuilder(this.latestLoader).createQueryFromURI(uri, map);
- List<Vertex> results = uriQuery.getQueryBuilder().toList();
- if (results.size() == 1) {
- if (results.get(0).<Boolean>property(AAIProperties.LINKED).orElse(false) && obj.getValue(entry.getKey()) == null) {
- //delete vertex because property was removed
- serializer.delete(results.get(0), "", false);
- } else {
- //link vertex that already exists
- this.addLinkedProperty(results.get(0));
- }
- } else {
- if (results.isEmpty()) {
- //locate previously linked vertex
- List<Vertex> linkedVertices = uriQuery.getQueryBuilder().getContainerQuery().getVerticesByProperty(AAIProperties.LINKED, true).toList();
- if (!linkedVertices.isEmpty()) {
- if (linkedVertices.size() > 1) {
- throw new AAIMultiplePropertiesException("multiple vertices found for single cardinality propery found when searching " + uri);
- } else {
- //found one, remove the linked property because it didn't match the uri
- linkedVertices.get(0).property(AAIProperties.LINKED).remove();
- }
- }
- if (obj.getValue(entry.getKey()) != null) {
- //add new vertex to database if we have values
- URIToObject parser = new URIToObject(this.latestLoader, uri);
- Introspector resultObj = parser.getEntity();
- Vertex newV = serializer.createNewVertex(resultObj);
- serializer.serializeToDb(resultObj, newV, uriQuery, completeUri.get(), this.latestLoader.getVersion().toString());
- this.addLinkedProperty(newV);
- }
- } else if (results.size() > 1) {
- throw new AAIMultiplePropertiesException("multiple values of " + entry.getKey() + " found when searching " + uri);
- }
- }
- } else {
- //skip processing because no required properties were specified
- }
- }
-
- @Override
- protected boolean replaceWithWildcard() {
- return true;
- }
-
- private void addLinkedProperty(Vertex v) {
- v.property(AAIProperties.LINKED, true);
- }
+ @Override
+ protected boolean replaceWithWildcard() {
+ return true;
+ }
+ private void addLinkedProperty(Vertex v) {
+ v.property(AAIProperties.LINKED, true);
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/introspection/sideeffect/PrivateEdge.java b/aai-core/src/main/java/org/onap/aai/introspection/sideeffect/PrivateEdge.java
index 5b719e33..f4f0bfac 100644
--- a/aai-core/src/main/java/org/onap/aai/introspection/sideeffect/PrivateEdge.java
+++ b/aai-core/src/main/java/org/onap/aai/introspection/sideeffect/PrivateEdge.java
@@ -17,16 +17,28 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.introspection.sideeffect;
import com.google.common.collect.Multimap;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.*;
+import java.util.Map.Entry;
+
+import javax.ws.rs.core.MultivaluedMap;
+
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.VertexProperty;
import org.onap.aai.config.SpringContextAware;
import org.onap.aai.db.props.AAIProperties;
import org.onap.aai.edges.EdgeIngestor;
+import org.onap.aai.edges.EdgeRule;
import org.onap.aai.edges.EdgeRuleQuery;
+import org.onap.aai.edges.enums.EdgeType;
import org.onap.aai.edges.exceptions.AmbiguousRuleChoiceException;
import org.onap.aai.edges.exceptions.EdgeRuleNotFoundException;
import org.onap.aai.exceptions.AAIException;
@@ -36,20 +48,10 @@ import org.onap.aai.parsers.query.QueryParser;
import org.onap.aai.restcore.util.URITools;
import org.onap.aai.schema.enums.PropertyMetadata;
import org.onap.aai.serialization.db.DBSerializer;
-import org.onap.aai.edges.EdgeRule;
-import org.onap.aai.edges.enums.EdgeType;
import org.onap.aai.serialization.db.EdgeSerializer;
import org.onap.aai.serialization.db.exceptions.EdgeMultiplicityException;
import org.onap.aai.serialization.engines.TransactionalGraphEngine;
-import javax.ws.rs.core.MultivaluedMap;
-import java.io.UnsupportedEncodingException;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.util.*;
-import java.util.Map.Entry;
-
-
public class PrivateEdge extends SideEffect {
public PrivateEdge(Introspector obj, Vertex self, TransactionalGraphEngine dbEngine, DBSerializer serializer) {
@@ -57,16 +59,18 @@ public class PrivateEdge extends SideEffect {
}
@Override
- protected void processURI(Optional<String> completeUri, Entry<String, String> entry) throws URISyntaxException, UnsupportedEncodingException, AAIException, EdgeRuleNotFoundException, AmbiguousRuleChoiceException {
+ protected void processURI(Optional<String> completeUri, Entry<String, String> entry) throws URISyntaxException,
+ UnsupportedEncodingException, AAIException, EdgeRuleNotFoundException, AmbiguousRuleChoiceException {
if (completeUri.isPresent()) {
process(completeUri, entry);
} else {
// Check if the vertex self has the template keys or the db aliased keys
// If it does check if the self vertex has a edge to that model
// If it does, then remove the edge since the update happened and doesn't have required props anymore
- // "service-design-and-creation/models/model/{model-invariant-id}/model-vers/model-ver/{model-version-id}"
+ // "service-design-and-creation/models/model/{model-invariant-id}/model-vers/model-ver/{model-version-id}"
// If the vertex does have
- Loader loader = SpringContextAware.getBean(LoaderFactory.class).createLoaderForVersion(ModelType.MOXY, obj.getVersion());
+ Loader loader = SpringContextAware.getBean(LoaderFactory.class).createLoaderForVersion(ModelType.MOXY,
+ obj.getVersion());
Introspector introspector = loader.introspectorFromName(obj.getDbName());
List<Vertex> vertices = new ArrayList<>();
vertices.add(self);
@@ -76,8 +80,9 @@ public class PrivateEdge extends SideEffect {
}
}
- private void process(Optional<String> completeUri, Entry<String, String> entry) throws URISyntaxException, UnsupportedEncodingException, AAIException, EdgeRuleNotFoundException, AmbiguousRuleChoiceException {
- if(completeUri.isPresent()){
+ private void process(Optional<String> completeUri, Entry<String, String> entry) throws URISyntaxException,
+ UnsupportedEncodingException, AAIException, EdgeRuleNotFoundException, AmbiguousRuleChoiceException {
+ if (completeUri.isPresent()) {
URI uri = new URI(completeUri.get());
MultivaluedMap<String, String> map = URITools.getQueryMap(uri);
QueryParser uriQuery = dbEngine.getQueryBuilder(this.latestLoader).createQueryFromURI(uri, map);
@@ -88,34 +93,39 @@ public class PrivateEdge extends SideEffect {
if (otherVProperty.isPresent()) {
- EdgeRuleQuery edgeQuery = new EdgeRuleQuery.Builder(obj.getName(), otherVProperty.value().toString()).edgeType(EdgeType.COUSIN).setPrivate(true).build();
+ EdgeRuleQuery edgeQuery =
+ new EdgeRuleQuery.Builder(obj.getName(), otherVProperty.value().toString())
+ .edgeType(EdgeType.COUSIN).setPrivate(true).build();
EdgeIngestor edgeIngestor = serializer.getEdgeIngestor();
EdgeSerializer edgeSerializer = serializer.getEdgeSeriailizer();
Multimap<String, EdgeRule> edgeRulesMap = edgeIngestor.getRules(edgeQuery);
if (edgeRulesMap.isEmpty()) {
- String message = String.format("Unable to find edge between %s and %s", obj.getName(), otherVProperty.value().toString());
+ String message = String.format("Unable to find edge between %s and %s", obj.getName(),
+ otherVProperty.value().toString());
throw new AAIException("AAI_6127", message);
} else if (edgeRulesMap.size() > 1) {
- String message = String.format("Found multiple edges between %s and %s", obj.getName(), otherVProperty.value().toString());
+ String message = String.format("Found multiple edges between %s and %s", obj.getName(),
+ otherVProperty.value().toString());
throw new EdgeMultiplicityException(message);
}
-
for (Entry<String, EdgeRule> edgeEntry : edgeRulesMap.entries()) {
EdgeRule edgeRule = edgeIngestor.getRule(edgeQuery);
Iterator<Edge> edges = self.edges(edgeRule.getDirection(), edgeRule.getLabel().toString());
- if(edges.hasNext()){
+ if (edges.hasNext()) {
Edge edge = edges.next();
EdgeStatus status = checkStatus(obj, self);
- switch(status){
+ switch (status) {
case CREATED:
- edgeSerializer.addPrivateEdge(this.dbEngine.asAdmin().getTraversalSource(), self, otherVertex, edgeRule.getLabel());
+ edgeSerializer.addPrivateEdge(this.dbEngine.asAdmin().getTraversalSource(), self,
+ otherVertex, edgeRule.getLabel());
break;
case MODIFIED:
edge.remove();
- edgeSerializer.addPrivateEdge(this.dbEngine.asAdmin().getTraversalSource(), self, otherVertex, edgeRule.getLabel());
+ edgeSerializer.addPrivateEdge(this.dbEngine.asAdmin().getTraversalSource(), self,
+ otherVertex, edgeRule.getLabel());
break;
case REMOVED:
edge.remove();
@@ -124,7 +134,8 @@ public class PrivateEdge extends SideEffect {
break;
}
} else {
- edgeSerializer.addPrivateEdge(this.dbEngine.asAdmin().getTraversalSource(), self, otherVertex, edgeRule.getLabel());
+ edgeSerializer.addPrivateEdge(this.dbEngine.asAdmin().getTraversalSource(), self,
+ otherVertex, edgeRule.getLabel());
}
}
}
@@ -132,49 +143,47 @@ public class PrivateEdge extends SideEffect {
if (results.isEmpty()) {
throw new AAIException("AAI_6114", "object located at " + uri + " not found");
} else if (results.size() > 1) {
- throw new AAIMultiplePropertiesException("multiple values of " + entry.getKey() + " found when searching " + uri);
+ throw new AAIMultiplePropertiesException(
+ "multiple values of " + entry.getKey() + " found when searching " + uri);
}
}
}
}
public enum EdgeStatus {
- CREATED,
- REMOVED,
- MODIFIED,
- UNCHANGED
+ CREATED, REMOVED, MODIFIED, UNCHANGED
}
private EdgeStatus checkStatus(Introspector obj, Vertex self) {
- for(String key : templateKeys){
+ for (String key : templateKeys) {
String currentObjValue = obj.getValue(key);
Map<PropertyMetadata, String> map = obj.getPropertyMetadata(key);
String oldVertexValue = null;
- if(map.containsKey(PropertyMetadata.DB_ALIAS)){
+ if (map.containsKey(PropertyMetadata.DB_ALIAS)) {
oldVertexValue = self.<String>property(key + AAIProperties.DB_ALIAS_SUFFIX).orElse(null);
} else {
oldVertexValue = self.<String>property(key).orElse(null);
}
- if(currentObjValue == null && oldVertexValue == null){
+ if (currentObjValue == null && oldVertexValue == null) {
continue;
}
- if(currentObjValue == null){
- if(oldVertexValue != null){
+ if (currentObjValue == null) {
+ if (oldVertexValue != null) {
return EdgeStatus.REMOVED;
}
}
- if(oldVertexValue == null){
- if(currentObjValue != null){
+ if (oldVertexValue == null) {
+ if (currentObjValue != null) {
return EdgeStatus.CREATED;
}
}
- if(!oldVertexValue.equals(currentObjValue)){
+ if (!oldVertexValue.equals(currentObjValue)) {
return EdgeStatus.MODIFIED;
}
}
diff --git a/aai-core/src/main/java/org/onap/aai/introspection/sideeffect/SideEffect.java b/aai-core/src/main/java/org/onap/aai/introspection/sideeffect/SideEffect.java
index 891876af..d86c18a0 100644
--- a/aai-core/src/main/java/org/onap/aai/introspection/sideeffect/SideEffect.java
+++ b/aai-core/src/main/java/org/onap/aai/introspection/sideeffect/SideEffect.java
@@ -17,10 +17,19 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.introspection.sideeffect;
import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URISyntaxException;
+import java.util.*;
+import java.util.Map.Entry;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.onap.aai.config.SpringContextAware;
import org.onap.aai.db.props.AAIProperties;
@@ -34,109 +43,108 @@ import org.onap.aai.serialization.db.DBSerializer;
import org.onap.aai.serialization.engines.TransactionalGraphEngine;
import org.onap.aai.setup.SchemaVersions;
-
-import java.io.UnsupportedEncodingException;
-import java.net.URISyntaxException;
-import java.util.*;
-import java.util.Map.Entry;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
public abstract class SideEffect {
- protected static final Pattern template = Pattern.compile("\\{(.*?)\\}");
- private static final EELFLogger logger = EELFManager.getInstance().getLogger(SideEffect.class);
-
- protected final Introspector obj;
- protected final TransactionalGraphEngine dbEngine;
- protected final DBSerializer serializer;
- protected final Loader latestLoader;
- protected final Vertex self;
-
- protected Set<String> templateKeys = new HashSet<>();
-
- public SideEffect (Introspector obj, Vertex self, TransactionalGraphEngine dbEngine, DBSerializer serializer) {
- this.obj = obj;
- this.dbEngine = dbEngine;
- this.serializer = serializer;
- this.self = self;
- this.latestLoader = LoaderUtil.getLatestVersion();
- }
-
- protected void execute() throws UnsupportedEncodingException, URISyntaxException, AAIException {
- final Map<String, String> properties = this.findPopertiesWithMetadata(obj, this.getPropertyMetadata());
- for (Entry<String, String> entry : properties.entrySet()) {
- Optional<String> populatedUri = this.replaceTemplates(obj, entry.getValue());
- Optional<String> completeUri = this.resolveRelativePath(populatedUri);
- try {
- this.processURI(completeUri, entry);
- } catch (EdgeRuleNotFoundException | AmbiguousRuleChoiceException e) {
- logger.warn("Unable to execute the side effect {} due to ", e, this.getClass().getName());
- }
- }
- }
-
- protected Map<String, String> findPopertiesWithMetadata(Introspector obj, PropertyMetadata metadata) {
- final Map<String, String> result = new HashMap<>();
- for (String prop : obj.getProperties()) {
- final Map<PropertyMetadata, String> map = obj.getPropertyMetadata(prop);
- if (map.containsKey(metadata)) {
- result.put(prop, map.get(metadata));
- }
- }
- return result;
- }
-
- protected Map<String, String> findProperties(Introspector obj, String uriString) throws AAIMissingRequiredPropertyException {
-
- final Map<String, String> result = new HashMap<>();
- final Set<String> missing = new LinkedHashSet<>();
- Matcher m = template.matcher(uriString);
- int properties = 0;
- while (m.find()) {
- String propName = m.group(1);
- String value = obj.getValue(propName);
- properties++;
- if (value != null) {
- result.put(propName, value);
- } else {
- if (replaceWithWildcard()) {
- result.put(propName, "*");
- }
- missing.add(propName);
- }
- }
-
- if (!missing.isEmpty() && (properties != missing.size())) {
- throw new AAIMissingRequiredPropertyException("Cannot complete " + this.getPropertyMetadata().toString() + " uri. Missing properties " + missing);
- }
- return result;
- }
-
- protected Optional<String> replaceTemplates(Introspector obj, String uriString) throws AAIMissingRequiredPropertyException {
- String result = uriString;
- final Map<String, String> propMap = this.findProperties(obj, uriString);
- if (propMap.isEmpty()) {
- return Optional.empty();
- }
- for (Entry<String, String> entry : propMap.entrySet()) {
- templateKeys.add(entry.getKey());
- result = result.replaceAll("\\{" + entry.getKey() + "\\}", entry.getValue());
- }
- //drop out wildcards if they exist
- result = result.replaceFirst("/[^/]+?(?:/\\*)+", "");
- return Optional.of(result);
- }
-
- private Optional<String> resolveRelativePath(Optional<String> populatedUri) throws UnsupportedEncodingException {
- if (!populatedUri.isPresent()) {
- return Optional.empty();
- } else {
- return Optional.of(populatedUri.get().replaceFirst("\\./", this.serializer.getURIForVertex(self) + "/"));
- }
- }
-
- protected abstract boolean replaceWithWildcard();
- protected abstract PropertyMetadata getPropertyMetadata();
- protected abstract void processURI(Optional<String> completeUri, Entry<String, String> entry) throws URISyntaxException, UnsupportedEncodingException, AAIException, EdgeRuleNotFoundException, AmbiguousRuleChoiceException;
+ protected static final Pattern template = Pattern.compile("\\{(.*?)\\}");
+ private static final EELFLogger logger = EELFManager.getInstance().getLogger(SideEffect.class);
+
+ protected final Introspector obj;
+ protected final TransactionalGraphEngine dbEngine;
+ protected final DBSerializer serializer;
+ protected final Loader latestLoader;
+ protected final Vertex self;
+
+ protected Set<String> templateKeys = new HashSet<>();
+
+ public SideEffect(Introspector obj, Vertex self, TransactionalGraphEngine dbEngine, DBSerializer serializer) {
+ this.obj = obj;
+ this.dbEngine = dbEngine;
+ this.serializer = serializer;
+ this.self = self;
+ this.latestLoader = LoaderUtil.getLatestVersion();
+ }
+
+ protected void execute() throws UnsupportedEncodingException, URISyntaxException, AAIException {
+ final Map<String, String> properties = this.findPopertiesWithMetadata(obj, this.getPropertyMetadata());
+ for (Entry<String, String> entry : properties.entrySet()) {
+ Optional<String> populatedUri = this.replaceTemplates(obj, entry.getValue());
+ Optional<String> completeUri = this.resolveRelativePath(populatedUri);
+ try {
+ this.processURI(completeUri, entry);
+ } catch (EdgeRuleNotFoundException | AmbiguousRuleChoiceException e) {
+ logger.warn("Unable to execute the side effect {} due to ", e, this.getClass().getName());
+ }
+ }
+ }
+
+ protected Map<String, String> findPopertiesWithMetadata(Introspector obj, PropertyMetadata metadata) {
+ final Map<String, String> result = new HashMap<>();
+ for (String prop : obj.getProperties()) {
+ final Map<PropertyMetadata, String> map = obj.getPropertyMetadata(prop);
+ if (map.containsKey(metadata)) {
+ result.put(prop, map.get(metadata));
+ }
+ }
+ return result;
+ }
+
+ protected Map<String, String> findProperties(Introspector obj, String uriString)
+ throws AAIMissingRequiredPropertyException {
+
+ final Map<String, String> result = new HashMap<>();
+ final Set<String> missing = new LinkedHashSet<>();
+ Matcher m = template.matcher(uriString);
+ int properties = 0;
+ while (m.find()) {
+ String propName = m.group(1);
+ String value = obj.getValue(propName);
+ properties++;
+ if (value != null) {
+ result.put(propName, value);
+ } else {
+ if (replaceWithWildcard()) {
+ result.put(propName, "*");
+ }
+ missing.add(propName);
+ }
+ }
+
+ if (!missing.isEmpty() && (properties != missing.size())) {
+ throw new AAIMissingRequiredPropertyException(
+ "Cannot complete " + this.getPropertyMetadata().toString() + " uri. Missing properties " + missing);
+ }
+ return result;
+ }
+
+ protected Optional<String> replaceTemplates(Introspector obj, String uriString)
+ throws AAIMissingRequiredPropertyException {
+ String result = uriString;
+ final Map<String, String> propMap = this.findProperties(obj, uriString);
+ if (propMap.isEmpty()) {
+ return Optional.empty();
+ }
+ for (Entry<String, String> entry : propMap.entrySet()) {
+ templateKeys.add(entry.getKey());
+ result = result.replaceAll("\\{" + entry.getKey() + "\\}", entry.getValue());
+ }
+ // drop out wildcards if they exist
+ result = result.replaceFirst("/[^/]+?(?:/\\*)+", "");
+ return Optional.of(result);
+ }
+
+ private Optional<String> resolveRelativePath(Optional<String> populatedUri) throws UnsupportedEncodingException {
+ if (!populatedUri.isPresent()) {
+ return Optional.empty();
+ } else {
+ return Optional.of(populatedUri.get().replaceFirst("\\./", this.serializer.getURIForVertex(self) + "/"));
+ }
+ }
+
+ protected abstract boolean replaceWithWildcard();
+
+ protected abstract PropertyMetadata getPropertyMetadata();
+
+ protected abstract void processURI(Optional<String> completeUri, Entry<String, String> entry)
+ throws URISyntaxException, UnsupportedEncodingException, AAIException, EdgeRuleNotFoundException,
+ AmbiguousRuleChoiceException;
}
diff --git a/aai-core/src/main/java/org/onap/aai/introspection/sideeffect/SideEffectRunner.java b/aai-core/src/main/java/org/onap/aai/introspection/sideeffect/SideEffectRunner.java
index 0d70c382..ffd9a8c8 100644
--- a/aai-core/src/main/java/org/onap/aai/introspection/sideeffect/SideEffectRunner.java
+++ b/aai-core/src/main/java/org/onap/aai/introspection/sideeffect/SideEffectRunner.java
@@ -17,15 +17,11 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.introspection.sideeffect;
import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
-import org.apache.tinkerpop.gremlin.structure.Vertex;
-import org.onap.aai.exceptions.AAIException;
-import org.onap.aai.introspection.Introspector;
-import org.onap.aai.serialization.db.DBSerializer;
-import org.onap.aai.serialization.engines.TransactionalGraphEngine;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
@@ -33,68 +29,76 @@ import java.net.URISyntaxException;
import java.util.LinkedHashSet;
import java.util.Set;
+import org.apache.tinkerpop.gremlin.structure.Vertex;
+import org.onap.aai.exceptions.AAIException;
+import org.onap.aai.introspection.Introspector;
+import org.onap.aai.serialization.db.DBSerializer;
+import org.onap.aai.serialization.engines.TransactionalGraphEngine;
+
public class SideEffectRunner {
- protected final TransactionalGraphEngine dbEngine;
- protected final DBSerializer serializer;
- protected final Set<Class<? extends SideEffect>> sideEffects;
- protected SideEffectRunner(Builder builder) {
- this.dbEngine = builder.getDbEngine();
- this.serializer = builder.getSerializer();
- this.sideEffects = builder.getSideEffects();
- }
-
- public void execute(Introspector obj, Vertex self) throws AAIException {
-
- for (Class<? extends SideEffect> se : sideEffects) {
- try {
- se.getConstructor(Introspector.class, Vertex.class, TransactionalGraphEngine.class, DBSerializer.class)
- .newInstance(obj, self, dbEngine, serializer).execute();
- } catch (UnsupportedEncodingException | InstantiationException | IllegalAccessException
- | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException
- | URISyntaxException e) {
- throw new AAIException("strange exception", e);
- }
- }
- }
-
- public static class Builder {
-
- private final TransactionalGraphEngine dbEngine;
- private final DBSerializer serializer;
- private final Set<Class<? extends SideEffect>> sideEffects;
-
- public Builder(final TransactionalGraphEngine dbEngine, final DBSerializer serializer) {
- this.dbEngine = dbEngine;
- this.serializer = serializer;
- this.sideEffects = new LinkedHashSet<>();
- }
-
- public Builder addSideEffect(Class<? extends SideEffect> se) {
- sideEffects.add(se);
- return this;
- }
-
- public Builder addSideEffects(Class<? extends SideEffect>... sideEffects) {
- for (Class<? extends SideEffect> se : sideEffects) {
- this.addSideEffect(se);
- }
- return this;
- }
-
- public SideEffectRunner build() {
- return new SideEffectRunner(this);
- }
- protected TransactionalGraphEngine getDbEngine() {
- return dbEngine;
- }
-
- protected DBSerializer getSerializer() {
- return serializer;
- }
-
- protected Set<Class<? extends SideEffect>> getSideEffects() {
- return sideEffects;
- }
- }
+ protected final TransactionalGraphEngine dbEngine;
+ protected final DBSerializer serializer;
+ protected final Set<Class<? extends SideEffect>> sideEffects;
+
+ protected SideEffectRunner(Builder builder) {
+ this.dbEngine = builder.getDbEngine();
+ this.serializer = builder.getSerializer();
+ this.sideEffects = builder.getSideEffects();
+ }
+
+ public void execute(Introspector obj, Vertex self) throws AAIException {
+
+ for (Class<? extends SideEffect> se : sideEffects) {
+ try {
+ se.getConstructor(Introspector.class, Vertex.class, TransactionalGraphEngine.class, DBSerializer.class)
+ .newInstance(obj, self, dbEngine, serializer).execute();
+ } catch (UnsupportedEncodingException | InstantiationException | IllegalAccessException
+ | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException
+ | URISyntaxException e) {
+ throw new AAIException("strange exception", e);
+ }
+ }
+ }
+
+ public static class Builder {
+
+ private final TransactionalGraphEngine dbEngine;
+ private final DBSerializer serializer;
+ private final Set<Class<? extends SideEffect>> sideEffects;
+
+ public Builder(final TransactionalGraphEngine dbEngine, final DBSerializer serializer) {
+ this.dbEngine = dbEngine;
+ this.serializer = serializer;
+ this.sideEffects = new LinkedHashSet<>();
+ }
+
+ public Builder addSideEffect(Class<? extends SideEffect> se) {
+ sideEffects.add(se);
+ return this;
+ }
+
+ public Builder addSideEffects(Class<? extends SideEffect>... sideEffects) {
+ for (Class<? extends SideEffect> se : sideEffects) {
+ this.addSideEffect(se);
+ }
+ return this;
+ }
+
+ public SideEffectRunner build() {
+ return new SideEffectRunner(this);
+ }
+
+ protected TransactionalGraphEngine getDbEngine() {
+ return dbEngine;
+ }
+
+ protected DBSerializer getSerializer() {
+ return serializer;
+ }
+
+ protected Set<Class<? extends SideEffect>> getSideEffects() {
+ return sideEffects;
+ }
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/introspection/sideeffect/SideEffectRunnerHelper.java b/aai-core/src/main/java/org/onap/aai/introspection/sideeffect/SideEffectRunnerHelper.java
index 4daefe4c..160a91ea 100644
--- a/aai-core/src/main/java/org/onap/aai/introspection/sideeffect/SideEffectRunnerHelper.java
+++ b/aai-core/src/main/java/org/onap/aai/introspection/sideeffect/SideEffectRunnerHelper.java
@@ -17,13 +17,8 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-package org.onap.aai.introspection.sideeffect;
-import org.onap.aai.exceptions.AAIException;
-import org.onap.aai.introspection.Introspector;
-import org.onap.aai.introspection.Wanderer;
-import org.onap.aai.serialization.db.DBSerializer;
-import org.onap.aai.serialization.engines.TransactionalGraphEngine;
+package org.onap.aai.introspection.sideeffect;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
@@ -31,54 +26,62 @@ import java.net.URISyntaxException;
import java.util.List;
import java.util.Set;
+import org.onap.aai.exceptions.AAIException;
+import org.onap.aai.introspection.Introspector;
+import org.onap.aai.introspection.Wanderer;
+import org.onap.aai.serialization.db.DBSerializer;
+import org.onap.aai.serialization.engines.TransactionalGraphEngine;
+
class SideEffectRunnerHelper implements Wanderer {
-
- protected final TransactionalGraphEngine dbEngine;
- protected final DBSerializer serializer;
- protected final Set<Class<? extends SideEffect>> sideEffects;
- protected SideEffectRunnerHelper(final TransactionalGraphEngine dbEngine, final DBSerializer serializer, final Set<Class<? extends SideEffect>> sideEffects) {
- this.dbEngine = dbEngine;
- this.serializer = serializer;
- this.sideEffects = sideEffects;
- }
-
- private void runSideEffects(Introspector obj) throws AAIException {
- for (Class<? extends SideEffect> se : sideEffects) {
- try {
- se.getConstructor(Introspector.class, TransactionalGraphEngine.class, DBSerializer.class)
- .newInstance(obj, dbEngine, serializer).execute();
- } catch (UnsupportedEncodingException | InstantiationException | IllegalAccessException
- | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException
- | URISyntaxException e) {
- throw new AAIException("strange exception", e);
- }
- }
- }
- @Override
- public void processPrimitive(String propName, Introspector obj) {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void processPrimitiveList(String propName, Introspector obj) {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void processComplexObj(Introspector obj) throws AAIException {
-
- runSideEffects(obj);
-
- }
-
- @Override
- public void modifyComplexList(List<Introspector> list, List<Object> listReference, Introspector parent,
- Introspector child) {
- // TODO Auto-generated method stub
-
- }
+ protected final TransactionalGraphEngine dbEngine;
+ protected final DBSerializer serializer;
+ protected final Set<Class<? extends SideEffect>> sideEffects;
+
+ protected SideEffectRunnerHelper(final TransactionalGraphEngine dbEngine, final DBSerializer serializer,
+ final Set<Class<? extends SideEffect>> sideEffects) {
+ this.dbEngine = dbEngine;
+ this.serializer = serializer;
+ this.sideEffects = sideEffects;
+ }
+
+ private void runSideEffects(Introspector obj) throws AAIException {
+ for (Class<? extends SideEffect> se : sideEffects) {
+ try {
+ se.getConstructor(Introspector.class, TransactionalGraphEngine.class, DBSerializer.class)
+ .newInstance(obj, dbEngine, serializer).execute();
+ } catch (UnsupportedEncodingException | InstantiationException | IllegalAccessException
+ | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException
+ | URISyntaxException e) {
+ throw new AAIException("strange exception", e);
+ }
+ }
+ }
+
+ @Override
+ public void processPrimitive(String propName, Introspector obj) {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void processPrimitiveList(String propName, Introspector obj) {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void processComplexObj(Introspector obj) throws AAIException {
+
+ runSideEffects(obj);
+
+ }
+
+ @Override
+ public void modifyComplexList(List<Introspector> list, List<Object> listReference, Introspector parent,
+ Introspector child) {
+ // TODO Auto-generated method stub
+
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/introspection/sideeffect/exceptions/AAIMissingRequiredPropertyException.java b/aai-core/src/main/java/org/onap/aai/introspection/sideeffect/exceptions/AAIMissingRequiredPropertyException.java
index ac9abbe6..06f82404 100644
--- a/aai-core/src/main/java/org/onap/aai/introspection/sideeffect/exceptions/AAIMissingRequiredPropertyException.java
+++ b/aai-core/src/main/java/org/onap/aai/introspection/sideeffect/exceptions/AAIMissingRequiredPropertyException.java
@@ -17,28 +17,28 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.introspection.sideeffect.exceptions;
import org.onap.aai.exceptions.AAIException;
public class AAIMissingRequiredPropertyException extends AAIException {
+ private static final long serialVersionUID = -8907079650472014019L;
- private static final long serialVersionUID = -8907079650472014019L;
+ public AAIMissingRequiredPropertyException() {
+ }
- public AAIMissingRequiredPropertyException() {}
+ public AAIMissingRequiredPropertyException(String message) {
+ super("AAI_5107", message);
+ }
- public AAIMissingRequiredPropertyException(String message) {
- super("AAI_5107", message);
- }
+ public AAIMissingRequiredPropertyException(Throwable cause) {
+ super("AAI_5107", cause);
+ }
- public AAIMissingRequiredPropertyException(Throwable cause) {
- super("AAI_5107",cause);
- }
+ public AAIMissingRequiredPropertyException(String message, Throwable cause) {
+ super("AAI_5107", cause, message);
+ }
- public AAIMissingRequiredPropertyException(String message, Throwable cause) {
- super("AAI_5107", cause, message);
- }
-
-
}
diff --git a/aai-core/src/main/java/org/onap/aai/introspection/sideeffect/exceptions/AAIMultiplePropertiesException.java b/aai-core/src/main/java/org/onap/aai/introspection/sideeffect/exceptions/AAIMultiplePropertiesException.java
index dc4be817..369ee8fc 100644
--- a/aai-core/src/main/java/org/onap/aai/introspection/sideeffect/exceptions/AAIMultiplePropertiesException.java
+++ b/aai-core/src/main/java/org/onap/aai/introspection/sideeffect/exceptions/AAIMultiplePropertiesException.java
@@ -17,27 +17,28 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.introspection.sideeffect.exceptions;
import org.onap.aai.exceptions.AAIException;
public class AAIMultiplePropertiesException extends AAIException {
- private static final long serialVersionUID = 2098371383166008345L;
+ private static final long serialVersionUID = 2098371383166008345L;
+
+ public AAIMultiplePropertiesException() {
+ }
- public AAIMultiplePropertiesException() {}
+ public AAIMultiplePropertiesException(String message) {
+ super("AAI_6136", message);
+ }
- public AAIMultiplePropertiesException(String message) {
- super("AAI_6136", message);
- }
+ public AAIMultiplePropertiesException(Throwable cause) {
+ super("AAI_6136", cause);
+ }
- public AAIMultiplePropertiesException(Throwable cause) {
- super("AAI_6136",cause);
- }
+ public AAIMultiplePropertiesException(String message, Throwable cause) {
+ super("AAI_6136", cause, message);
+ }
- public AAIMultiplePropertiesException(String message, Throwable cause) {
- super("AAI_6136", cause, message);
- }
-
-
}
diff --git a/aai-core/src/main/java/org/onap/aai/introspection/tools/CreateUUID.java b/aai-core/src/main/java/org/onap/aai/introspection/tools/CreateUUID.java
index 4652c8fa..725792a2 100644
--- a/aai-core/src/main/java/org/onap/aai/introspection/tools/CreateUUID.java
+++ b/aai-core/src/main/java/org/onap/aai/introspection/tools/CreateUUID.java
@@ -17,14 +17,15 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-package org.onap.aai.introspection.tools;
-import org.onap.aai.introspection.Introspector;
-import org.onap.aai.schema.enums.PropertyMetadata;
+package org.onap.aai.introspection.tools;
import java.util.Map;
import java.util.UUID;
+import org.onap.aai.introspection.Introspector;
+import org.onap.aai.schema.enums.PropertyMetadata;
+
/**
* <b>CreateUUID</b> is an issue resolver that is responsible
* for looking to check if the property that is missing has
@@ -46,30 +47,31 @@ import java.util.UUID;
*/
public class CreateUUID implements IssueResolver {
- /**
- * Resolves the issue by checking if the issue type is missing key prop
- * and if it is it will retrieve the introspector associated with the issue
- * then gets the metadata associated to that specific property
- * and if it contains the auto generate meta property and if it does
- * then it will fix it by setting that property value to generated uuid
- *
- * @param issue the issue with the details associated to the problem
- * @return true if the issue has been successfully resolved
- * false otherwise
- */
- @Override
- public boolean resolveIssue(Issue issue) {
+ /**
+ * Resolves the issue by checking if the issue type is missing key prop
+ * and if it is it will retrieve the introspector associated with the issue
+ * then gets the metadata associated to that specific property
+ * and if it contains the auto generate meta property and if it does
+ * then it will fix it by setting that property value to generated uuid
+ *
+ * @param issue the issue with the details associated to the problem
+ * @return true if the issue has been successfully resolved
+ * false otherwise
+ */
+ @Override
+ public boolean resolveIssue(Issue issue) {
+
+ Introspector obj = issue.getIntrospector();
+ if (issue.getType().equals(IssueType.MISSING_KEY_PROP)) {
+ Map<PropertyMetadata, String> metadata = obj.getPropertyMetadata(issue.getPropName());
+ if (metadata.containsKey(PropertyMetadata.AUTO_GENERATE_UUID)
+ && metadata.get(PropertyMetadata.AUTO_GENERATE_UUID).equals("true")) {
+ obj.setValue(issue.getPropName(), UUID.randomUUID().toString());
+ return true;
+ }
+ }
- Introspector obj = issue.getIntrospector();
- if (issue.getType().equals(IssueType.MISSING_KEY_PROP)) {
- Map<PropertyMetadata, String> metadata = obj.getPropertyMetadata(issue.getPropName());
- if (metadata.containsKey(PropertyMetadata.AUTO_GENERATE_UUID) && metadata.get(PropertyMetadata.AUTO_GENERATE_UUID).equals("true")) {
- obj.setValue(issue.getPropName(), UUID.randomUUID().toString());
- return true;
- }
- }
-
- return false;
- }
+ return false;
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/introspection/tools/DefaultFields.java b/aai-core/src/main/java/org/onap/aai/introspection/tools/DefaultFields.java
index cb7b5037..f05069ea 100644
--- a/aai-core/src/main/java/org/onap/aai/introspection/tools/DefaultFields.java
+++ b/aai-core/src/main/java/org/onap/aai/introspection/tools/DefaultFields.java
@@ -17,31 +17,32 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.introspection.tools;
+import java.util.Map;
+
import org.onap.aai.introspection.Introspector;
import org.onap.aai.schema.enums.PropertyMetadata;
-import java.util.Map;
-
public class DefaultFields implements IssueResolver {
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean resolveIssue(Issue issue) {
-
- Introspector obj = issue.getIntrospector();
- if (issue.getType().equals(IssueType.MISSING_REQUIRED_PROP)) {
- Map<PropertyMetadata, String> metadata = obj.getPropertyMetadata(issue.getPropName());
- if (metadata.containsKey(PropertyMetadata.DEFAULT_VALUE)) {
- obj.setValue(issue.getPropName(), metadata.get(PropertyMetadata.DEFAULT_VALUE));
- return true;
- }
- }
-
- return false;
- }
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public boolean resolveIssue(Issue issue) {
+
+ Introspector obj = issue.getIntrospector();
+ if (issue.getType().equals(IssueType.MISSING_REQUIRED_PROP)) {
+ Map<PropertyMetadata, String> metadata = obj.getPropertyMetadata(issue.getPropName());
+ if (metadata.containsKey(PropertyMetadata.DEFAULT_VALUE)) {
+ obj.setValue(issue.getPropName(), metadata.get(PropertyMetadata.DEFAULT_VALUE));
+ return true;
+ }
+ }
+
+ return false;
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/introspection/tools/InjectKeysFromURI.java b/aai-core/src/main/java/org/onap/aai/introspection/tools/InjectKeysFromURI.java
index 7f6bb39f..748821a7 100644
--- a/aai-core/src/main/java/org/onap/aai/introspection/tools/InjectKeysFromURI.java
+++ b/aai-core/src/main/java/org/onap/aai/introspection/tools/InjectKeysFromURI.java
@@ -17,52 +17,53 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.introspection.tools;
+import java.net.URI;
+
import org.onap.aai.introspection.Introspector;
import org.onap.aai.introspection.Loader;
import org.onap.aai.parsers.uri.URIToObject;
-import java.net.URI;
+public class InjectKeysFromURI implements IssueResolver {
+
+ private URI uri = null;
+ private Loader loader = null;
+
+ /**
+ * Instantiates a new inject keys from URI.
+ *
+ * @param loader the loader
+ * @param uri the uri
+ */
+ public InjectKeysFromURI(Loader loader, URI uri) {
+ this.loader = loader;
+ this.uri = uri;
+ }
-public class InjectKeysFromURI implements IssueResolver {
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public boolean resolveIssue(Issue issue) {
+ boolean result = false;
+ Introspector obj = issue.getIntrospector();
+ if (issue.getType().equals(IssueType.MISSING_KEY_PROP)) {
+ try {
+ URIToObject toObject = new URIToObject(loader, uri);
+ Introspector minimumObj = toObject.getEntity();
+ if (toObject.getEntityName().equals(obj.getDbName())) {
+ obj.setValue(issue.getPropName(), minimumObj.getValue(issue.getPropName()));
+ result = true;
+ }
+ } catch (Exception e) {
+ // log something probably
+ result = false;
+ }
+ }
- private URI uri = null;
- private Loader loader = null;
-
- /**
- * Instantiates a new inject keys from URI.
- *
- * @param loader the loader
- * @param uri the uri
- */
- public InjectKeysFromURI(Loader loader, URI uri) {
- this.loader = loader;
- this.uri = uri;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean resolveIssue(Issue issue) {
- boolean result = false;
- Introspector obj = issue.getIntrospector();
- if (issue.getType().equals(IssueType.MISSING_KEY_PROP)) {
- try {
- URIToObject toObject = new URIToObject(loader, uri);
- Introspector minimumObj = toObject.getEntity();
- if (toObject.getEntityName().equals(obj.getDbName())) {
- obj.setValue(issue.getPropName(), minimumObj.getValue(issue.getPropName()));
- result = true;
- }
- } catch (Exception e) {
- //log something probably
- result = false;
- }
- }
-
- return result;
- }
+ return result;
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/introspection/tools/IntrospectorValidator.java b/aai-core/src/main/java/org/onap/aai/introspection/tools/IntrospectorValidator.java
index c6d31c27..8e1d8eeb 100644
--- a/aai-core/src/main/java/org/onap/aai/introspection/tools/IntrospectorValidator.java
+++ b/aai-core/src/main/java/org/onap/aai/introspection/tools/IntrospectorValidator.java
@@ -17,8 +17,11 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.introspection.tools;
+import java.util.*;
+
import org.onap.aai.db.props.AAIProperties;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.introspection.Introspector;
@@ -27,291 +30,291 @@ import org.onap.aai.introspection.Visibility;
import org.onap.aai.introspection.Wanderer;
import org.onap.aai.schema.enums.PropertyMetadata;
-import java.util.*;
-
public class IntrospectorValidator implements Wanderer {
-
- private List<Issue> issues = null;
- private List<IssueResolver> issueResolvers = null;
- private boolean validateRequired = true;
- private final int maximumDepth;
- private int currentDepth = 0;
-
- private final Set<String> relationshipChain;
- /**
- * Instantiates a new introspector validator.
- *
- * @param builder the builder
- */
- private IntrospectorValidator(Builder builder) {
- this.validateRequired = builder.getValidateRequired();
- this.issueResolvers = builder.getResolvers();
- this.maximumDepth = builder.getMaximumDepth();
- issues = new ArrayList<>();
-
- relationshipChain = new HashSet<>();
-
- relationshipChain.add("relationship-list");
- relationshipChain.add("relationship");
- relationshipChain.add("relationship-data");
- relationshipChain.add("related-to-property");
-
-
- }
-
- /**
- * Validate.
- *
- * @param obj the obj
- * @return true, if successful
- * @throws AAIException
- */
- public boolean validate(Introspector obj) throws AAIException {
- IntrospectorWalker walker = new IntrospectorWalker(this);
- this.currentDepth = 0;
- walker.walk(obj);
-
- for (Issue m : issues) {
- if (!m.getSeverity().equals(Severity.WARNING)) {
- return false;
- }
- }
-
- return true;
- }
-
- /**
- * Gets the issues.
- *
- * @return the issues
- */
- public List<Issue> getIssues() {
- return this.issues;
- }
-
- /**
- * Sets the issue resolvers.
- *
- * @param resolvers the new issue resolvers
- */
- public void setIssueResolvers(List<IssueResolver> resolvers) {
- issueResolvers = new ArrayList<>();
- for (IssueResolver resolver : resolvers) {
- issueResolvers.add(resolver);
- }
- }
-
- /**
- * Resolve issues.
- *
- * @return true, if successful
- */
- public boolean resolveIssues() {
- boolean result = true;
- for (Issue issue : issues) {
- for (IssueResolver resolver : issueResolvers) {
- if (resolver.resolveIssue(issue)) {
- issue.setResolved(true);
- }
- }
- if (!issue.isResolved()) {
- result = false;
- }
- }
-
- return result;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public void processComplexObj(Introspector obj) {
-
- if (this.currentDepth > this.maximumDepth && !relationshipChain.contains(obj.getDbName())) {
- Issue message =
- this.buildMessage(Severity.CRITICAL, IssueType.EXCEEDED_ALLOWED_DEPTH, "Maximum allowed depth of this object has been exceeded on: " + obj.getDbName());
- message.setIntrospector(obj);
- issues.add(message);
- }
- Set<String> requiredProps = obj.getRequiredProperties();
- Set<String> keys = obj.getKeys();
- Set<String> props = obj.getProperties();
-
- for (String prop : props) {
- Object value = obj.getValue(prop);
- if (keys.contains(prop)) {
- if (value == null) {
- Issue message =
- this.buildMessage(Severity.CRITICAL, IssueType.MISSING_KEY_PROP, "Missing key property: " + prop);
- message.setIntrospector(obj);
- message.setPropName(prop);
- issues.add(message);
- }
- } else if (requiredProps.contains(prop)) {
- if (value == null && validateRequired) {
- Issue message =
- this.buildMessage(Severity.CRITICAL, IssueType.MISSING_REQUIRED_PROP, "Missing required property: " + prop);
- message.setIntrospector(obj);
- message.setPropName(prop);
- issues.add(message);
- }
- }
-
- final Optional<String> visibility = obj.getPropertyMetadata(prop, PropertyMetadata.VISIBILITY);
- if(visibility.isPresent() && Visibility.internal.equals(Visibility.valueOf(visibility.get())) && obj.getValue(prop) != null) {
- Issue message =
- this.buildMessage(Severity.ERROR, IssueType.PROPERTY_NOT_VISIBLE, "client attemptted to set property not visible: " + prop);
- message.setIntrospector(obj);
- message.setPropName(prop);
- issues.add(message);
-
- }
- final Optional<String> requires = obj.getPropertyMetadata(prop, PropertyMetadata.REQUIRES);
- if (requires.isPresent() && (obj.getValue(prop) != null && obj.getValue(requires.get()) == null)) {
- Issue message =
- this.buildMessage(Severity.CRITICAL, IssueType.DEPENDENT_PROP_NOT_FOUND, prop + " requires " + requires.get() + " to also be popluated.");
- message.setIntrospector(obj);
- message.setPropName(prop);
- issues.add(message);
- }
- }
-
- if (!relationshipChain.contains(obj.getDbName())) {
- this.currentDepth++;
- }
-
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public void processPrimitive(String propName, Introspector obj) {
- //NO OP
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public void processPrimitiveList(String propName, Introspector obj) {
- //NO OP
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public void modifyComplexList(List<Introspector> list, List<Object> listReference, Introspector parent, Introspector child) {
- //NO OP
- }
-
-
- /**
- * Builds the message.
- *
- * @param severity the severity
- * @param error the error
- * @param detail the detail
- * @return the issue
- */
- private Issue buildMessage(Severity severity, IssueType error, String detail) {
- Issue message = new Issue();
- message.setSeverity(severity);
- message.setType(error);
- message.setDetail(detail);
-
- return message;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean createComplexObjIfNull() {
- return false;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public int createComplexListSize(Introspector parent, Introspector child) {
- return 0;
- }
-
- public static class Builder {
-
- private boolean validateRequired = true;
- private List<IssueResolver> issueResolvers = null;
- private int maximumDepth = AAIProperties.MAXIMUM_DEPTH;
- /**
- * Instantiates a new builder.
- *
- * @param llBuilder the ll builder
- */
- public Builder() {
- issueResolvers = new ArrayList<IssueResolver>();
- }
-
- /**
- * Validate required.
- *
- * @param validateRequired the validate required
- * @return the builder
- */
- public Builder validateRequired(boolean validateRequired) {
- this.validateRequired = validateRequired;
- return this;
- }
-
- public Builder restrictDepth(int depth) {
- this.maximumDepth = depth;
- return this;
- }
- /**
- * Adds the resolver.
- *
- * @param resolver the resolver
- * @return the builder
- */
- public Builder addResolver(IssueResolver resolver) {
- issueResolvers.add(resolver);
- return this;
- }
-
- /**
- * Builds the.
- *
- * @return the introspector validator
- */
- public IntrospectorValidator build() {
- return new IntrospectorValidator(this);
- }
-
- /**
- * Gets the validate required.
- *
- * @return the validate required
- */
- public boolean getValidateRequired() {
- return this.validateRequired;
- }
-
- /**
- * Gets the resolvers.
- *
- * @return the resolvers
- */
- public List<IssueResolver> getResolvers() {
- return this.issueResolvers;
- }
-
- public int getMaximumDepth() {
- return this.maximumDepth;
- }
- }
-
+ private List<Issue> issues = null;
+ private List<IssueResolver> issueResolvers = null;
+ private boolean validateRequired = true;
+ private final int maximumDepth;
+ private int currentDepth = 0;
+
+ private final Set<String> relationshipChain;
+
+ /**
+ * Instantiates a new introspector validator.
+ *
+ * @param builder the builder
+ */
+ private IntrospectorValidator(Builder builder) {
+ this.validateRequired = builder.getValidateRequired();
+ this.issueResolvers = builder.getResolvers();
+ this.maximumDepth = builder.getMaximumDepth();
+ issues = new ArrayList<>();
+
+ relationshipChain = new HashSet<>();
+
+ relationshipChain.add("relationship-list");
+ relationshipChain.add("relationship");
+ relationshipChain.add("relationship-data");
+ relationshipChain.add("related-to-property");
+
+ }
+
+ /**
+ * Validate.
+ *
+ * @param obj the obj
+ * @return true, if successful
+ * @throws AAIException
+ */
+ public boolean validate(Introspector obj) throws AAIException {
+ IntrospectorWalker walker = new IntrospectorWalker(this);
+ this.currentDepth = 0;
+ walker.walk(obj);
+
+ for (Issue m : issues) {
+ if (!m.getSeverity().equals(Severity.WARNING)) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ /**
+ * Gets the issues.
+ *
+ * @return the issues
+ */
+ public List<Issue> getIssues() {
+ return this.issues;
+ }
+
+ /**
+ * Sets the issue resolvers.
+ *
+ * @param resolvers the new issue resolvers
+ */
+ public void setIssueResolvers(List<IssueResolver> resolvers) {
+ issueResolvers = new ArrayList<>();
+ for (IssueResolver resolver : resolvers) {
+ issueResolvers.add(resolver);
+ }
+ }
+
+ /**
+ * Resolve issues.
+ *
+ * @return true, if successful
+ */
+ public boolean resolveIssues() {
+ boolean result = true;
+ for (Issue issue : issues) {
+ for (IssueResolver resolver : issueResolvers) {
+ if (resolver.resolveIssue(issue)) {
+ issue.setResolved(true);
+ }
+ }
+ if (!issue.isResolved()) {
+ result = false;
+ }
+ }
+
+ return result;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public void processComplexObj(Introspector obj) {
+
+ if (this.currentDepth > this.maximumDepth && !relationshipChain.contains(obj.getDbName())) {
+ Issue message = this.buildMessage(Severity.CRITICAL, IssueType.EXCEEDED_ALLOWED_DEPTH,
+ "Maximum allowed depth of this object has been exceeded on: " + obj.getDbName());
+ message.setIntrospector(obj);
+ issues.add(message);
+ }
+ Set<String> requiredProps = obj.getRequiredProperties();
+ Set<String> keys = obj.getKeys();
+ Set<String> props = obj.getProperties();
+
+ for (String prop : props) {
+ Object value = obj.getValue(prop);
+ if (keys.contains(prop)) {
+ if (value == null) {
+ Issue message = this.buildMessage(Severity.CRITICAL, IssueType.MISSING_KEY_PROP,
+ "Missing key property: " + prop);
+ message.setIntrospector(obj);
+ message.setPropName(prop);
+ issues.add(message);
+ }
+ } else if (requiredProps.contains(prop)) {
+ if (value == null && validateRequired) {
+ Issue message = this.buildMessage(Severity.CRITICAL, IssueType.MISSING_REQUIRED_PROP,
+ "Missing required property: " + prop);
+ message.setIntrospector(obj);
+ message.setPropName(prop);
+ issues.add(message);
+ }
+ }
+
+ final Optional<String> visibility = obj.getPropertyMetadata(prop, PropertyMetadata.VISIBILITY);
+ if (visibility.isPresent() && Visibility.internal.equals(Visibility.valueOf(visibility.get()))
+ && obj.getValue(prop) != null) {
+ Issue message = this.buildMessage(Severity.ERROR, IssueType.PROPERTY_NOT_VISIBLE,
+ "client attemptted to set property not visible: " + prop);
+ message.setIntrospector(obj);
+ message.setPropName(prop);
+ issues.add(message);
+
+ }
+ final Optional<String> requires = obj.getPropertyMetadata(prop, PropertyMetadata.REQUIRES);
+ if (requires.isPresent() && (obj.getValue(prop) != null && obj.getValue(requires.get()) == null)) {
+ Issue message = this.buildMessage(Severity.CRITICAL, IssueType.DEPENDENT_PROP_NOT_FOUND,
+ prop + " requires " + requires.get() + " to also be popluated.");
+ message.setIntrospector(obj);
+ message.setPropName(prop);
+ issues.add(message);
+ }
+ }
+
+ if (!relationshipChain.contains(obj.getDbName())) {
+ this.currentDepth++;
+ }
+
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public void processPrimitive(String propName, Introspector obj) {
+ // NO OP
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public void processPrimitiveList(String propName, Introspector obj) {
+ // NO OP
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public void modifyComplexList(List<Introspector> list, List<Object> listReference, Introspector parent,
+ Introspector child) {
+ // NO OP
+ }
+
+ /**
+ * Builds the message.
+ *
+ * @param severity the severity
+ * @param error the error
+ * @param detail the detail
+ * @return the issue
+ */
+ private Issue buildMessage(Severity severity, IssueType error, String detail) {
+ Issue message = new Issue();
+ message.setSeverity(severity);
+ message.setType(error);
+ message.setDetail(detail);
+
+ return message;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public boolean createComplexObjIfNull() {
+ return false;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public int createComplexListSize(Introspector parent, Introspector child) {
+ return 0;
+ }
+
+ public static class Builder {
+
+ private boolean validateRequired = true;
+ private List<IssueResolver> issueResolvers = null;
+ private int maximumDepth = AAIProperties.MAXIMUM_DEPTH;
+
+ /**
+ * Instantiates a new builder.
+ *
+ * @param llBuilder the ll builder
+ */
+ public Builder() {
+ issueResolvers = new ArrayList<IssueResolver>();
+ }
+
+ /**
+ * Validate required.
+ *
+ * @param validateRequired the validate required
+ * @return the builder
+ */
+ public Builder validateRequired(boolean validateRequired) {
+ this.validateRequired = validateRequired;
+ return this;
+ }
+
+ public Builder restrictDepth(int depth) {
+ this.maximumDepth = depth;
+ return this;
+ }
+
+ /**
+ * Adds the resolver.
+ *
+ * @param resolver the resolver
+ * @return the builder
+ */
+ public Builder addResolver(IssueResolver resolver) {
+ issueResolvers.add(resolver);
+ return this;
+ }
+
+ /**
+ * Builds the.
+ *
+ * @return the introspector validator
+ */
+ public IntrospectorValidator build() {
+ return new IntrospectorValidator(this);
+ }
+
+ /**
+ * Gets the validate required.
+ *
+ * @return the validate required
+ */
+ public boolean getValidateRequired() {
+ return this.validateRequired;
+ }
+
+ /**
+ * Gets the resolvers.
+ *
+ * @return the resolvers
+ */
+ public List<IssueResolver> getResolvers() {
+ return this.issueResolvers;
+ }
+
+ public int getMaximumDepth() {
+ return this.maximumDepth;
+ }
+ }
+
}
diff --git a/aai-core/src/main/java/org/onap/aai/introspection/tools/Issue.java b/aai-core/src/main/java/org/onap/aai/introspection/tools/Issue.java
index 73ab232e..c4e6850e 100644
--- a/aai-core/src/main/java/org/onap/aai/introspection/tools/Issue.java
+++ b/aai-core/src/main/java/org/onap/aai/introspection/tools/Issue.java
@@ -17,127 +17,127 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.introspection.tools;
import org.onap.aai.introspection.Introspector;
public class Issue {
- private Severity severity;
- private IssueType error;
- private String detail;
- private Introspector obj;
- private String propName;
- private boolean resolved = false;
-
- /**
- * Sets the severity.
- *
- * @param severity the new severity
- */
- public void setSeverity(Severity severity) {
-
- this.severity = severity;
- }
-
- /**
- * Sets the error.
- *
- * @param error the new error
- */
- public void setType(IssueType error) {
- this.error = error;
- }
-
- /**
- * Sets the detail.
- *
- * @param detail the new detail
- */
- public void setDetail(String detail) {
- this.detail = detail;
- }
-
- /**
- * Gets the severity.
- *
- * @return the severity
- */
- public Object getSeverity() {
- return this.severity;
- }
-
- /**
- * Sets the introspector.
- *
- * @param obj the new introspector
- */
- public void setIntrospector(Introspector obj) {
- this.obj = obj;
- }
-
- /**
- * Gets the introspector.
- *
- * @return the introspector
- */
- public Introspector getIntrospector() {
- return this.obj;
- }
-
- /**
- * Gets the detail.
- *
- * @return the detail
- */
- public String getDetail() {
- return this.detail;
- }
-
- /**
- * Gets the error.
- *
- * @return the error
- */
- public IssueType getType() {
- return this.error;
- }
-
- /**
- * Sets the prop name.
- *
- * @param prop the new prop name
- */
- public void setPropName(String prop) {
- this.propName= prop;
- }
-
- /**
- * Gets the prop name.
- *
- * @return the prop name
- */
- public String getPropName() {
- return this.propName;
- }
-
- /**
- * Checks if is resolved.
- *
- * @return true, if is resolved
- */
- public boolean isResolved() {
- return resolved;
- }
-
- /**
- * Sets the resolved.
- *
- * @param resolved the new resolved
- */
- public void setResolved(boolean resolved) {
- this.resolved = resolved;
- }
-
-
+ private Severity severity;
+ private IssueType error;
+ private String detail;
+ private Introspector obj;
+ private String propName;
+ private boolean resolved = false;
+
+ /**
+ * Sets the severity.
+ *
+ * @param severity the new severity
+ */
+ public void setSeverity(Severity severity) {
+
+ this.severity = severity;
+ }
+
+ /**
+ * Sets the error.
+ *
+ * @param error the new error
+ */
+ public void setType(IssueType error) {
+ this.error = error;
+ }
+
+ /**
+ * Sets the detail.
+ *
+ * @param detail the new detail
+ */
+ public void setDetail(String detail) {
+ this.detail = detail;
+ }
+
+ /**
+ * Gets the severity.
+ *
+ * @return the severity
+ */
+ public Object getSeverity() {
+ return this.severity;
+ }
+
+ /**
+ * Sets the introspector.
+ *
+ * @param obj the new introspector
+ */
+ public void setIntrospector(Introspector obj) {
+ this.obj = obj;
+ }
+
+ /**
+ * Gets the introspector.
+ *
+ * @return the introspector
+ */
+ public Introspector getIntrospector() {
+ return this.obj;
+ }
+
+ /**
+ * Gets the detail.
+ *
+ * @return the detail
+ */
+ public String getDetail() {
+ return this.detail;
+ }
+
+ /**
+ * Gets the error.
+ *
+ * @return the error
+ */
+ public IssueType getType() {
+ return this.error;
+ }
+
+ /**
+ * Sets the prop name.
+ *
+ * @param prop the new prop name
+ */
+ public void setPropName(String prop) {
+ this.propName = prop;
+ }
+
+ /**
+ * Gets the prop name.
+ *
+ * @return the prop name
+ */
+ public String getPropName() {
+ return this.propName;
+ }
+
+ /**
+ * Checks if is resolved.
+ *
+ * @return true, if is resolved
+ */
+ public boolean isResolved() {
+ return resolved;
+ }
+
+ /**
+ * Sets the resolved.
+ *
+ * @param resolved the new resolved
+ */
+ public void setResolved(boolean resolved) {
+ this.resolved = resolved;
+ }
+
}
diff --git a/aai-core/src/main/java/org/onap/aai/introspection/tools/IssueResolver.java b/aai-core/src/main/java/org/onap/aai/introspection/tools/IssueResolver.java
index b47d7531..63f7e8ec 100644
--- a/aai-core/src/main/java/org/onap/aai/introspection/tools/IssueResolver.java
+++ b/aai-core/src/main/java/org/onap/aai/introspection/tools/IssueResolver.java
@@ -17,16 +17,16 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.introspection.tools;
public interface IssueResolver {
-
- /**
- * Resolve issue.
- *
- * @param issue the issue
- * @return true, if successful
- */
- public boolean resolveIssue(Issue issue);
+ /**
+ * Resolve issue.
+ *
+ * @param issue the issue
+ * @return true, if successful
+ */
+ public boolean resolveIssue(Issue issue);
}
diff --git a/aai-core/src/main/java/org/onap/aai/introspection/tools/IssueType.java b/aai-core/src/main/java/org/onap/aai/introspection/tools/IssueType.java
index 51516172..8b75bf8f 100644
--- a/aai-core/src/main/java/org/onap/aai/introspection/tools/IssueType.java
+++ b/aai-core/src/main/java/org/onap/aai/introspection/tools/IssueType.java
@@ -17,8 +17,9 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.introspection.tools;
public enum IssueType {
- MISSING_REQUIRED_PROP, MISSING_KEY_PROP, EXCEEDED_ALLOWED_DEPTH, PROPERTY_NOT_VISIBLE, DEPENDENT_PROP_NOT_FOUND
+ MISSING_REQUIRED_PROP, MISSING_KEY_PROP, EXCEEDED_ALLOWED_DEPTH, PROPERTY_NOT_VISIBLE, DEPENDENT_PROP_NOT_FOUND
}
diff --git a/aai-core/src/main/java/org/onap/aai/introspection/tools/RemoveNonVisibleProperty.java b/aai-core/src/main/java/org/onap/aai/introspection/tools/RemoveNonVisibleProperty.java
index 07fff1bc..062fb96b 100644
--- a/aai-core/src/main/java/org/onap/aai/introspection/tools/RemoveNonVisibleProperty.java
+++ b/aai-core/src/main/java/org/onap/aai/introspection/tools/RemoveNonVisibleProperty.java
@@ -17,19 +17,20 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.introspection.tools;
public class RemoveNonVisibleProperty implements IssueResolver {
- @Override
- public boolean resolveIssue(Issue issue) {
+ @Override
+ public boolean resolveIssue(Issue issue) {
- if (IssueType.PROPERTY_NOT_VISIBLE.equals(issue.getType())) {
- //remove property value
- issue.getIntrospector().setValue(issue.getPropName(), null);
- return true;
- }
- return false;
- }
+ if (IssueType.PROPERTY_NOT_VISIBLE.equals(issue.getType())) {
+ // remove property value
+ issue.getIntrospector().setValue(issue.getPropName(), null);
+ return true;
+ }
+ return false;
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/introspection/tools/Severity.java b/aai-core/src/main/java/org/onap/aai/introspection/tools/Severity.java
index 5e48bcc1..5cc56cc7 100644
--- a/aai-core/src/main/java/org/onap/aai/introspection/tools/Severity.java
+++ b/aai-core/src/main/java/org/onap/aai/introspection/tools/Severity.java
@@ -17,10 +17,9 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.introspection.tools;
public enum Severity {
- WARNING,
- ERROR,
- CRITICAL
+ WARNING, ERROR, CRITICAL
}
diff --git a/aai-core/src/main/java/org/onap/aai/logging/CNName.java b/aai-core/src/main/java/org/onap/aai/logging/CNName.java
index 1a60af13..5337afe3 100644
--- a/aai-core/src/main/java/org/onap/aai/logging/CNName.java
+++ b/aai-core/src/main/java/org/onap/aai/logging/CNName.java
@@ -17,80 +17,83 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.logging;
+import static java.util.Base64.getDecoder;
+
import ch.qos.logback.access.pattern.AccessConverter;
import ch.qos.logback.access.spi.IAccessEvent;
+
import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
-import javax.security.auth.x500.X500Principal;
-import javax.servlet.http.HttpServletRequest;
import java.security.cert.X509Certificate;
-import static java.util.Base64.getDecoder;
+import javax.security.auth.x500.X500Principal;
+import javax.servlet.http.HttpServletRequest;
public class CNName extends AccessConverter {
- private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(CNName.class);
-
- /**
- * Converts access events to String response codes
- *
- * @param accessEvent the IAccessEvent
- */
- public String convert(IAccessEvent accessEvent) {
- if (!isStarted()) {
- return "INACTIVE_HEADER_CONV";
- }
-
- String cipherSuite = (String) accessEvent.getRequest().getAttribute("javax.servlet.request.cipher_suite");
- String authUser = null;
- if (cipherSuite != null) {
- try {
+ private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(CNName.class);
+
+ /**
+ * Converts access events to String response codes
+ *
+ * @param accessEvent the IAccessEvent
+ */
+ public String convert(IAccessEvent accessEvent) {
+ if (!isStarted()) {
+ return "INACTIVE_HEADER_CONV";
+ }
+
+ String cipherSuite = (String) accessEvent.getRequest().getAttribute("javax.servlet.request.cipher_suite");
+ String authUser = null;
+ if (cipherSuite != null) {
+ try {
X509Certificate certChain[] = (X509Certificate[]) accessEvent.getRequest()
.getAttribute("javax.servlet.request.X509Certificate");
- if(certChain == null || certChain.length == 0){
+ if (certChain == null || certChain.length == 0) {
- HttpServletRequest request = accessEvent.getRequest();
+ HttpServletRequest request = accessEvent.getRequest();
- String authorization = request.getHeader("Authorization");
+ String authorization = request.getHeader("Authorization");
// Set the auth user to "-" so if the authorization header is not found
- // Or if the decoded basic auth credentials are not found in the format required
- // it should return "-"
- // If the decoded string is in the right format, find the index of ":"
+ // Or if the decoded basic auth credentials are not found in the format required
+ // it should return "-"
+ // If the decoded string is in the right format, find the index of ":"
// Then get the substring of the starting point to the colon not including the colon
authUser = "-";
- if(authorization != null && authorization.startsWith("Basic ")){
- String credentials = authorization.replace("Basic ", "");
+ if (authorization != null && authorization.startsWith("Basic ")) {
+ String credentials = authorization.replace("Basic ", "");
byte[] userCredentials = getDecoder().decode(credentials.getBytes("utf-8"));
credentials = new String(userCredentials);
- int codePoint = credentials.indexOf(':');
+ int codePoint = credentials.indexOf(':');
- if(codePoint != -1){
+ if (codePoint != -1) {
authUser = credentials.substring(0, codePoint);
- }
-
- }
-
- return authUser;
-
- } else {
- X509Certificate clientCert = certChain[0];
- X500Principal subjectDN = clientCert.getSubjectX500Principal();
- authUser = subjectDN.toString();
- return authUser;
- }
- } catch(Exception e){
- LOGGER.error(e.getMessage(),e);
- return "-";
- }
- } else {
- return "-";
- }
- }
+ }
+
+ }
+
+ return authUser;
+
+ } else {
+ X509Certificate clientCert = certChain[0];
+ X500Principal subjectDN = clientCert.getSubjectX500Principal();
+ authUser = subjectDN.toString();
+ return authUser;
+ }
+ } catch (Exception e) {
+ LOGGER.error(e.getMessage(), e);
+ return "-";
+ }
+ } else {
+ return "-";
+ }
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/logging/CustomLogPatternLayout.java b/aai-core/src/main/java/org/onap/aai/logging/CustomLogPatternLayout.java
index ee7b4ef9..63cc49f7 100644
--- a/aai-core/src/main/java/org/onap/aai/logging/CustomLogPatternLayout.java
+++ b/aai-core/src/main/java/org/onap/aai/logging/CustomLogPatternLayout.java
@@ -17,11 +17,12 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.logging;
public class CustomLogPatternLayout extends ch.qos.logback.access.PatternLayout {
- static {
- defaultConverterMap.put("z", CNName.class.getName());
- defaultConverterMap.put("y", DME2RestFlag.class.getName());
- }
+ static {
+ defaultConverterMap.put("z", CNName.class.getName());
+ defaultConverterMap.put("y", DME2RestFlag.class.getName());
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/logging/CustomLogPatternLayoutEncoder.java b/aai-core/src/main/java/org/onap/aai/logging/CustomLogPatternLayoutEncoder.java
index 0f474eef..010d828b 100644
--- a/aai-core/src/main/java/org/onap/aai/logging/CustomLogPatternLayoutEncoder.java
+++ b/aai-core/src/main/java/org/onap/aai/logging/CustomLogPatternLayoutEncoder.java
@@ -17,23 +17,24 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.logging;
import ch.qos.logback.access.PatternLayout;
public class CustomLogPatternLayoutEncoder extends ch.qos.logback.access.PatternLayoutEncoder {
-/**
- * @{inheritDoc}
- */
- @Override
- public void start(){
- PatternLayout patternLayout = new CustomLogPatternLayout();
- patternLayout.setContext(context);
- patternLayout.setPattern(getPattern());
- patternLayout.start();
- this.layout = patternLayout;
- super.start();
- }
+ /**
+ * @{inheritDoc}
+ */
+ @Override
+ public void start() {
+ PatternLayout patternLayout = new CustomLogPatternLayout();
+ patternLayout.setContext(context);
+ patternLayout.setPattern(getPattern());
+ patternLayout.start();
+ this.layout = patternLayout;
+ super.start();
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/logging/DME2RestFlag.java b/aai-core/src/main/java/org/onap/aai/logging/DME2RestFlag.java
index 86c25260..768c095b 100644
--- a/aai-core/src/main/java/org/onap/aai/logging/DME2RestFlag.java
+++ b/aai-core/src/main/java/org/onap/aai/logging/DME2RestFlag.java
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.logging;
import ch.qos.logback.access.pattern.AccessConverter;
@@ -24,31 +25,31 @@ import ch.qos.logback.access.spi.IAccessEvent;
public class DME2RestFlag extends AccessConverter {
- /**
- * @{inheritDoc}
- */
- @Override
- public String convert(IAccessEvent accessEvent) {
- if (!isStarted()) {
- return "INACTIVE_HEADER_CONV";
- }
+ /**
+ * @{inheritDoc}
+ */
+ @Override
+ public String convert(IAccessEvent accessEvent) {
+ if (!isStarted()) {
+ return "INACTIVE_HEADER_CONV";
+ }
- String flag = "-";
+ String flag = "-";
- if (accessEvent.getRequestParameter("envContext").length > 0
- && !accessEvent.getRequestParameter("envContext")[0].isEmpty()
- && !accessEvent.getRequestParameter("envContext")[0].equals("-")
- && accessEvent.getRequestParameter("routeOffer").length > 0
- && !accessEvent.getRequestParameter("routeOffer")[0].isEmpty()
- && !accessEvent.getRequestParameter("routeOffer")[0].equals("-")
- && accessEvent.getRequestParameter("version").length > 0
- && !accessEvent.getRequestParameter("version")[0].isEmpty()
- && !accessEvent.getRequestParameter("version")[0].equals("-")) {
- flag = "DME2";
- } else {
- flag = "REST";
- }
+ if (accessEvent.getRequestParameter("envContext").length > 0
+ && !accessEvent.getRequestParameter("envContext")[0].isEmpty()
+ && !accessEvent.getRequestParameter("envContext")[0].equals("-")
+ && accessEvent.getRequestParameter("routeOffer").length > 0
+ && !accessEvent.getRequestParameter("routeOffer")[0].isEmpty()
+ && !accessEvent.getRequestParameter("routeOffer")[0].equals("-")
+ && accessEvent.getRequestParameter("version").length > 0
+ && !accessEvent.getRequestParameter("version")[0].isEmpty()
+ && !accessEvent.getRequestParameter("version")[0].equals("-")) {
+ flag = "DME2";
+ } else {
+ flag = "REST";
+ }
- return flag;
- }
+ return flag;
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/logging/EcompElapsedTime.java b/aai-core/src/main/java/org/onap/aai/logging/EcompElapsedTime.java
index f6c89b9f..66d27868 100644
--- a/aai-core/src/main/java/org/onap/aai/logging/EcompElapsedTime.java
+++ b/aai-core/src/main/java/org/onap/aai/logging/EcompElapsedTime.java
@@ -17,50 +17,50 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-package org.onap.aai.logging;
-import org.onap.aai.logging.LoggingContext.LoggingField;
+package org.onap.aai.logging;
import ch.qos.logback.classic.pattern.ClassicConverter;
import ch.qos.logback.classic.spi.ILoggingEvent;
+import org.onap.aai.logging.LoggingContext.LoggingField;
+
public class EcompElapsedTime extends ClassicConverter {
- private static final String DEFAULT_ELAPSED_TIME_FORMAT = "%d";
+ private static final String DEFAULT_ELAPSED_TIME_FORMAT = "%d";
- private String ELAPSED_TIME_FORMAT;
+ private String ELAPSED_TIME_FORMAT;
- @Override
- public void start() {
- ELAPSED_TIME_FORMAT = getFirstOption();
- }
+ @Override
+ public void start() {
+ ELAPSED_TIME_FORMAT = getFirstOption();
+ }
- @Override
- public String convert(ILoggingEvent event) {
- final long end = event.getTimeStamp();
+ @Override
+ public String convert(ILoggingEvent event) {
+ final long end = event.getTimeStamp();
- if (!event.getMDCPropertyMap().containsKey(LoggingField.START_TIME.toString())) {
- return format(0);
- } else if (event.getMDCPropertyMap().containsKey(LoggingField.ELAPSED_TIME.toString())) {
- return format(
- Integer.parseInt(event.getMDCPropertyMap().get(LoggingField.ELAPSED_TIME.toString()))
- );
- }
+ if (!event.getMDCPropertyMap().containsKey(LoggingField.START_TIME.toString())) {
+ return format(0);
+ } else if (event.getMDCPropertyMap().containsKey(LoggingField.ELAPSED_TIME.toString())) {
+ return format(Integer.parseInt(event.getMDCPropertyMap().get(LoggingField.ELAPSED_TIME.toString())));
+ }
- final long start = LogFormatTools.toTimestamp(event.getMDCPropertyMap().get(LoggingField.START_TIME.toString()));
+ final long start =
+ LogFormatTools.toTimestamp(event.getMDCPropertyMap().get(LoggingField.START_TIME.toString()));
- return format(end - start);
- }
+ return format(end - start);
+ }
- private String format(long elapsedTime) {
- if (ELAPSED_TIME_FORMAT == null) {
- return format(DEFAULT_ELAPSED_TIME_FORMAT, elapsedTime);
- }
+ private String format(long elapsedTime) {
+ if (ELAPSED_TIME_FORMAT == null) {
+ return format(DEFAULT_ELAPSED_TIME_FORMAT, elapsedTime);
+ }
- return format (ELAPSED_TIME_FORMAT, elapsedTime);
- }
+ return format(ELAPSED_TIME_FORMAT, elapsedTime);
+ }
- private String format(String format, long elapsedTime) {
- return String.format(format, elapsedTime);
- }
+ private String format(String format, long elapsedTime) {
+ return String.format(format, elapsedTime);
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/logging/EcompEncoder.java b/aai-core/src/main/java/org/onap/aai/logging/EcompEncoder.java
index 18a8425f..88587297 100644
--- a/aai-core/src/main/java/org/onap/aai/logging/EcompEncoder.java
+++ b/aai-core/src/main/java/org/onap/aai/logging/EcompEncoder.java
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.logging;
import ch.qos.logback.classic.PatternLayout;
diff --git a/aai-core/src/main/java/org/onap/aai/logging/EcompErrorCategory.java b/aai-core/src/main/java/org/onap/aai/logging/EcompErrorCategory.java
index 48c87c59..452fcd08 100644
--- a/aai-core/src/main/java/org/onap/aai/logging/EcompErrorCategory.java
+++ b/aai-core/src/main/java/org/onap/aai/logging/EcompErrorCategory.java
@@ -17,26 +17,26 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.logging;
+import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.pattern.ClassicConverter;
import ch.qos.logback.classic.spi.ILoggingEvent;
-import ch.qos.logback.classic.Level;
public class EcompErrorCategory extends ClassicConverter {
- @Override
- public String convert(ILoggingEvent event) {
-
- final Level lev = event.getLevel();
- final String defaultCategory = "WARN";
-
- if ((Level.WARN).equals(lev)) {
- return (defaultCategory);
- }
- else if ((Level.ERROR).equals(lev)) {
- return ("ERROR");
- }
- return (defaultCategory);
- }
+ @Override
+ public String convert(ILoggingEvent event) {
+
+ final Level lev = event.getLevel();
+ final String defaultCategory = "WARN";
+
+ if ((Level.WARN).equals(lev)) {
+ return (defaultCategory);
+ } else if ((Level.ERROR).equals(lev)) {
+ return ("ERROR");
+ }
+ return (defaultCategory);
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/logging/EcompPatternLayout.java b/aai-core/src/main/java/org/onap/aai/logging/EcompPatternLayout.java
index 65374312..43c147a0 100644
--- a/aai-core/src/main/java/org/onap/aai/logging/EcompPatternLayout.java
+++ b/aai-core/src/main/java/org/onap/aai/logging/EcompPatternLayout.java
@@ -17,19 +17,20 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.logging;
import ch.qos.logback.classic.PatternLayout;
public class EcompPatternLayout extends PatternLayout {
- static {
- PatternLayout.defaultConverterMap.put("ecompStartTime", EcompStartTime.class.getName());
- PatternLayout.defaultConverterMap.put("ecompElapsedTime", EcompElapsedTime.class.getName());
- PatternLayout.defaultConverterMap.put("eelfClassOfCaller", EelfClassOfCaller.class.getName());
- PatternLayout.defaultConverterMap.put("ecompErrorCategory", EcompErrorCategory.class.getName());
- PatternLayout.defaultConverterMap.put("ecompResponseCode", EcompResponseCode.class.getName());
- PatternLayout.defaultConverterMap.put("ecompResponseDescription", EcompResponseDescription.class.getName());
- PatternLayout.defaultConverterMap.put("ecompStatusCode", EcompStatusCode.class.getName());
- PatternLayout.defaultConverterMap.put("ecompServiceName", EcompServiceName.class.getName());
- }
+ static {
+ PatternLayout.defaultConverterMap.put("ecompStartTime", EcompStartTime.class.getName());
+ PatternLayout.defaultConverterMap.put("ecompElapsedTime", EcompElapsedTime.class.getName());
+ PatternLayout.defaultConverterMap.put("eelfClassOfCaller", EelfClassOfCaller.class.getName());
+ PatternLayout.defaultConverterMap.put("ecompErrorCategory", EcompErrorCategory.class.getName());
+ PatternLayout.defaultConverterMap.put("ecompResponseCode", EcompResponseCode.class.getName());
+ PatternLayout.defaultConverterMap.put("ecompResponseDescription", EcompResponseDescription.class.getName());
+ PatternLayout.defaultConverterMap.put("ecompStatusCode", EcompStatusCode.class.getName());
+ PatternLayout.defaultConverterMap.put("ecompServiceName", EcompServiceName.class.getName());
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/logging/EcompResponseCode.java b/aai-core/src/main/java/org/onap/aai/logging/EcompResponseCode.java
index b57c6650..1dc59b4e 100644
--- a/aai-core/src/main/java/org/onap/aai/logging/EcompResponseCode.java
+++ b/aai-core/src/main/java/org/onap/aai/logging/EcompResponseCode.java
@@ -17,22 +17,23 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-package org.onap.aai.logging;
-import org.onap.aai.logging.LoggingContext.LoggingField;
+package org.onap.aai.logging;
import ch.qos.logback.classic.pattern.ClassicConverter;
import ch.qos.logback.classic.spi.ILoggingEvent;
+import org.onap.aai.logging.LoggingContext.LoggingField;
+
public class EcompResponseCode extends ClassicConverter {
- @Override
- public String convert(ILoggingEvent event) {
+ @Override
+ public String convert(ILoggingEvent event) {
- if (!event.getMDCPropertyMap().containsKey(LoggingField.RESPONSE_CODE.toString())) {
- // if response code is not set, return "unknown" (900)
- return LoggingContext.UNKNOWN_ERROR;
- }
- return event.getMDCPropertyMap().get(LoggingField.RESPONSE_CODE.toString());
- }
+ if (!event.getMDCPropertyMap().containsKey(LoggingField.RESPONSE_CODE.toString())) {
+ // if response code is not set, return "unknown" (900)
+ return LoggingContext.UNKNOWN_ERROR;
+ }
+ return event.getMDCPropertyMap().get(LoggingField.RESPONSE_CODE.toString());
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/logging/EcompResponseDescription.java b/aai-core/src/main/java/org/onap/aai/logging/EcompResponseDescription.java
index eb11c16b..4b2b3b46 100644
--- a/aai-core/src/main/java/org/onap/aai/logging/EcompResponseDescription.java
+++ b/aai-core/src/main/java/org/onap/aai/logging/EcompResponseDescription.java
@@ -17,28 +17,30 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-package org.onap.aai.logging;
-import org.onap.aai.logging.LoggingContext.LoggingField;
+package org.onap.aai.logging;
import ch.qos.logback.classic.pattern.ClassicConverter;
import ch.qos.logback.classic.spi.ILoggingEvent;
+import org.onap.aai.logging.LoggingContext.LoggingField;
+
public class EcompResponseDescription extends ClassicConverter {
- public final static String DefaultDescription = "Unknown response/error description";
- @Override
- public String convert(ILoggingEvent event) {
+ public final static String DefaultDescription = "Unknown response/error description";
+
+ @Override
+ public String convert(ILoggingEvent event) {
- if (!event.getMDCPropertyMap().containsKey(LoggingField.RESPONSE_DESCRIPTION.toString())) {
- return (DefaultDescription);
- }
- // Replace pipes and new lines
- String currentDesc = event.getMDCPropertyMap().get(LoggingField.RESPONSE_DESCRIPTION.toString());
- if ( (currentDesc == null) || (currentDesc.length() == 0) ) {
- return (DefaultDescription);
- }
- currentDesc = currentDesc.replaceAll("|", "!");
- currentDesc = currentDesc.replaceAll("[\\r\\n]+", "^");
- return event.getMDCPropertyMap().get(LoggingField.RESPONSE_DESCRIPTION.toString());
- }
+ if (!event.getMDCPropertyMap().containsKey(LoggingField.RESPONSE_DESCRIPTION.toString())) {
+ return (DefaultDescription);
+ }
+ // Replace pipes and new lines
+ String currentDesc = event.getMDCPropertyMap().get(LoggingField.RESPONSE_DESCRIPTION.toString());
+ if ((currentDesc == null) || (currentDesc.length() == 0)) {
+ return (DefaultDescription);
+ }
+ currentDesc = currentDesc.replaceAll("|", "!");
+ currentDesc = currentDesc.replaceAll("[\\r\\n]+", "^");
+ return event.getMDCPropertyMap().get(LoggingField.RESPONSE_DESCRIPTION.toString());
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/logging/EcompServiceName.java b/aai-core/src/main/java/org/onap/aai/logging/EcompServiceName.java
index e20c841b..10d7a211 100644
--- a/aai-core/src/main/java/org/onap/aai/logging/EcompServiceName.java
+++ b/aai-core/src/main/java/org/onap/aai/logging/EcompServiceName.java
@@ -17,10 +17,12 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.logging;
import ch.qos.logback.classic.pattern.ClassicConverter;
import ch.qos.logback.classic.spi.ILoggingEvent;
+
import org.onap.aai.logging.LoggingContext.LoggingField;
public class EcompServiceName extends ClassicConverter {
@@ -32,4 +34,3 @@ public class EcompServiceName extends ClassicConverter {
return event.getMDCPropertyMap().get(LoggingField.SERVICE_NAME.toString());
}
}
-
diff --git a/aai-core/src/main/java/org/onap/aai/logging/EcompStartTime.java b/aai-core/src/main/java/org/onap/aai/logging/EcompStartTime.java
index ef383af6..8f015414 100644
--- a/aai-core/src/main/java/org/onap/aai/logging/EcompStartTime.java
+++ b/aai-core/src/main/java/org/onap/aai/logging/EcompStartTime.java
@@ -17,22 +17,23 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-package org.onap.aai.logging;
-import org.onap.aai.logging.LoggingContext.LoggingField;
+package org.onap.aai.logging;
import ch.qos.logback.classic.pattern.ClassicConverter;
import ch.qos.logback.classic.spi.ILoggingEvent;
+import org.onap.aai.logging.LoggingContext.LoggingField;
+
public class EcompStartTime extends ClassicConverter {
- @Override
- public String convert(ILoggingEvent event) {
+ @Override
+ public String convert(ILoggingEvent event) {
- if (!event.getMDCPropertyMap().containsKey(LoggingField.START_TIME.toString())) {
- return LogFormatTools.toDate(event.getTimeStamp());
- }
+ if (!event.getMDCPropertyMap().containsKey(LoggingField.START_TIME.toString())) {
+ return LogFormatTools.toDate(event.getTimeStamp());
+ }
- return event.getMDCPropertyMap().get(LoggingField.START_TIME.toString());
- }
+ return event.getMDCPropertyMap().get(LoggingField.START_TIME.toString());
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/logging/EcompStatusCode.java b/aai-core/src/main/java/org/onap/aai/logging/EcompStatusCode.java
index 1ac4606b..4319bbbd 100644
--- a/aai-core/src/main/java/org/onap/aai/logging/EcompStatusCode.java
+++ b/aai-core/src/main/java/org/onap/aai/logging/EcompStatusCode.java
@@ -17,12 +17,14 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.logging;
-import org.onap.aai.logging.LoggingContext.LoggingField;
import ch.qos.logback.classic.pattern.ClassicConverter;
import ch.qos.logback.classic.spi.ILoggingEvent;
+import org.onap.aai.logging.LoggingContext.LoggingField;
+
public class EcompStatusCode extends ClassicConverter {
@Override
public String convert(ILoggingEvent event) {
@@ -32,4 +34,3 @@ public class EcompStatusCode extends ClassicConverter {
return event.getMDCPropertyMap().get(LoggingField.STATUS_CODE.toString());
}
}
-
diff --git a/aai-core/src/main/java/org/onap/aai/logging/EelfClassOfCaller.java b/aai-core/src/main/java/org/onap/aai/logging/EelfClassOfCaller.java
index f7ae2e93..dc9bc2c2 100644
--- a/aai-core/src/main/java/org/onap/aai/logging/EelfClassOfCaller.java
+++ b/aai-core/src/main/java/org/onap/aai/logging/EelfClassOfCaller.java
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.logging;
import ch.qos.logback.classic.pattern.NamedConverter;
@@ -28,13 +29,13 @@ public class EelfClassOfCaller extends NamedConverter {
StackTraceElement[] cda = event.getCallerData();
- //If using the EELFLogger, it "hides" the calling class because it wraps the logging calls
- //Without this, you'd only ever see "EELF SLF4jWrapper" when using the
- // %C pattern converter
+ // If using the EELFLogger, it "hides" the calling class because it wraps the logging calls
+ // Without this, you'd only ever see "EELF SLF4jWrapper" when using the
+ // %C pattern converter
if (cda != null && cda.length > 2) {
return cda[2].getClassName();
} else if (cda != null && cda.length > 0) {
- return cda[0].getClassName();
+ return cda[0].getClassName();
} else {
return CallerData.NA;
}
diff --git a/aai-core/src/main/java/org/onap/aai/logging/ErrorLogHelper.java b/aai-core/src/main/java/org/onap/aai/logging/ErrorLogHelper.java
index 7d97ffbf..01327606 100644
--- a/aai-core/src/main/java/org/onap/aai/logging/ErrorLogHelper.java
+++ b/aai-core/src/main/java/org/onap/aai/logging/ErrorLogHelper.java
@@ -17,8 +17,12 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.logging;
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
+
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
@@ -36,581 +40,594 @@ import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import org.apache.commons.lang.StringUtils;
-import org.slf4j.MDC;
-
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.logging.LoggingContext.StatusCode;
import org.onap.aai.util.AAIConfig;
import org.onap.aai.util.AAIConstants;
import org.onap.aai.util.MapperUtil;
-
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
+import org.slf4j.MDC;
/**
*
* This classes loads the application error properties file
- * and provides a method that returns an ErrorObject
+ * and provides a method that returns an ErrorObject
*
*/
public class ErrorLogHelper {
- private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(ErrorLogHelper.class);
- private static final HashMap<String, ErrorObject> ERROR_OBJECTS = new HashMap<String, ErrorObject> ();
-
- static {
- try {
- loadProperties();
- } catch (IOException e) {
- throw new RuntimeException("Failed to load error.properties file", e);
- } catch (ErrorObjectFormatException e) {
- throw new RuntimeException("Failed to parse error.properties file", e);
- }
- }
-
- /**
- * Load properties.
- * @throws ErrorObjectFormatException
- * @throws Exception the exception
- */
- public static void loadProperties() throws IOException, ErrorObjectFormatException {
- final String filePath = AAIConstants.AAI_HOME_ETC_APP_PROPERTIES + "error.properties";
- final InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(filePath);
- final Properties properties = new Properties();
-
- if (is != null) {
- properties.load(is);
- } else {
- try (final FileInputStream fis = new FileInputStream(filePath)) {
- properties.load(fis);
- }
- }
-
- for (Entry<Object, Object> entry : properties.entrySet()) {
- final String key = (String) entry.getKey();
- final String value = (String) entry.getValue();
- final String[] errorProperties = value.split(":");
-
- if (errorProperties.length != 7) throw new ErrorObjectFormatException();
-
- final ErrorObject errorObject = new ErrorObject();
-
- errorObject.setDisposition(errorProperties[0].trim());
- errorObject.setCategory(errorProperties[1].trim());
- errorObject.setSeverity(errorProperties[2].trim());
- errorObject.setErrorCode(errorProperties[3].trim());
- errorObject.setHTTPResponseCode(errorProperties[4].trim());
- errorObject.setRESTErrorCode(errorProperties[5].trim());
- errorObject.setErrorText(errorProperties[6].trim());
-
- ERROR_OBJECTS.put(key, errorObject);
- }
- }
-
- /**
- * Logs a known A&AI exception (i.e. one that can be found in error.properties)
- *
- * @param key The key for the error in the error.properties file
- * @throws IOException
- * @throws ErrorObjectNotFoundException
- * @throws ErrorObjectFormatException
- */
- public static ErrorObject getErrorObject(String code) throws ErrorObjectNotFoundException {
-
- if (code == null) throw new IllegalArgumentException("Key cannot be null");
-
- final ErrorObject errorObject = ERROR_OBJECTS.get(code);
-
- if (errorObject == null) {
- LOGGER.warn("Unknown AAIException with code=" + code + ". Using default AAIException");
- return ERROR_OBJECTS.get(AAIException.DEFAULT_EXCEPTION_CODE);
- }
-
- return errorObject;
- }
-
- /**
- * Determines whether category is policy or not. If policy (1), this is a POL error, else it's a SVC error.
- * The AAIRESTException may contain a different ErrorObject than that created with the REST error key.
- * This allows lower level exception detail to be returned to the client to help troubleshoot the problem.
- * If no error object is embedded in the AAIException, one will be created using the error object from the AAIException.
- * @param are must have a restError value whose numeric value must match what should be returned in the REST API
- * @param variables optional list of variables to flesh out text in error string
- * @return appropriately formatted JSON response per the REST API spec.
- * @throws ErrorObjectFormatException
- * @throws ErrorObjectNotFoundException
- * @throws IOException
- * @deprecated
- */
- public static String getRESTAPIErrorResponse(AAIException are, ArrayList<String> variables) {
- List<MediaType> acceptHeaders = new ArrayList<MediaType>();
- acceptHeaders.add(MediaType.APPLICATION_JSON_TYPE);
-
- return getRESTAPIErrorResponse(acceptHeaders, are, variables);
- }
-
- /**
- * Determines whether category is policy or not. If policy (1), this is a POL error, else it's a SVC error.
- * The AAIRESTException may contain a different ErrorObject than that created with the REST error key.
- * This allows lower level exception detail to be returned to the client to help troubleshoot the problem.
- * If no error object is embedded in the AAIException, one will be created using the error object from the AAIException.
- *
- * @param acceptHeadersOrig the accept headers orig
- * @param are must have a restError value whose numeric value must match what should be returned in the REST API
- * @param variables optional list of variables to flesh out text in error string
- * @return appropriately formatted JSON response per the REST API spec.
- * @throws ErrorObjectFormatException
- * @throws ErrorObjectNotFoundException
- * @throws IOException
- */
- public static String getRESTAPIErrorResponse(List<MediaType> acceptHeadersOrig, AAIException are, ArrayList<String> variables) {
-
-
- StringBuilder text = new StringBuilder();
- String response = null;
-
- List<MediaType> acceptHeaders = new ArrayList<MediaType>();
- // we might have an exception but no accept header, so we'll set default to JSON
- boolean foundValidAcceptHeader = false;
- for (MediaType mt : acceptHeadersOrig) {
- if (MediaType.APPLICATION_XML_TYPE.isCompatible(mt) ||
- MediaType.APPLICATION_JSON_TYPE.isCompatible(mt)) {
- acceptHeaders.add(mt);
- foundValidAcceptHeader = true;
- }
- }
- if (foundValidAcceptHeader == false) {
- // override the exception, client needs to set an appropriate Accept header
- are = new AAIException("AAI_4014");
- acceptHeaders.add(MediaType.APPLICATION_JSON_TYPE);
- }
-
- final ErrorObject eo = are.getErrorObject();
-
- int restErrorCode = Integer.parseInt(eo.getRESTErrorCode());
-
- ErrorObject restErrorObject;
-
- try {
- restErrorObject = ErrorLogHelper.getErrorObject("AAI_"+restErrorCode);
- } catch (ErrorObjectNotFoundException e) {
- LOGGER.warn("Failed to find related error object AAI_" + restErrorCode + " for error object " + eo.getErrorCode() + "; using AAI_" + restErrorCode);
- restErrorObject = eo;
- }
-
- text.append(restErrorObject.getErrorText());
-
- // We want to always append the (msg=%n) (ec=%n+1) to the text, but have to find value of n
- // This assumes that the variables in the ArrayList, which might be more than are needed to flesh out the
- // error, are ordered based on the error string.
- int localDataIndex = StringUtils.countMatches(restErrorObject.getErrorText(), "%");
- text.append(" (msg=%").append(localDataIndex+1).append(") (ec=%").append(localDataIndex+2).append(")");
-
- if (variables == null)
- {
- variables = new ArrayList<String>();
- }
-
- if (variables.size() < localDataIndex) {
- ErrorLogHelper.logError("AAI_4011", "data missing for rest error");
- while (variables.size() < localDataIndex) {
- variables.add("null");
- }
- }
-
- // This will put the error code and error text into the right positions
- if (are.getMessage() == null || are.getMessage().length() == 0) {
- variables.add(localDataIndex++, eo.getErrorText());
- }
- else {
- variables.add(localDataIndex++, eo.getErrorText() + ":" + are.getMessage());
- }
- variables.add(localDataIndex, eo.getErrorCodeString());
-
- for (MediaType mediaType : acceptHeaders) {
- if (MediaType.APPLICATION_XML_TYPE.isCompatible(mediaType)) {
- JAXBContext context = null;
- try {
- if(eo.getCategory().equals("1")) {
-
- context = JAXBContext.newInstance(org.onap.aai.domain.restPolicyException.Fault.class);
- Marshaller m = context.createMarshaller();
- m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
- m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
-
- org.onap.aai.domain.restPolicyException.ObjectFactory factory = new org.onap.aai.domain.restPolicyException.ObjectFactory();
- org.onap.aai.domain.restPolicyException.Fault fault = factory.createFault();
- org.onap.aai.domain.restPolicyException.Fault.RequestError requestError = factory.createFaultRequestError();
- org.onap.aai.domain.restPolicyException.Fault.RequestError.PolicyException policyException = factory.createFaultRequestErrorPolicyException();
- org.onap.aai.domain.restPolicyException.Fault.RequestError.PolicyException.Variables polvariables = factory.createFaultRequestErrorPolicyExceptionVariables();
-
- policyException.setMessageId("POL" + eo.getRESTErrorCode());
- policyException.setText(text.toString());
- for (int i=0;i<variables.size();i++)
- {
- polvariables.getVariable().add(variables.get(i));
- }
- policyException.setVariables(polvariables);
- requestError.setPolicyException(policyException);
- fault.setRequestError(requestError);
-
- StringWriter sw = new StringWriter();
- m.marshal(fault, sw);
-
- response = sw.toString();
-
- } else {
-
- context = JAXBContext.newInstance(org.onap.aai.domain.restServiceException.Fault.class);
- Marshaller m = context.createMarshaller();
- m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
- m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
-
- org.onap.aai.domain.restServiceException.ObjectFactory factory = new org.onap.aai.domain.restServiceException.ObjectFactory();
- org.onap.aai.domain.restServiceException.Fault fault = factory.createFault();
- org.onap.aai.domain.restServiceException.Fault.RequestError requestError = factory.createFaultRequestError();
- org.onap.aai.domain.restServiceException.Fault.RequestError.ServiceException serviceException = factory.createFaultRequestErrorServiceException();
- org.onap.aai.domain.restServiceException.Fault.RequestError.ServiceException.Variables svcvariables = factory.createFaultRequestErrorServiceExceptionVariables();
- serviceException.setMessageId("SVC" + eo.getRESTErrorCode());
- serviceException.setText(text.toString());
- for (int i=0;i<variables.size();i++)
- {
- svcvariables.getVariable().add(variables.get(i));
- }
- serviceException.setVariables(svcvariables);
- requestError.setServiceException(serviceException);
- fault.setRequestError(requestError);
-
- StringWriter sw = new StringWriter();
- m.marshal(fault, sw);
-
- response = sw.toString();
-
- }
- } catch (Exception ex) {
- LOGGER.error("We were unable to create a rest exception to return on an API because of a parsing error " + ex.getMessage());
- }
- }
- else {
- try {
- if(eo.getCategory().equals("1")) {
- org.onap.aai.domain.restPolicyException.RESTResponse restresp = new org.onap.aai.domain.restPolicyException.RESTResponse();
- org.onap.aai.domain.restPolicyException.RequestError reqerr = new org.onap.aai.domain.restPolicyException.RequestError();
- org.onap.aai.domain.restPolicyException.PolicyException polexc = new org.onap.aai.domain.restPolicyException.PolicyException();
- polexc.setMessageId("POL" + eo.getRESTErrorCode());
- polexc.setText(text.toString());
- polexc.setVariables(variables);
- reqerr.setPolicyException(polexc);
- restresp.setRequestError(reqerr);
- response = (MapperUtil.writeAsJSONString((Object) restresp));
-
- } else {
- org.onap.aai.domain.restServiceException.RESTResponse restresp = new org.onap.aai.domain.restServiceException.RESTResponse();
- org.onap.aai.domain.restServiceException.RequestError reqerr = new org.onap.aai.domain.restServiceException.RequestError();
- org.onap.aai.domain.restServiceException.ServiceException svcexc = new org.onap.aai.domain.restServiceException.ServiceException();
- svcexc.setMessageId("SVC" + eo.getRESTErrorCode());
- svcexc.setText(text.toString());
- svcexc.setVariables(variables);
- reqerr.setServiceException(svcexc);
- restresp.setRequestError(reqerr);
- response = (MapperUtil.writeAsJSONString((Object) restresp));
- }
- } catch (AAIException ex) {
- LOGGER.error("We were unable to create a rest exception to return on an API because of a parsing error " + ex.getMessage());
- }
- }
- }
-
-
- return response;
- }
-
- /**
- * Gets the RESTAPI error response with logging.
- *
- * @param acceptHeadersOrig the accept headers orig
- * @param are the are
- * @param variables the variables
- * @param logline the logline
- * @return the RESTAPI error response with logging
- * @throws ErrorObjectFormatException
- * @throws ErrorObjectNotFoundException
- * @throws IOException
- */
- public static String getRESTAPIErrorResponseWithLogging(List<MediaType> acceptHeadersOrig, AAIException are, ArrayList<String> variables) {
- String response = ErrorLogHelper.getRESTAPIErrorResponse(acceptHeadersOrig, are, variables);
-
- LOGGER.error(are.getMessage() + " " + LogFormatTools.getStackTop(are));
-
- return response;
- }
-
- /**
- * Gets the RESTAPI info response.
- *
- * @param acceptHeaders the accept headers
- * @param areList the are list
- * @return the RESTAPI info response
- * @throws ErrorObjectFormatException
- * @throws ErrorObjectNotFoundException
- * @throws IOException
- */
- public static Object getRESTAPIInfoResponse(List<MediaType> acceptHeaders, HashMap<AAIException,ArrayList<String>> areList) {
-
- Object respObj = null;
-
- org.onap.aai.domain.restResponseInfo.ObjectFactory factory = new org.onap.aai.domain.restResponseInfo.ObjectFactory();
- org.onap.aai.domain.restResponseInfo.Info info = factory.createInfo();
- org.onap.aai.domain.restResponseInfo.Info.ResponseMessages responseMessages = factory.createInfoResponseMessages();
- Iterator<Entry<AAIException, ArrayList<String>>> it = areList.entrySet().iterator();
-
- while (it.hasNext()) {
- Entry<AAIException,ArrayList<String>> pair = (Entry<AAIException, ArrayList<String>>)it.next();
- AAIException are = pair.getKey();
- ArrayList<String> variables = pair.getValue();
-
- StringBuilder text = new StringBuilder();
-
- ErrorObject eo = are.getErrorObject();
-
- int restErrorCode = Integer.parseInt(eo.getRESTErrorCode());
- ErrorObject restErrorObject;
- try {
- restErrorObject = ErrorLogHelper.getErrorObject("AAI_"+String.format("%04d", restErrorCode));
- } catch (ErrorObjectNotFoundException e) {
- restErrorObject = eo;
- }
- text.append(restErrorObject.getErrorText());
-
- // We want to always append the (msg=%n) (ec=%n+1) to the text, but have to find value of n
- // This assumes that the variables in the ArrayList, which might be more than are needed to flesh out the
- // error, are ordered based on the error string.
- int localDataIndex = StringUtils.countMatches(restErrorObject.getErrorText(), "%");
- text.append(" (msg=%").append(localDataIndex+1).append(") (rc=%").append(localDataIndex+2).append(")");
-
- if (variables == null)
- {
- variables = new ArrayList<String>();
- }
-
- if (variables.size() < localDataIndex) {
- ErrorLogHelper.logError("AAI_4011", "data missing for rest error");
- while (variables.size() < localDataIndex) {
- variables.add("null");
- }
- }
-
- // This will put the error code and error text into the right positions
- if (are.getMessage() == null) {
- variables.add(localDataIndex++, eo.getErrorText());
- }
- else {
- variables.add(localDataIndex++, eo.getErrorText() + ":" + are.getMessage());
- }
- variables.add(localDataIndex, eo.getErrorCodeString());
-
- try {
- org.onap.aai.domain.restResponseInfo.Info.ResponseMessages.ResponseMessage responseMessage = factory.createInfoResponseMessagesResponseMessage();
- org.onap.aai.domain.restResponseInfo.Info.ResponseMessages.ResponseMessage.Variables infovariables = factory.createInfoResponseMessagesResponseMessageVariables();
-
- responseMessage.setMessageId("INF" + eo.getRESTErrorCode());
- responseMessage.setText(text.toString());
- for (int i=0;i<variables.size();i++)
- {
- infovariables.getVariable().add(variables.get(i));
- }
-
- responseMessage.setVariables(infovariables);
- responseMessages.getResponseMessage().add(responseMessage);
-
- } catch (Exception ex) {
- LOGGER.error("We were unable to create a rest exception to return on an API because of a parsing error " + ex.getMessage());
- }
- }
-
- info.setResponseMessages(responseMessages);
- respObj = (Object) info;
-
- return respObj;
- }
-
-
- /**
- * Determines whether category is policy or not. If policy (1), this is a POL error, else it's a SVC error.
- * The AAIRESTException may contain a different ErrorObject than that created with the REST error key.
- * This allows lower level exception detail to be returned to the client to help troubleshoot the problem.
- * If no error object is embedded in the AAIException, one will be created using the error object from the AAIException.
- * @param are must have a restError value whose numeric value must match what should be returned in the REST API
- * @param variables optional list of variables to flesh out text in error string
- * @return appropriately formatted JSON response per the REST API spec.
- * @throws ErrorObjectFormatException
- * @throws ErrorObjectNotFoundException
- * @throws IOException
- */
- public static String getRESTAPIPolicyErrorResponseXML(AAIException are, ArrayList<String> variables) {
-
- StringBuilder text = new StringBuilder();
- String response = null;
- JAXBContext context = null;
-
- ErrorObject eo = are.getErrorObject();
-
- int restErrorCode = Integer.parseInt(eo.getRESTErrorCode());
- ErrorObject restErrorObject;
- try {
- restErrorObject = ErrorLogHelper.getErrorObject("AAI_"+restErrorCode);
- } catch (ErrorObjectNotFoundException e) {
- restErrorObject = eo;
- }
-
- text.append(restErrorObject.getErrorText());
-
- // We want to always append the (msg=%n) (ec=%n+1) to the text, but have to find value of n
- // This assumes that the variables in the ArrayList, which might be more than are needed to flesh out the
- // error, are ordered based on the error string.
- int localDataIndex = StringUtils.countMatches(restErrorObject.getErrorText(), "%");
- text.append(" (msg=%").append(localDataIndex+1).append(") (ec=%").append(localDataIndex+2).append(")");
-
- if (variables == null)
- {
- variables = new ArrayList<String>();
- }
-
- if (variables.size() < localDataIndex) {
- ErrorLogHelper.logError("AAI_4011", "data missing for rest error");
- while (variables.size() < localDataIndex) {
- variables.add("null");
- }
- }
-
- // This will put the error code and error text into the right positions
- if (are.getMessage() == null) {
- variables.add(localDataIndex++, eo.getErrorText());
- }
- else {
- variables.add(localDataIndex++, eo.getErrorText() + ":" + are.getMessage());
- }
- variables.add(localDataIndex, eo.getErrorCodeString());
-
- try {
- if(eo.getCategory().equals("1")) {
-
- context = JAXBContext.newInstance(org.onap.aai.domain.restPolicyException.Fault.class);
- Marshaller m = context.createMarshaller();
- m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
- m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
-
- org.onap.aai.domain.restPolicyException.ObjectFactory factory = new org.onap.aai.domain.restPolicyException.ObjectFactory();
- org.onap.aai.domain.restPolicyException.Fault fault = factory.createFault();
- org.onap.aai.domain.restPolicyException.Fault.RequestError requestError = factory.createFaultRequestError();
- org.onap.aai.domain.restPolicyException.Fault.RequestError.PolicyException policyException = factory.createFaultRequestErrorPolicyException();
- org.onap.aai.domain.restPolicyException.Fault.RequestError.PolicyException.Variables polvariables = factory.createFaultRequestErrorPolicyExceptionVariables();
-
- policyException.setMessageId("POL" + eo.getRESTErrorCode());
- policyException.setText(text.toString());
- for (int i=0;i<variables.size();i++)
- {
- polvariables.getVariable().add(variables.get(i));
- }
- policyException.setVariables(polvariables);
- requestError.setPolicyException(policyException);
- fault.setRequestError(requestError);
-
- StringWriter sw = new StringWriter();
- m.marshal(fault, sw);
-
- response = sw.toString();
-
- } else {
-
- context = JAXBContext.newInstance(org.onap.aai.domain.restServiceException.Fault.class);
- Marshaller m = context.createMarshaller();
- m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
- m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
-
- org.onap.aai.domain.restServiceException.ObjectFactory factory = new org.onap.aai.domain.restServiceException.ObjectFactory();
- org.onap.aai.domain.restServiceException.Fault fault = factory.createFault();
- org.onap.aai.domain.restServiceException.Fault.RequestError requestError = factory.createFaultRequestError();
- org.onap.aai.domain.restServiceException.Fault.RequestError.ServiceException serviceException = factory.createFaultRequestErrorServiceException();
- org.onap.aai.domain.restServiceException.Fault.RequestError.ServiceException.Variables svcvariables = factory.createFaultRequestErrorServiceExceptionVariables();
- serviceException.setMessageId("POL" + eo.getRESTErrorCode());
- serviceException.setText(text.toString());
- for (int i=0;i<variables.size();i++)
- {
- svcvariables.getVariable().add(variables.get(i));
- }
- serviceException.setVariables(svcvariables);
- requestError.setServiceException(serviceException);
- fault.setRequestError(requestError);
-
- StringWriter sw = new StringWriter();
- m.marshal(fault, sw);
-
- response = sw.toString();
-
- }
- } catch (Exception ex) {
- LOGGER.error("We were unable to create a rest exception to return on an API because of a parsing error "+ ex.getMessage());
- }
- return response;
- }
-
- public static void logException(AAIException e) {
- final ErrorObject errorObject = e.getErrorObject();
-
-// MDC.put("severity", errorObject.getSeverity()); //TODO Use LoggingContext.severity(int severity)
- String severityCode = errorObject.getSeverityCode(errorObject.getSeverity());
-
- if (!AAIConfig.isEmpty(severityCode)) {
- int sevCode = Integer.parseInt(severityCode);
- if (sevCode > 0 && sevCode <= 3 )
- {
- LoggingContext.severity(sevCode);
- }
- }
- String stackTrace = "";
- try {
- stackTrace = LogFormatTools.getStackTop(e);
- }
- catch (Exception a) {
- //ignore
- }
- final String errorMessage = new StringBuilder()
- .append(errorObject.getErrorText())
- .append(":")
- .append(errorObject.getRESTErrorCode())
- .append(":")
- .append(errorObject.getHTTPResponseCode())
- .append(":")
- .append(e.getMessage())
- .toString()
- .replaceAll("\\n", "^");
-
- LoggingContext.responseCode(Integer.toString(errorObject.getHTTPResponseCode().getStatusCode()));
- LoggingContext.responseDescription(errorMessage);
- LoggingContext.statusCode(StatusCode.ERROR);
-
- final String details = new StringBuilder().append(errorObject.getErrorCodeString())
- .append(" ")
- .append(stackTrace)
- .toString();
-
- if (errorObject.getSeverity().equalsIgnoreCase("WARN"))
- LOGGER.warn(details);
- else if (errorObject.getSeverity().equalsIgnoreCase("ERROR"))
- LOGGER.error(details);
- else if (errorObject.getSeverity().equalsIgnoreCase("FATAL"))
- LOGGER.error(details);
- else if (errorObject.getSeverity().equals("INFO"))
- LOGGER.info(details);
- }
-
- public static void logError(String code) {
- logError(code, "");
- }
-
- public static void logError(String code, String message) {
- logException(new AAIException(code, message));
- }
+ private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(ErrorLogHelper.class);
+ private static final HashMap<String, ErrorObject> ERROR_OBJECTS = new HashMap<String, ErrorObject>();
+
+ static {
+ try {
+ loadProperties();
+ } catch (IOException e) {
+ throw new RuntimeException("Failed to load error.properties file", e);
+ } catch (ErrorObjectFormatException e) {
+ throw new RuntimeException("Failed to parse error.properties file", e);
+ }
+ }
+
+ /**
+ * Load properties.
+ *
+ * @throws ErrorObjectFormatException
+ * @throws Exception the exception
+ */
+ public static void loadProperties() throws IOException, ErrorObjectFormatException {
+ final String filePath = AAIConstants.AAI_HOME_ETC_APP_PROPERTIES + "error.properties";
+ final InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(filePath);
+ final Properties properties = new Properties();
+
+ if (is != null) {
+ properties.load(is);
+ } else {
+ try (final FileInputStream fis = new FileInputStream(filePath)) {
+ properties.load(fis);
+ }
+ }
+
+ for (Entry<Object, Object> entry : properties.entrySet()) {
+ final String key = (String) entry.getKey();
+ final String value = (String) entry.getValue();
+ final String[] errorProperties = value.split(":");
+
+ if (errorProperties.length != 7)
+ throw new ErrorObjectFormatException();
+
+ final ErrorObject errorObject = new ErrorObject();
+
+ errorObject.setDisposition(errorProperties[0].trim());
+ errorObject.setCategory(errorProperties[1].trim());
+ errorObject.setSeverity(errorProperties[2].trim());
+ errorObject.setErrorCode(errorProperties[3].trim());
+ errorObject.setHTTPResponseCode(errorProperties[4].trim());
+ errorObject.setRESTErrorCode(errorProperties[5].trim());
+ errorObject.setErrorText(errorProperties[6].trim());
+
+ ERROR_OBJECTS.put(key, errorObject);
+ }
+ }
+
+ /**
+ * Logs a known A&AI exception (i.e. one that can be found in error.properties)
+ *
+ * @param key The key for the error in the error.properties file
+ * @throws IOException
+ * @throws ErrorObjectNotFoundException
+ * @throws ErrorObjectFormatException
+ */
+ public static ErrorObject getErrorObject(String code) throws ErrorObjectNotFoundException {
+
+ if (code == null)
+ throw new IllegalArgumentException("Key cannot be null");
+
+ final ErrorObject errorObject = ERROR_OBJECTS.get(code);
+
+ if (errorObject == null) {
+ LOGGER.warn("Unknown AAIException with code=" + code + ". Using default AAIException");
+ return ERROR_OBJECTS.get(AAIException.DEFAULT_EXCEPTION_CODE);
+ }
+
+ return errorObject;
+ }
+
+ /**
+ * Determines whether category is policy or not. If policy (1), this is a POL error, else it's a SVC error.
+ * The AAIRESTException may contain a different ErrorObject than that created with the REST error key.
+ * This allows lower level exception detail to be returned to the client to help troubleshoot the problem.
+ * If no error object is embedded in the AAIException, one will be created using the error object from the
+ * AAIException.
+ *
+ * @param are must have a restError value whose numeric value must match what should be returned in the REST API
+ * @param variables optional list of variables to flesh out text in error string
+ * @return appropriately formatted JSON response per the REST API spec.
+ * @throws ErrorObjectFormatException
+ * @throws ErrorObjectNotFoundException
+ * @throws IOException
+ * @deprecated
+ */
+ public static String getRESTAPIErrorResponse(AAIException are, ArrayList<String> variables) {
+ List<MediaType> acceptHeaders = new ArrayList<MediaType>();
+ acceptHeaders.add(MediaType.APPLICATION_JSON_TYPE);
+
+ return getRESTAPIErrorResponse(acceptHeaders, are, variables);
+ }
+
+ /**
+ * Determines whether category is policy or not. If policy (1), this is a POL error, else it's a SVC error.
+ * The AAIRESTException may contain a different ErrorObject than that created with the REST error key.
+ * This allows lower level exception detail to be returned to the client to help troubleshoot the problem.
+ * If no error object is embedded in the AAIException, one will be created using the error object from the
+ * AAIException.
+ *
+ * @param acceptHeadersOrig the accept headers orig
+ * @param are must have a restError value whose numeric value must match what should be returned in the REST API
+ * @param variables optional list of variables to flesh out text in error string
+ * @return appropriately formatted JSON response per the REST API spec.
+ * @throws ErrorObjectFormatException
+ * @throws ErrorObjectNotFoundException
+ * @throws IOException
+ */
+ public static String getRESTAPIErrorResponse(List<MediaType> acceptHeadersOrig, AAIException are,
+ ArrayList<String> variables) {
+
+ StringBuilder text = new StringBuilder();
+ String response = null;
+
+ List<MediaType> acceptHeaders = new ArrayList<MediaType>();
+ // we might have an exception but no accept header, so we'll set default to JSON
+ boolean foundValidAcceptHeader = false;
+ for (MediaType mt : acceptHeadersOrig) {
+ if (MediaType.APPLICATION_XML_TYPE.isCompatible(mt) || MediaType.APPLICATION_JSON_TYPE.isCompatible(mt)) {
+ acceptHeaders.add(mt);
+ foundValidAcceptHeader = true;
+ }
+ }
+ if (foundValidAcceptHeader == false) {
+ // override the exception, client needs to set an appropriate Accept header
+ are = new AAIException("AAI_4014");
+ acceptHeaders.add(MediaType.APPLICATION_JSON_TYPE);
+ }
+
+ final ErrorObject eo = are.getErrorObject();
+
+ int restErrorCode = Integer.parseInt(eo.getRESTErrorCode());
+
+ ErrorObject restErrorObject;
+
+ try {
+ restErrorObject = ErrorLogHelper.getErrorObject("AAI_" + restErrorCode);
+ } catch (ErrorObjectNotFoundException e) {
+ LOGGER.warn("Failed to find related error object AAI_" + restErrorCode + " for error object "
+ + eo.getErrorCode() + "; using AAI_" + restErrorCode);
+ restErrorObject = eo;
+ }
+
+ text.append(restErrorObject.getErrorText());
+
+ // We want to always append the (msg=%n) (ec=%n+1) to the text, but have to find value of n
+ // This assumes that the variables in the ArrayList, which might be more than are needed to flesh out the
+ // error, are ordered based on the error string.
+ int localDataIndex = StringUtils.countMatches(restErrorObject.getErrorText(), "%");
+ text.append(" (msg=%").append(localDataIndex + 1).append(") (ec=%").append(localDataIndex + 2).append(")");
+
+ if (variables == null) {
+ variables = new ArrayList<String>();
+ }
+
+ if (variables.size() < localDataIndex) {
+ ErrorLogHelper.logError("AAI_4011", "data missing for rest error");
+ while (variables.size() < localDataIndex) {
+ variables.add("null");
+ }
+ }
+
+ // This will put the error code and error text into the right positions
+ if (are.getMessage() == null || are.getMessage().length() == 0) {
+ variables.add(localDataIndex++, eo.getErrorText());
+ } else {
+ variables.add(localDataIndex++, eo.getErrorText() + ":" + are.getMessage());
+ }
+ variables.add(localDataIndex, eo.getErrorCodeString());
+
+ for (MediaType mediaType : acceptHeaders) {
+ if (MediaType.APPLICATION_XML_TYPE.isCompatible(mediaType)) {
+ JAXBContext context = null;
+ try {
+ if (eo.getCategory().equals("1")) {
+
+ context = JAXBContext.newInstance(org.onap.aai.domain.restPolicyException.Fault.class);
+ Marshaller m = context.createMarshaller();
+ m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
+ m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
+
+ org.onap.aai.domain.restPolicyException.ObjectFactory factory =
+ new org.onap.aai.domain.restPolicyException.ObjectFactory();
+ org.onap.aai.domain.restPolicyException.Fault fault = factory.createFault();
+ org.onap.aai.domain.restPolicyException.Fault.RequestError requestError =
+ factory.createFaultRequestError();
+ org.onap.aai.domain.restPolicyException.Fault.RequestError.PolicyException policyException =
+ factory.createFaultRequestErrorPolicyException();
+ org.onap.aai.domain.restPolicyException.Fault.RequestError.PolicyException.Variables polvariables =
+ factory.createFaultRequestErrorPolicyExceptionVariables();
+
+ policyException.setMessageId("POL" + eo.getRESTErrorCode());
+ policyException.setText(text.toString());
+ for (int i = 0; i < variables.size(); i++) {
+ polvariables.getVariable().add(variables.get(i));
+ }
+ policyException.setVariables(polvariables);
+ requestError.setPolicyException(policyException);
+ fault.setRequestError(requestError);
+
+ StringWriter sw = new StringWriter();
+ m.marshal(fault, sw);
+
+ response = sw.toString();
+
+ } else {
+
+ context = JAXBContext.newInstance(org.onap.aai.domain.restServiceException.Fault.class);
+ Marshaller m = context.createMarshaller();
+ m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
+ m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
+
+ org.onap.aai.domain.restServiceException.ObjectFactory factory =
+ new org.onap.aai.domain.restServiceException.ObjectFactory();
+ org.onap.aai.domain.restServiceException.Fault fault = factory.createFault();
+ org.onap.aai.domain.restServiceException.Fault.RequestError requestError =
+ factory.createFaultRequestError();
+ org.onap.aai.domain.restServiceException.Fault.RequestError.ServiceException serviceException =
+ factory.createFaultRequestErrorServiceException();
+ org.onap.aai.domain.restServiceException.Fault.RequestError.ServiceException.Variables svcvariables =
+ factory.createFaultRequestErrorServiceExceptionVariables();
+ serviceException.setMessageId("SVC" + eo.getRESTErrorCode());
+ serviceException.setText(text.toString());
+ for (int i = 0; i < variables.size(); i++) {
+ svcvariables.getVariable().add(variables.get(i));
+ }
+ serviceException.setVariables(svcvariables);
+ requestError.setServiceException(serviceException);
+ fault.setRequestError(requestError);
+
+ StringWriter sw = new StringWriter();
+ m.marshal(fault, sw);
+
+ response = sw.toString();
+
+ }
+ } catch (Exception ex) {
+ LOGGER.error(
+ "We were unable to create a rest exception to return on an API because of a parsing error "
+ + ex.getMessage());
+ }
+ } else {
+ try {
+ if (eo.getCategory().equals("1")) {
+ org.onap.aai.domain.restPolicyException.RESTResponse restresp =
+ new org.onap.aai.domain.restPolicyException.RESTResponse();
+ org.onap.aai.domain.restPolicyException.RequestError reqerr =
+ new org.onap.aai.domain.restPolicyException.RequestError();
+ org.onap.aai.domain.restPolicyException.PolicyException polexc =
+ new org.onap.aai.domain.restPolicyException.PolicyException();
+ polexc.setMessageId("POL" + eo.getRESTErrorCode());
+ polexc.setText(text.toString());
+ polexc.setVariables(variables);
+ reqerr.setPolicyException(polexc);
+ restresp.setRequestError(reqerr);
+ response = (MapperUtil.writeAsJSONString((Object) restresp));
+
+ } else {
+ org.onap.aai.domain.restServiceException.RESTResponse restresp =
+ new org.onap.aai.domain.restServiceException.RESTResponse();
+ org.onap.aai.domain.restServiceException.RequestError reqerr =
+ new org.onap.aai.domain.restServiceException.RequestError();
+ org.onap.aai.domain.restServiceException.ServiceException svcexc =
+ new org.onap.aai.domain.restServiceException.ServiceException();
+ svcexc.setMessageId("SVC" + eo.getRESTErrorCode());
+ svcexc.setText(text.toString());
+ svcexc.setVariables(variables);
+ reqerr.setServiceException(svcexc);
+ restresp.setRequestError(reqerr);
+ response = (MapperUtil.writeAsJSONString((Object) restresp));
+ }
+ } catch (AAIException ex) {
+ LOGGER.error(
+ "We were unable to create a rest exception to return on an API because of a parsing error "
+ + ex.getMessage());
+ }
+ }
+ }
+
+ return response;
+ }
+
+ /**
+ * Gets the RESTAPI error response with logging.
+ *
+ * @param acceptHeadersOrig the accept headers orig
+ * @param are the are
+ * @param variables the variables
+ * @param logline the logline
+ * @return the RESTAPI error response with logging
+ * @throws ErrorObjectFormatException
+ * @throws ErrorObjectNotFoundException
+ * @throws IOException
+ */
+ public static String getRESTAPIErrorResponseWithLogging(List<MediaType> acceptHeadersOrig, AAIException are,
+ ArrayList<String> variables) {
+ String response = ErrorLogHelper.getRESTAPIErrorResponse(acceptHeadersOrig, are, variables);
+
+ LOGGER.error(are.getMessage() + " " + LogFormatTools.getStackTop(are));
+
+ return response;
+ }
+
+ /**
+ * Gets the RESTAPI info response.
+ *
+ * @param acceptHeaders the accept headers
+ * @param areList the are list
+ * @return the RESTAPI info response
+ * @throws ErrorObjectFormatException
+ * @throws ErrorObjectNotFoundException
+ * @throws IOException
+ */
+ public static Object getRESTAPIInfoResponse(List<MediaType> acceptHeaders,
+ HashMap<AAIException, ArrayList<String>> areList) {
+
+ Object respObj = null;
+
+ org.onap.aai.domain.restResponseInfo.ObjectFactory factory =
+ new org.onap.aai.domain.restResponseInfo.ObjectFactory();
+ org.onap.aai.domain.restResponseInfo.Info info = factory.createInfo();
+ org.onap.aai.domain.restResponseInfo.Info.ResponseMessages responseMessages =
+ factory.createInfoResponseMessages();
+ Iterator<Entry<AAIException, ArrayList<String>>> it = areList.entrySet().iterator();
+
+ while (it.hasNext()) {
+ Entry<AAIException, ArrayList<String>> pair = (Entry<AAIException, ArrayList<String>>) it.next();
+ AAIException are = pair.getKey();
+ ArrayList<String> variables = pair.getValue();
+
+ StringBuilder text = new StringBuilder();
+
+ ErrorObject eo = are.getErrorObject();
+
+ int restErrorCode = Integer.parseInt(eo.getRESTErrorCode());
+ ErrorObject restErrorObject;
+ try {
+ restErrorObject = ErrorLogHelper.getErrorObject("AAI_" + String.format("%04d", restErrorCode));
+ } catch (ErrorObjectNotFoundException e) {
+ restErrorObject = eo;
+ }
+ text.append(restErrorObject.getErrorText());
+
+ // We want to always append the (msg=%n) (ec=%n+1) to the text, but have to find value of n
+ // This assumes that the variables in the ArrayList, which might be more than are needed to flesh out the
+ // error, are ordered based on the error string.
+ int localDataIndex = StringUtils.countMatches(restErrorObject.getErrorText(), "%");
+ text.append(" (msg=%").append(localDataIndex + 1).append(") (rc=%").append(localDataIndex + 2).append(")");
+
+ if (variables == null) {
+ variables = new ArrayList<String>();
+ }
+
+ if (variables.size() < localDataIndex) {
+ ErrorLogHelper.logError("AAI_4011", "data missing for rest error");
+ while (variables.size() < localDataIndex) {
+ variables.add("null");
+ }
+ }
+
+ // This will put the error code and error text into the right positions
+ if (are.getMessage() == null) {
+ variables.add(localDataIndex++, eo.getErrorText());
+ } else {
+ variables.add(localDataIndex++, eo.getErrorText() + ":" + are.getMessage());
+ }
+ variables.add(localDataIndex, eo.getErrorCodeString());
+
+ try {
+ org.onap.aai.domain.restResponseInfo.Info.ResponseMessages.ResponseMessage responseMessage =
+ factory.createInfoResponseMessagesResponseMessage();
+ org.onap.aai.domain.restResponseInfo.Info.ResponseMessages.ResponseMessage.Variables infovariables =
+ factory.createInfoResponseMessagesResponseMessageVariables();
+
+ responseMessage.setMessageId("INF" + eo.getRESTErrorCode());
+ responseMessage.setText(text.toString());
+ for (int i = 0; i < variables.size(); i++) {
+ infovariables.getVariable().add(variables.get(i));
+ }
+
+ responseMessage.setVariables(infovariables);
+ responseMessages.getResponseMessage().add(responseMessage);
+
+ } catch (Exception ex) {
+ LOGGER.error("We were unable to create a rest exception to return on an API because of a parsing error "
+ + ex.getMessage());
+ }
+ }
+
+ info.setResponseMessages(responseMessages);
+ respObj = (Object) info;
+
+ return respObj;
+ }
+
+ /**
+ * Determines whether category is policy or not. If policy (1), this is a POL error, else it's a SVC error.
+ * The AAIRESTException may contain a different ErrorObject than that created with the REST error key.
+ * This allows lower level exception detail to be returned to the client to help troubleshoot the problem.
+ * If no error object is embedded in the AAIException, one will be created using the error object from the
+ * AAIException.
+ *
+ * @param are must have a restError value whose numeric value must match what should be returned in the REST API
+ * @param variables optional list of variables to flesh out text in error string
+ * @return appropriately formatted JSON response per the REST API spec.
+ * @throws ErrorObjectFormatException
+ * @throws ErrorObjectNotFoundException
+ * @throws IOException
+ */
+ public static String getRESTAPIPolicyErrorResponseXML(AAIException are, ArrayList<String> variables) {
+
+ StringBuilder text = new StringBuilder();
+ String response = null;
+ JAXBContext context = null;
+
+ ErrorObject eo = are.getErrorObject();
+
+ int restErrorCode = Integer.parseInt(eo.getRESTErrorCode());
+ ErrorObject restErrorObject;
+ try {
+ restErrorObject = ErrorLogHelper.getErrorObject("AAI_" + restErrorCode);
+ } catch (ErrorObjectNotFoundException e) {
+ restErrorObject = eo;
+ }
+
+ text.append(restErrorObject.getErrorText());
+
+ // We want to always append the (msg=%n) (ec=%n+1) to the text, but have to find value of n
+ // This assumes that the variables in the ArrayList, which might be more than are needed to flesh out the
+ // error, are ordered based on the error string.
+ int localDataIndex = StringUtils.countMatches(restErrorObject.getErrorText(), "%");
+ text.append(" (msg=%").append(localDataIndex + 1).append(") (ec=%").append(localDataIndex + 2).append(")");
+
+ if (variables == null) {
+ variables = new ArrayList<String>();
+ }
+
+ if (variables.size() < localDataIndex) {
+ ErrorLogHelper.logError("AAI_4011", "data missing for rest error");
+ while (variables.size() < localDataIndex) {
+ variables.add("null");
+ }
+ }
+
+ // This will put the error code and error text into the right positions
+ if (are.getMessage() == null) {
+ variables.add(localDataIndex++, eo.getErrorText());
+ } else {
+ variables.add(localDataIndex++, eo.getErrorText() + ":" + are.getMessage());
+ }
+ variables.add(localDataIndex, eo.getErrorCodeString());
+
+ try {
+ if (eo.getCategory().equals("1")) {
+
+ context = JAXBContext.newInstance(org.onap.aai.domain.restPolicyException.Fault.class);
+ Marshaller m = context.createMarshaller();
+ m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
+ m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
+
+ org.onap.aai.domain.restPolicyException.ObjectFactory factory =
+ new org.onap.aai.domain.restPolicyException.ObjectFactory();
+ org.onap.aai.domain.restPolicyException.Fault fault = factory.createFault();
+ org.onap.aai.domain.restPolicyException.Fault.RequestError requestError =
+ factory.createFaultRequestError();
+ org.onap.aai.domain.restPolicyException.Fault.RequestError.PolicyException policyException =
+ factory.createFaultRequestErrorPolicyException();
+ org.onap.aai.domain.restPolicyException.Fault.RequestError.PolicyException.Variables polvariables =
+ factory.createFaultRequestErrorPolicyExceptionVariables();
+
+ policyException.setMessageId("POL" + eo.getRESTErrorCode());
+ policyException.setText(text.toString());
+ for (int i = 0; i < variables.size(); i++) {
+ polvariables.getVariable().add(variables.get(i));
+ }
+ policyException.setVariables(polvariables);
+ requestError.setPolicyException(policyException);
+ fault.setRequestError(requestError);
+
+ StringWriter sw = new StringWriter();
+ m.marshal(fault, sw);
+
+ response = sw.toString();
+
+ } else {
+
+ context = JAXBContext.newInstance(org.onap.aai.domain.restServiceException.Fault.class);
+ Marshaller m = context.createMarshaller();
+ m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
+ m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
+
+ org.onap.aai.domain.restServiceException.ObjectFactory factory =
+ new org.onap.aai.domain.restServiceException.ObjectFactory();
+ org.onap.aai.domain.restServiceException.Fault fault = factory.createFault();
+ org.onap.aai.domain.restServiceException.Fault.RequestError requestError =
+ factory.createFaultRequestError();
+ org.onap.aai.domain.restServiceException.Fault.RequestError.ServiceException serviceException =
+ factory.createFaultRequestErrorServiceException();
+ org.onap.aai.domain.restServiceException.Fault.RequestError.ServiceException.Variables svcvariables =
+ factory.createFaultRequestErrorServiceExceptionVariables();
+ serviceException.setMessageId("POL" + eo.getRESTErrorCode());
+ serviceException.setText(text.toString());
+ for (int i = 0; i < variables.size(); i++) {
+ svcvariables.getVariable().add(variables.get(i));
+ }
+ serviceException.setVariables(svcvariables);
+ requestError.setServiceException(serviceException);
+ fault.setRequestError(requestError);
+
+ StringWriter sw = new StringWriter();
+ m.marshal(fault, sw);
+
+ response = sw.toString();
+
+ }
+ } catch (Exception ex) {
+ LOGGER.error("We were unable to create a rest exception to return on an API because of a parsing error "
+ + ex.getMessage());
+ }
+ return response;
+ }
+
+ public static void logException(AAIException e) {
+ final ErrorObject errorObject = e.getErrorObject();
+
+ // MDC.put("severity", errorObject.getSeverity()); //TODO Use LoggingContext.severity(int severity)
+ String severityCode = errorObject.getSeverityCode(errorObject.getSeverity());
+
+ if (!AAIConfig.isEmpty(severityCode)) {
+ int sevCode = Integer.parseInt(severityCode);
+ if (sevCode > 0 && sevCode <= 3) {
+ LoggingContext.severity(sevCode);
+ }
+ }
+ String stackTrace = "";
+ try {
+ stackTrace = LogFormatTools.getStackTop(e);
+ } catch (Exception a) {
+ // ignore
+ }
+ final String errorMessage = new StringBuilder().append(errorObject.getErrorText()).append(":")
+ .append(errorObject.getRESTErrorCode()).append(":").append(errorObject.getHTTPResponseCode())
+ .append(":").append(e.getMessage()).toString().replaceAll("\\n", "^");
+
+ LoggingContext.responseCode(Integer.toString(errorObject.getHTTPResponseCode().getStatusCode()));
+ LoggingContext.responseDescription(errorMessage);
+ LoggingContext.statusCode(StatusCode.ERROR);
+
+ final String details =
+ new StringBuilder().append(errorObject.getErrorCodeString()).append(" ").append(stackTrace).toString();
+
+ if (errorObject.getSeverity().equalsIgnoreCase("WARN"))
+ LOGGER.warn(details);
+ else if (errorObject.getSeverity().equalsIgnoreCase("ERROR"))
+ LOGGER.error(details);
+ else if (errorObject.getSeverity().equalsIgnoreCase("FATAL"))
+ LOGGER.error(details);
+ else if (errorObject.getSeverity().equals("INFO"))
+ LOGGER.info(details);
+ }
+
+ public static void logError(String code) {
+ logError(code, "");
+ }
+
+ public static void logError(String code, String message) {
+ logException(new AAIException(code, message));
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/logging/ErrorObject.java b/aai-core/src/main/java/org/onap/aai/logging/ErrorObject.java
index c39b5a61..6048c18b 100644
--- a/aai-core/src/main/java/org/onap/aai/logging/ErrorObject.java
+++ b/aai-core/src/main/java/org/onap/aai/logging/ErrorObject.java
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.logging;
import javax.ws.rs.core.Response.Status;
@@ -25,325 +26,334 @@ import javax.ws.rs.core.Response.Status;
*
* Contains the definition of all error message fields to be mapped from the Error
* properties file
- *
+ *
*/
public class ErrorObject {
-
- private String disposition;
- private String category;
- private String severity;
- private Status httpResponseCode = Status.INTERNAL_SERVER_ERROR; // default
- private String restErrorCode = "3002";
- private String errorCode;
- private String errorText;
- private String details;
-
- /**
- * Instantiates a new error object.
- */
- public ErrorObject() {
- super();
- }
-
- /**
- * Creates an error object with the default HTTP Error Code (Status.INTERNAL_SERVER_ERROR)
- *
- * @param disposition the disposition
- * @param category the category
- * @param severity the severity
- * @param httpResponseCode the http response code
- * @param restErrorCode the rest error code
- * @param errorCode the error code
- * @param errorText the error text
- */
- public ErrorObject(String disposition, String category, String severity, Integer httpResponseCode, String restErrorCode, String errorCode, String errorText) {
- super();
- this.setDisposition(disposition);
- this.setCategory(category);
- this.severity = severity;
- this.setHTTPResponseCode(httpResponseCode);
- this.setRESTErrorCode(restErrorCode);
- this.setErrorCode(errorCode);
- this.setErrorText(errorText);
- }
-
- // OLD STARTS HERE
-
- /**
- * Instantiates a new error object.
- *
- * @param severity the severity
- * @param errorCode the error code
- * @param errorText the error text
- * @param disposition the disposition
- * @param category the category
- */
- public ErrorObject(String severity, String errorCode, String errorText, String disposition, String category) {
- this(severity, Status.INTERNAL_SERVER_ERROR, errorCode, errorText, disposition, category);
- }
-
- /**
- * Instantiates a new error object.
- *
- * @param severity the severity
- * @param httpResponseCode the http response code
- * @param errorCode the error code
- * @param errorText the error text
- * @param disposition the disposition
- * @param category the category
- */
- public ErrorObject(String severity, Integer httpResponseCode, String errorCode, String errorText, String disposition, String category) {
- super();
- this.severity = severity;
- this.setHTTPResponseCode(httpResponseCode);
- this.setErrorCode(errorCode);
- this.setErrorText(errorText);
- this.setDisposition(disposition);
- this.setCategory(category);
- }
-
- /**
- * Instantiates a new error object.
- *
- * @param severity the severity
- * @param httpResponseCode the http response code
- * @param errorCode the error code
- * @param errorText the error text
- * @param disposition the disposition
- * @param category the category
- */
- public ErrorObject(String severity, Status httpResponseCode, String errorCode, String errorText, String disposition, String category) {
- super();
- this.severity = severity;
- this.setHTTPResponseCode(httpResponseCode);
- this.setErrorCode(errorCode);
- this.setErrorText(errorText);
- this.setDisposition(disposition);
- this.setCategory(category);
- }
-
- /**
- * Gets the disposition.
- *
- * @return the disposition
- */
- public String getDisposition() {
- return disposition;
- }
-
- /**
- * Sets the disposition.
- *
- * @param disposition the new disposition
- */
- public void setDisposition(String disposition) {
- this.disposition = disposition;
- }
-
- /**
- * Gets the category.
- *
- * @return the category
- */
- public String getCategory() {
- return category;
- }
-
- /**
- * Sets the category.
- *
- * @param category the new category
- */
- public void setCategory(String category) {
- this.category = category;
- }
-
- /**
- * Gets the severity.
- *
- * @return the severity
- */
- public String getSeverity() {
- return severity;
- }
-
- /**
- * Sets the severity.
- *
- * @param severity the new severity
- */
- public void setSeverity(String severity) {
- this.severity = severity;
- }
-
- /**
- * Gets the error code.
- *
- * @return the error code
- */
- public String getErrorCode() {
- return errorCode;
- }
-
- /**
- * Sets the error code.
- *
- * @param errorCode the new error code
- */
- public void setErrorCode(String errorCode) {
- this.errorCode = errorCode;
- }
-
- /**
- * Gets the HTTP response code.
- *
- * @return the HTTP response code
- */
- public Status getHTTPResponseCode() {
- return httpResponseCode;
- }
-
- /**
- * Sets the HTTP response code.
- *
- * @param httpResponseCode the new HTTP response code
- */
- public void setHTTPResponseCode(Integer httpResponseCode) {
- this.httpResponseCode = Status.fromStatusCode(httpResponseCode);
- if (this.httpResponseCode == null) {
- throw new IllegalArgumentException("setHTTPResponseCode was passed an invalid Integer value, fix error.properties or your code "+httpResponseCode);
- }
- }
-
- /**
- * Sets the HTTP response code.
- *
- * @param httpResponseCode the new HTTP response code
- */
- public void setHTTPResponseCode(String httpResponseCode) {
- this.httpResponseCode = Status.fromStatusCode(Integer.valueOf(httpResponseCode));
- if (this.httpResponseCode == null) {
- throw new IllegalArgumentException("setHTTPResponseCode was passed an invalid String value, fix error.properties or your code "+httpResponseCode);
- }
- }
-
- /**
- * Sets the REST error code.
- *
- * @param restErrorCode the new REST error code
- */
- public void setRESTErrorCode(String restErrorCode) {
- this.restErrorCode = restErrorCode;
- }
-
- /**
- * Gets the REST error code.
- *
- * @return the REST error code
- */
- public String getRESTErrorCode() {
- return this.restErrorCode;
- }
-
- /**
- * Sets the HTTP response code.
- *
- * @param httpResponseCode the new HTTP response code
- */
- public void setHTTPResponseCode(Status httpResponseCode) {
- this.httpResponseCode = httpResponseCode;
- if (this.httpResponseCode == null) {
- throw new IllegalArgumentException("setHTTPResponseCode was passed an invalid String value, fix error.properties or your code "+httpResponseCode);
- }
- }
-
- /**
- * Gets the error text.
- *
- * @return the error text
- */
- public String getErrorText() {
- return errorText;
- }
-
- /**
- * Sets the error text.
- *
- * @param errorText the new error text
- */
- public void setErrorText(String errorText) {
- this.errorText = errorText;
- }
-
- /**
- * Gets the details.
- *
- * @return the details
- */
- public String getDetails() {
- return details;
- }
-
- /**
- * Sets the details.
- *
- * @param details the new details
- */
- public void setDetails(String details) {
- this.details = details == null ? "" : details;
- }
-
- /**
- * Gets the error code string. This is also the string
- * configured in Nagios to alert on
- *
- * @return the error code string
- */
- // Get the X.Y.Z representation of the error code
- public String getErrorCodeString() {
- String prefix = null;
- switch (disposition) {
- default:
- prefix = "";
- break;
- case "5":
- prefix = "ERR.";
- break;
- }
- return prefix + disposition + "." + category + "." + errorCode;
- }
-
- /**
- * Gets the severity Code. This is also the string
- * configured in Nagios to alert on
- *
- * @return the severity
- */
- // Get the numerical value of severity
- public String getSeverityCode(String severity) {
- String severityCode = "";
- switch (severity) {
- case "WARN":
- severityCode = "1";
- break;
- case "ERROR":
- severityCode = "2";
- break;
- case "FATAL":
- severityCode = "3";
- break;
- }
- return severityCode;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public String toString() {
- return "ErrorObject [errorCode="+ errorCode + ", errorText=" + errorText
- + ", restErrorCode=" + restErrorCode + ", httpResponseCode="+ httpResponseCode
- + ", severity=" + severity + ", disposition=" + disposition + ", category=" + category +"]";
- }
-
+
+ private String disposition;
+ private String category;
+ private String severity;
+ private Status httpResponseCode = Status.INTERNAL_SERVER_ERROR; // default
+ private String restErrorCode = "3002";
+ private String errorCode;
+ private String errorText;
+ private String details;
+
+ /**
+ * Instantiates a new error object.
+ */
+ public ErrorObject() {
+ super();
+ }
+
+ /**
+ * Creates an error object with the default HTTP Error Code (Status.INTERNAL_SERVER_ERROR)
+ *
+ * @param disposition the disposition
+ * @param category the category
+ * @param severity the severity
+ * @param httpResponseCode the http response code
+ * @param restErrorCode the rest error code
+ * @param errorCode the error code
+ * @param errorText the error text
+ */
+ public ErrorObject(String disposition, String category, String severity, Integer httpResponseCode,
+ String restErrorCode, String errorCode, String errorText) {
+ super();
+ this.setDisposition(disposition);
+ this.setCategory(category);
+ this.severity = severity;
+ this.setHTTPResponseCode(httpResponseCode);
+ this.setRESTErrorCode(restErrorCode);
+ this.setErrorCode(errorCode);
+ this.setErrorText(errorText);
+ }
+
+ // OLD STARTS HERE
+
+ /**
+ * Instantiates a new error object.
+ *
+ * @param severity the severity
+ * @param errorCode the error code
+ * @param errorText the error text
+ * @param disposition the disposition
+ * @param category the category
+ */
+ public ErrorObject(String severity, String errorCode, String errorText, String disposition, String category) {
+ this(severity, Status.INTERNAL_SERVER_ERROR, errorCode, errorText, disposition, category);
+ }
+
+ /**
+ * Instantiates a new error object.
+ *
+ * @param severity the severity
+ * @param httpResponseCode the http response code
+ * @param errorCode the error code
+ * @param errorText the error text
+ * @param disposition the disposition
+ * @param category the category
+ */
+ public ErrorObject(String severity, Integer httpResponseCode, String errorCode, String errorText,
+ String disposition, String category) {
+ super();
+ this.severity = severity;
+ this.setHTTPResponseCode(httpResponseCode);
+ this.setErrorCode(errorCode);
+ this.setErrorText(errorText);
+ this.setDisposition(disposition);
+ this.setCategory(category);
+ }
+
+ /**
+ * Instantiates a new error object.
+ *
+ * @param severity the severity
+ * @param httpResponseCode the http response code
+ * @param errorCode the error code
+ * @param errorText the error text
+ * @param disposition the disposition
+ * @param category the category
+ */
+ public ErrorObject(String severity, Status httpResponseCode, String errorCode, String errorText, String disposition,
+ String category) {
+ super();
+ this.severity = severity;
+ this.setHTTPResponseCode(httpResponseCode);
+ this.setErrorCode(errorCode);
+ this.setErrorText(errorText);
+ this.setDisposition(disposition);
+ this.setCategory(category);
+ }
+
+ /**
+ * Gets the disposition.
+ *
+ * @return the disposition
+ */
+ public String getDisposition() {
+ return disposition;
+ }
+
+ /**
+ * Sets the disposition.
+ *
+ * @param disposition the new disposition
+ */
+ public void setDisposition(String disposition) {
+ this.disposition = disposition;
+ }
+
+ /**
+ * Gets the category.
+ *
+ * @return the category
+ */
+ public String getCategory() {
+ return category;
+ }
+
+ /**
+ * Sets the category.
+ *
+ * @param category the new category
+ */
+ public void setCategory(String category) {
+ this.category = category;
+ }
+
+ /**
+ * Gets the severity.
+ *
+ * @return the severity
+ */
+ public String getSeverity() {
+ return severity;
+ }
+
+ /**
+ * Sets the severity.
+ *
+ * @param severity the new severity
+ */
+ public void setSeverity(String severity) {
+ this.severity = severity;
+ }
+
+ /**
+ * Gets the error code.
+ *
+ * @return the error code
+ */
+ public String getErrorCode() {
+ return errorCode;
+ }
+
+ /**
+ * Sets the error code.
+ *
+ * @param errorCode the new error code
+ */
+ public void setErrorCode(String errorCode) {
+ this.errorCode = errorCode;
+ }
+
+ /**
+ * Gets the HTTP response code.
+ *
+ * @return the HTTP response code
+ */
+ public Status getHTTPResponseCode() {
+ return httpResponseCode;
+ }
+
+ /**
+ * Sets the HTTP response code.
+ *
+ * @param httpResponseCode the new HTTP response code
+ */
+ public void setHTTPResponseCode(Integer httpResponseCode) {
+ this.httpResponseCode = Status.fromStatusCode(httpResponseCode);
+ if (this.httpResponseCode == null) {
+ throw new IllegalArgumentException(
+ "setHTTPResponseCode was passed an invalid Integer value, fix error.properties or your code "
+ + httpResponseCode);
+ }
+ }
+
+ /**
+ * Sets the HTTP response code.
+ *
+ * @param httpResponseCode the new HTTP response code
+ */
+ public void setHTTPResponseCode(String httpResponseCode) {
+ this.httpResponseCode = Status.fromStatusCode(Integer.valueOf(httpResponseCode));
+ if (this.httpResponseCode == null) {
+ throw new IllegalArgumentException(
+ "setHTTPResponseCode was passed an invalid String value, fix error.properties or your code "
+ + httpResponseCode);
+ }
+ }
+
+ /**
+ * Sets the REST error code.
+ *
+ * @param restErrorCode the new REST error code
+ */
+ public void setRESTErrorCode(String restErrorCode) {
+ this.restErrorCode = restErrorCode;
+ }
+
+ /**
+ * Gets the REST error code.
+ *
+ * @return the REST error code
+ */
+ public String getRESTErrorCode() {
+ return this.restErrorCode;
+ }
+
+ /**
+ * Sets the HTTP response code.
+ *
+ * @param httpResponseCode the new HTTP response code
+ */
+ public void setHTTPResponseCode(Status httpResponseCode) {
+ this.httpResponseCode = httpResponseCode;
+ if (this.httpResponseCode == null) {
+ throw new IllegalArgumentException(
+ "setHTTPResponseCode was passed an invalid String value, fix error.properties or your code "
+ + httpResponseCode);
+ }
+ }
+
+ /**
+ * Gets the error text.
+ *
+ * @return the error text
+ */
+ public String getErrorText() {
+ return errorText;
+ }
+
+ /**
+ * Sets the error text.
+ *
+ * @param errorText the new error text
+ */
+ public void setErrorText(String errorText) {
+ this.errorText = errorText;
+ }
+
+ /**
+ * Gets the details.
+ *
+ * @return the details
+ */
+ public String getDetails() {
+ return details;
+ }
+
+ /**
+ * Sets the details.
+ *
+ * @param details the new details
+ */
+ public void setDetails(String details) {
+ this.details = details == null ? "" : details;
+ }
+
+ /**
+ * Gets the error code string. This is also the string
+ * configured in Nagios to alert on
+ *
+ * @return the error code string
+ */
+ // Get the X.Y.Z representation of the error code
+ public String getErrorCodeString() {
+ String prefix = null;
+ switch (disposition) {
+ default:
+ prefix = "";
+ break;
+ case "5":
+ prefix = "ERR.";
+ break;
+ }
+ return prefix + disposition + "." + category + "." + errorCode;
+ }
+
+ /**
+ * Gets the severity Code. This is also the string
+ * configured in Nagios to alert on
+ *
+ * @return the severity
+ */
+ // Get the numerical value of severity
+ public String getSeverityCode(String severity) {
+ String severityCode = "";
+ switch (severity) {
+ case "WARN":
+ severityCode = "1";
+ break;
+ case "ERROR":
+ severityCode = "2";
+ break;
+ case "FATAL":
+ severityCode = "3";
+ break;
+ }
+ return severityCode;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public String toString() {
+ return "ErrorObject [errorCode=" + errorCode + ", errorText=" + errorText + ", restErrorCode=" + restErrorCode
+ + ", httpResponseCode=" + httpResponseCode + ", severity=" + severity + ", disposition=" + disposition
+ + ", category=" + category + "]";
+ }
+
}
diff --git a/aai-core/src/main/java/org/onap/aai/logging/ErrorObjectFormatException.java b/aai-core/src/main/java/org/onap/aai/logging/ErrorObjectFormatException.java
index f9a640b5..8d53f2e3 100644
--- a/aai-core/src/main/java/org/onap/aai/logging/ErrorObjectFormatException.java
+++ b/aai-core/src/main/java/org/onap/aai/logging/ErrorObjectFormatException.java
@@ -17,13 +17,14 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.logging;
public class ErrorObjectFormatException extends Exception {
- private static final long serialVersionUID = 3732705544448553685L;
+ private static final long serialVersionUID = 3732705544448553685L;
- public ErrorObjectFormatException() {
- super();
- }
+ public ErrorObjectFormatException() {
+ super();
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/logging/ErrorObjectNotFoundException.java b/aai-core/src/main/java/org/onap/aai/logging/ErrorObjectNotFoundException.java
index b279d6b8..3daf7137 100644
--- a/aai-core/src/main/java/org/onap/aai/logging/ErrorObjectNotFoundException.java
+++ b/aai-core/src/main/java/org/onap/aai/logging/ErrorObjectNotFoundException.java
@@ -17,34 +17,35 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.logging;
public class ErrorObjectNotFoundException extends Exception {
- private static final long serialVersionUID = 4115316781400786740L;
-
- public ErrorObjectNotFoundException() {
- // TODO Auto-generated constructor stub
- }
-
- public ErrorObjectNotFoundException(String message) {
- super(message);
- // TODO Auto-generated constructor stub
- }
-
- public ErrorObjectNotFoundException(Throwable cause) {
- super(cause);
- // TODO Auto-generated constructor stub
- }
-
- public ErrorObjectNotFoundException(String message, Throwable cause) {
- super(message, cause);
- // TODO Auto-generated constructor stub
- }
-
- public ErrorObjectNotFoundException(String message, Throwable cause, boolean enableSuppression,
- boolean writableStackTrace) {
- super(message, cause, enableSuppression, writableStackTrace);
- // TODO Auto-generated constructor stub
- }
+ private static final long serialVersionUID = 4115316781400786740L;
+
+ public ErrorObjectNotFoundException() {
+ // TODO Auto-generated constructor stub
+ }
+
+ public ErrorObjectNotFoundException(String message) {
+ super(message);
+ // TODO Auto-generated constructor stub
+ }
+
+ public ErrorObjectNotFoundException(Throwable cause) {
+ super(cause);
+ // TODO Auto-generated constructor stub
+ }
+
+ public ErrorObjectNotFoundException(String message, Throwable cause) {
+ super(message, cause);
+ // TODO Auto-generated constructor stub
+ }
+
+ public ErrorObjectNotFoundException(String message, Throwable cause, boolean enableSuppression,
+ boolean writableStackTrace) {
+ super(message, cause, enableSuppression, writableStackTrace);
+ // TODO Auto-generated constructor stub
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/logging/LogFormatTools.java b/aai-core/src/main/java/org/onap/aai/logging/LogFormatTools.java
index d91ba19d..804801f1 100644
--- a/aai-core/src/main/java/org/onap/aai/logging/LogFormatTools.java
+++ b/aai-core/src/main/java/org/onap/aai/logging/LogFormatTools.java
@@ -17,107 +17,107 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.logging;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
+
+import org.apache.commons.lang.exception.ExceptionUtils;
+import org.onap.aai.exceptions.AAIException;
import org.onap.aai.util.AAIConfig;
import org.onap.aai.util.AAIConstants;
-import org.onap.aai.exceptions.AAIException;
-import org.apache.commons.lang.exception.ExceptionUtils;
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);
+ 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());
+ }
- public static String getCurrentDateTime() {
- return DTF.format(ZonedDateTime.now());
- }
+ public static String toDate(long timestamp) {
+ return DTF.format(Instant.ofEpochMilli(timestamp));
+ }
- public static String toDate(long timestamp) {
- return DTF.format(Instant.ofEpochMilli(timestamp));
- }
+ public static long toTimestamp(String date) {
+ return ZonedDateTime.parse(date, DTF).toInstant().toEpochMilli();
+ }
- public static long toTimestamp(String date) {
- return ZonedDateTime.parse(date, DTF).toInstant().toEpochMilli();
- }
- /**
- * Gets the stack top.
- *
- * @param e the e
- * @return the stack top
- * @throws NumberFormatException the number format exception
- * @throws AAIException the AAI exception
- */
- public static String getStackTop(Throwable e) {
- // StringBuilder is more efficient than StringBuffer and should only
- // StringBuffer is only supposed to be used if multiple threads are modifying
- // the same object and since this object is created locally not necessary
- StringBuilder stackMessage = new StringBuilder();
- int maxStackTraceEntries = 10;
- try {
- maxStackTraceEntries = Integer.valueOf(AAIConfig.get(AAIConstants.LOGGING_MAX_STACK_TRACE_ENTRIES));
- }
- catch (AAIException a) {
- //ignore, use default
- }
- catch (NumberFormatException n) {
- //ignore, use default
- }
- if (e != null) {
- Throwable rootCause = ExceptionUtils.getRootCause(e);
- if (rootCause != null) {
- stackMessage.append("root cause=" + ExceptionUtils.getRootCause(e));
- StackTraceElement[] elements = rootCause.getStackTrace();
- int i = 0;
- for (StackTraceElement element : elements) {
- if (i < maxStackTraceEntries) {
- stackMessage.append(" ClassName- ");
- stackMessage.append(element.getClassName());
- stackMessage.append(" :LineNumber- ");
- stackMessage.append(element.getLineNumber());
- stackMessage.append(" :MethodName- ");
- stackMessage.append(element.getMethodName());
- }
- i++;
- }
- } else if (e.getCause() != null) {
- stackMessage.append("cause=" + e.getCause());
- StackTraceElement[] elements = e.getCause().getStackTrace();
- int i = 0;
- for (StackTraceElement element : elements) {
- if (i < maxStackTraceEntries) {
- stackMessage.append(" ClassName- ");
- stackMessage.append(element.getClassName());
- stackMessage.append(" :LineNumber- ");
- stackMessage.append(element.getLineNumber());
- stackMessage.append(" :MethodName- ");
- stackMessage.append(element.getMethodName());
- }
- i++;
- }
- } else if (e.getStackTrace() != null) {
- stackMessage.append("ex=" + e.toString());
- StackTraceElement[] elements = e.getStackTrace();
- int i = 0;
- for (StackTraceElement element : elements) {
- if (i < maxStackTraceEntries) {
- stackMessage.append(" ClassName- ");
- stackMessage.append(element.getClassName());
- stackMessage.append(" :LineNumber- ");
- stackMessage.append(element.getLineNumber());
- stackMessage.append(" :MethodName- ");
- stackMessage.append(element.getMethodName());
- }
- i++;
- }
- }
- }
- return stackMessage.toString();
- }
+ /**
+ * Gets the stack top.
+ *
+ * @param e the e
+ * @return the stack top
+ * @throws NumberFormatException the number format exception
+ * @throws AAIException the AAI exception
+ */
+ public static String getStackTop(Throwable e) {
+ // StringBuilder is more efficient than StringBuffer and should only
+ // StringBuffer is only supposed to be used if multiple threads are modifying
+ // the same object and since this object is created locally not necessary
+ StringBuilder stackMessage = new StringBuilder();
+ int maxStackTraceEntries = 10;
+ try {
+ maxStackTraceEntries = Integer.valueOf(AAIConfig.get(AAIConstants.LOGGING_MAX_STACK_TRACE_ENTRIES));
+ } catch (AAIException a) {
+ // ignore, use default
+ } catch (NumberFormatException n) {
+ // ignore, use default
+ }
+ if (e != null) {
+ Throwable rootCause = ExceptionUtils.getRootCause(e);
+ if (rootCause != null) {
+ stackMessage.append("root cause=" + ExceptionUtils.getRootCause(e));
+ StackTraceElement[] elements = rootCause.getStackTrace();
+ int i = 0;
+ for (StackTraceElement element : elements) {
+ if (i < maxStackTraceEntries) {
+ stackMessage.append(" ClassName- ");
+ stackMessage.append(element.getClassName());
+ stackMessage.append(" :LineNumber- ");
+ stackMessage.append(element.getLineNumber());
+ stackMessage.append(" :MethodName- ");
+ stackMessage.append(element.getMethodName());
+ }
+ i++;
+ }
+ } else if (e.getCause() != null) {
+ stackMessage.append("cause=" + e.getCause());
+ StackTraceElement[] elements = e.getCause().getStackTrace();
+ int i = 0;
+ for (StackTraceElement element : elements) {
+ if (i < maxStackTraceEntries) {
+ stackMessage.append(" ClassName- ");
+ stackMessage.append(element.getClassName());
+ stackMessage.append(" :LineNumber- ");
+ stackMessage.append(element.getLineNumber());
+ stackMessage.append(" :MethodName- ");
+ stackMessage.append(element.getMethodName());
+ }
+ i++;
+ }
+ } else if (e.getStackTrace() != null) {
+ stackMessage.append("ex=" + e.toString());
+ StackTraceElement[] elements = e.getStackTrace();
+ int i = 0;
+ for (StackTraceElement element : elements) {
+ if (i < maxStackTraceEntries) {
+ stackMessage.append(" ClassName- ");
+ stackMessage.append(element.getClassName());
+ stackMessage.append(" :LineNumber- ");
+ stackMessage.append(element.getLineNumber());
+ stackMessage.append(" :MethodName- ");
+ stackMessage.append(element.getMethodName());
+ }
+ i++;
+ }
+ }
+ }
+ return stackMessage.toString();
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/logging/LoggingContext.java b/aai-core/src/main/java/org/onap/aai/logging/LoggingContext.java
index 50af1c68..f79025a2 100644
--- a/aai-core/src/main/java/org/onap/aai/logging/LoggingContext.java
+++ b/aai-core/src/main/java/org/onap/aai/logging/LoggingContext.java
@@ -17,8 +17,12 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.logging;
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
+
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
@@ -33,394 +37,384 @@ import org.json.JSONObject;
import org.onap.aai.exceptions.AAIException;
import org.slf4j.MDC;
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
-
public class LoggingContext {
- public enum StatusCode {
- COMPLETE,
- ERROR
- }
-
- private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(LoggingContext.class);
-
- private static final String PREVIOUS_CONTEXTS_KEY = "_PREVIOUS_CONTEXTS";
-
- //Response codes from Logging Guidelines
- public static final String SUCCESS = "0";
- public static final String PERMISSION_ERROR = "100";
- public static final String AVAILABILITY_TIMEOUT_ERROR = "200";
- public static final String DATA_ERROR = "300";
- public static final String SCHEMA_ERROR = "400";
- public static final String BUSINESS_PROCESS_ERROR = "500";
- public static final String UNKNOWN_ERROR = "900";
-
- public static final Map<String, String> responseMap = new HashMap();
-
+ public enum StatusCode {
+ COMPLETE, ERROR
+ }
+
+ private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(LoggingContext.class);
+
+ private static final String PREVIOUS_CONTEXTS_KEY = "_PREVIOUS_CONTEXTS";
+
+ // Response codes from Logging Guidelines
+ public static final String SUCCESS = "0";
+ public static final String PERMISSION_ERROR = "100";
+ public static final String AVAILABILITY_TIMEOUT_ERROR = "200";
+ public static final String DATA_ERROR = "300";
+ public static final String SCHEMA_ERROR = "400";
+ public static final String BUSINESS_PROCESS_ERROR = "500";
+ public static final String UNKNOWN_ERROR = "900";
+
+ public static final Map<String, String> responseMap = new HashMap();
+
static {
responseMap.put(SUCCESS, "Success");
responseMap.put(UNKNOWN_ERROR, "Unknown error");
}
- // Specific Log Event Fields
- public static enum LoggingField {
- START_TIME("startTime"),
- REQUEST_ID("requestId"),
- SERVICE_INSTANCE_ID("serviceInstanceId"),
- SERVER_NAME("serverName"),
- SERVICE_NAME("serviceName"),
- PARTNER_NAME("partnerName"),
- STATUS_CODE("statusCode"),
- RESPONSE_CODE("responseCode"),
- RESPONSE_DESCRIPTION("responseDescription"),
- INSTANCE_UUID("instanceUUID"),
- SEVERITY("severity"),
- SERVER_IP_ADDRESS("serverIpAddress"),
- ELAPSED_TIME("elapsedTime"),
- SERVER("server"),
- CLIENT_IP_ADDRESS("clientIpAddress"),
- UNUSED("unused"),
- PROCESS_KEY("processKey"),
- CUSTOM_FIELD_1("customField1"),
- CUSTOM_FIELD_2("customField2"),
- CUSTOM_FIELD_3("customField3"),
- CUSTOM_FIELD_4("customField4"),
-
- // Specific Metric Log Event Fields
- TARGET_ENTITY("targetEntity"),
- TARGET_SERVICE_NAME("targetServiceName"),
- //A&AI Specific Log Event Fields
- COMPONENT("component"),
- STOP_WATCH_START("stopWatchStart");
-
- private final String text;
-
- private LoggingField(final String text) {
- this.text = text;
- }
-
- public String toString() {
- return text;
- }
- }
-
-
- public static void init() {
- LoggingContext.clear();
- LoggingContext.startTime();
- LoggingContext.server();
- LoggingContext.serverIpAddress();
- }
-
- public static void startTime() {
- MDC.put(LoggingField.START_TIME.toString(), LogFormatTools.getCurrentDateTime());
- }
-
- public static UUID requestId() {
- final String sUuid = MDC.get(LoggingField.REQUEST_ID.toString());
-
- if (sUuid == null) return null;
-
- return UUID.fromString(sUuid);
- }
-
- public static void requestId(UUID requestId) {
- MDC.put(LoggingField.REQUEST_ID.toString(), requestId.toString());
- }
-
- public static void requestId(String requestId) {
- try {
- if (requestId.contains(":")) {
- String[] uuidParts = requestId.split(":");
- requestId = uuidParts[0];
- }
- MDC.put(LoggingField.REQUEST_ID.toString(), UUID.fromString(requestId).toString());
- } catch (IllegalArgumentException e) {
- final UUID generatedRequestUuid = UUID.randomUUID();
- MDC.put(LoggingField.REQUEST_ID.toString(), generatedRequestUuid.toString());
- LoggingContext.save();
- // set response code to 0 since we don't know what the outcome of this request is yet
- String responseCode = LoggingContext.DATA_ERROR;
- LoggingContext.responseCode(responseCode);
- LoggingContext.responseDescription("Unable to use UUID " + requestId + " (Not formatted properly) ");
- LoggingContext.statusCode(StatusCode.ERROR);
-
- LOGGER.warn("Using generated UUID=" + generatedRequestUuid);
- LoggingContext.restore();
-
- }
- }
-
- public static void serviceInstanceId(String serviceInstanceId) {
- MDC.put(LoggingField.SERVICE_INSTANCE_ID.toString(), serviceInstanceId);
- }
-
- public static void serverName(String serverName) {
- MDC.put(LoggingField.SERVER_NAME.toString(), serverName);
- }
-
- public static void serviceName(String serviceName) {
- MDC.put(LoggingField.SERVICE_NAME.toString(), serviceName);
- }
-
- public static void partnerName(String partnerName) {
- MDC.put(LoggingField.PARTNER_NAME.toString(), partnerName);
- }
-
- public static void statusCode(StatusCode statusCode) {
- MDC.put(LoggingField.STATUS_CODE.toString(), statusCode.toString());
- }
-
- public static String responseCode() {
- return (String) MDC.get(LoggingField.RESPONSE_CODE.toString());
- }
-
- public static void responseCode(String responseCode) {
- MDC.put(LoggingField.RESPONSE_CODE.toString(), responseCode);
- }
-
- public static void responseDescription(String responseDescription) {
- MDC.put(LoggingField.RESPONSE_DESCRIPTION.toString(), responseDescription);
- }
-
- public static Object instanceUuid() {
- return UUID.fromString(MDC.get(LoggingField.INSTANCE_UUID.toString()));
- }
-
- public static void instanceUuid(UUID instanceUuid) {
- MDC.put(LoggingField.INSTANCE_UUID.toString(), instanceUuid.toString());
- }
-
- public static void severity(int severity) {
- MDC.put(LoggingField.SEVERITY.toString(), String.valueOf(severity));
- }
-
- public static void successStatusFields() {
- responseCode(SUCCESS);
- statusCode(StatusCode.COMPLETE);
- responseDescription("Success");
- }
- private static void serverIpAddress() {
- try {
- MDC.put(LoggingField.SERVER_IP_ADDRESS.toString(), InetAddress.getLocalHost().getHostAddress());
- } catch (UnknownHostException e) {
- LOGGER.warn("Unable to resolve server IP address - will not be displayed in logged events");
- }
- }
-
- public static void elapsedTime(long elapsedTime, TimeUnit timeUnit) {
- MDC.put(LoggingField.ELAPSED_TIME.toString(), String.valueOf(TimeUnit.MILLISECONDS.convert(elapsedTime, timeUnit)));
- }
-
- private static void server() {
- try {
- MDC.put(LoggingField.SERVER.toString(), InetAddress.getLocalHost().getCanonicalHostName());
- } catch (UnknownHostException e) {
- LOGGER.warn("Unable to resolve server IP address - hostname will not be displayed in logged events");
- }
- }
-
- public static void clientIpAddress(InetAddress clientIpAddress) {
- MDC.put(LoggingField.CLIENT_IP_ADDRESS.toString(), clientIpAddress.getHostAddress());
- }
-
- public static void clientIpAddress(String clientIpAddress) {
- try {
- MDC.put(LoggingField.CLIENT_IP_ADDRESS.toString(), InetAddress.getByName(clientIpAddress).getHostAddress());
- } catch (UnknownHostException e) {
- //Ignore, will not be thrown since InetAddress.getByName(String) only
- //checks the validity of the passed in string
- }
- }
-
- public static void unused(String unused) {
- LOGGER.warn("Using field '" + LoggingField.UNUSED + "' (seems like this should go unused...)");
- MDC.put(LoggingField.UNUSED.toString(), unused);
- }
-
- public static void processKey(String processKey) {
- MDC.put(LoggingField.PROCESS_KEY.toString(), processKey);
- }
-
- public static String customField1() {
- return MDC.get(LoggingField.CUSTOM_FIELD_1.toString());
- }
-
- public static void customField1(String customField1) {
- MDC.put(LoggingField.CUSTOM_FIELD_1.toString(), customField1);
- }
-
- public static void customField2(String customField2) {
- MDC.put(LoggingField.CUSTOM_FIELD_2.toString(), customField2);
- }
-
- public static void customField3(String customField3) {
- MDC.put(LoggingField.CUSTOM_FIELD_3.toString(), customField3);
- }
-
- public static void customField4(String customField4) {
- MDC.put(LoggingField.CUSTOM_FIELD_4.toString(), customField4);
- }
-
- public static void component(String component) {
- MDC.put(LoggingField.COMPONENT.toString(), component);
- }
-
- public static void targetEntity(String targetEntity) {
- MDC.put(LoggingField.TARGET_ENTITY.toString(), targetEntity);
- }
-
- public static void targetServiceName(String targetServiceName) {
- MDC.put(LoggingField.TARGET_SERVICE_NAME.toString(), targetServiceName);
- }
-
- public static boolean isStopWatchStarted() {
- final String rawStopWatchStart = MDC.get(LoggingField.STOP_WATCH_START.toString());
- if (rawStopWatchStart == null) {
- return false;
- }
- return true;
- }
- public static void stopWatchStart() {
- MDC.put(LoggingField.STOP_WATCH_START.toString(), String.valueOf(System.nanoTime()));
- }
-
- public static double stopWatchStop() {
- final long stopWatchEnd = System.nanoTime();
- final String rawStopWatchStart = MDC.get(LoggingField.STOP_WATCH_START.toString());
-
- if (rawStopWatchStart == null) throw new StopWatchNotStartedException();
-
- final Long stopWatchStart = Long.valueOf(rawStopWatchStart);
-
- MDC.remove(LoggingField.STOP_WATCH_START.toString());
-
- final double elapsedTimeMillis = (stopWatchEnd - stopWatchStart) / 1000.0 / 1000.0;
-
- LoggingContext.elapsedTime((long) elapsedTimeMillis, TimeUnit.MILLISECONDS);
-
- return elapsedTimeMillis;
- }
-
- public static void put(String key, String value) {
- MDC.put(key, value);
- }
-
- public static void clear() {
- MDC.clear();
- }
-
- public static void remove(String key) {
- MDC.remove(key);
- }
-
- public static void save() {
- final JSONObject context = new JSONObject();
-
- for (LoggingField field : LoggingField.values()) {
- if (field == LoggingField.ELAPSED_TIME) continue;
-
- try {
- context.put(field.toString(), MDC.get(field.toString()));
- } catch (JSONException e) {
- //Ignore - only occurs when the key is null (which can't happen)
- // or the value is invalid (everything is converted to a string
- // before it get put() to the MDC)
- }
- }
-
- final String rawJsonArray = MDC.get(PREVIOUS_CONTEXTS_KEY);
-
- if (rawJsonArray == null) {
- final JSONArray stack = new JSONArray()
- .put(context);
-
- MDC.put(PREVIOUS_CONTEXTS_KEY, stack.toString());
- } else {
- try {
- final JSONArray stack = new JSONArray(rawJsonArray)
- .put(context);
-
- MDC.put(PREVIOUS_CONTEXTS_KEY, stack.toString());
- } catch (JSONException e) {
- //Ignore
- }
- }
- }
-
- public static void restore() {
-
- final String rawPreviousContexts = MDC.get(PREVIOUS_CONTEXTS_KEY);
-
- if (rawPreviousContexts == null) {
- throw new LoggingContextNotExistsException();
- }
-
- try {
- final JSONArray previousContexts = new JSONArray(rawPreviousContexts);
- final JSONObject previousContext = previousContexts.getJSONObject(previousContexts.length() - 1);
-
- @SuppressWarnings("unchecked")
- final Iterator<String> keys = previousContext.keys();
- boolean foundElapsedTime = false;
- while (keys.hasNext()) {
- final String key = keys.next();
- if (LoggingField.ELAPSED_TIME.toString().equals(key)) {
- foundElapsedTime = true;
- }
- try {
- MDC.put(key, previousContext.getString(key));
- } catch (JSONException e) {
- //Ignore, only occurs when the key is null (cannot happen)
- // or the value is invalid (they are all strings)
- }
- }
- if ( !foundElapsedTime ) {
- MDC.remove(LoggingField.ELAPSED_TIME.toString());
- }
- MDC.put(PREVIOUS_CONTEXTS_KEY, removeLast(previousContexts).toString());
- } catch (JSONException e) {
- //Ignore, the previousContext is serialized from a JSONObject
- }
- }
- public static void restoreIfPossible() {
- try {
- restore();
- }
- catch (LoggingContextNotExistsException e) {
- //Ignore
- }
- }
-
- /**
- * AJSC declares an ancient version of org.json:json in one of the parent POMs of this project.
- * I tried to update our version of that library in our POM, but it's ignored because of the way
- * AJSC has organized their <dependencies>. Had they put it into the <dependencyManagement> section,
- * this method would not be necessary.
- */
- private static JSONArray removeLast(JSONArray previousContexts) {
- final JSONArray result = new JSONArray();
-
- for (int i = 0; i < previousContexts.length() - 1; i++) {
- try {
- result.put(previousContexts.getJSONObject(i));
- } catch (JSONException e) {
- //Ignore - not possible
- }
- }
-
- return result;
- }
-
- public static Map<String, String> getCopy() {
- final Map<String, String> copy = new HashMap<String, String> ();
-
- for (LoggingField field : LoggingField.values()) {
- final String value = MDC.get(field.toString());
-
- if (value != null) copy.put(field.toString(), value);
- }
-
- return copy;
- }
+
+ // Specific Log Event Fields
+ public static enum LoggingField {
+ START_TIME("startTime"), REQUEST_ID("requestId"), SERVICE_INSTANCE_ID("serviceInstanceId"), SERVER_NAME(
+ "serverName"), SERVICE_NAME("serviceName"), PARTNER_NAME("partnerName"), STATUS_CODE(
+ "statusCode"), RESPONSE_CODE("responseCode"), RESPONSE_DESCRIPTION(
+ "responseDescription"), INSTANCE_UUID("instanceUUID"), SEVERITY(
+ "severity"), SERVER_IP_ADDRESS(
+ "serverIpAddress"), ELAPSED_TIME("elapsedTime"), SERVER(
+ "server"), CLIENT_IP_ADDRESS("clientIpAddress"), UNUSED(
+ "unused"), PROCESS_KEY("processKey"), CUSTOM_FIELD_1(
+ "customField1"), CUSTOM_FIELD_2(
+ "customField2"), CUSTOM_FIELD_3(
+ "customField3"), CUSTOM_FIELD_4(
+ "customField4"),
+
+ // Specific Metric Log Event Fields
+ TARGET_ENTITY("targetEntity"), TARGET_SERVICE_NAME("targetServiceName"),
+ // A&AI Specific Log Event Fields
+ COMPONENT("component"), STOP_WATCH_START("stopWatchStart");
+
+ private final String text;
+
+ private LoggingField(final String text) {
+ this.text = text;
+ }
+
+ public String toString() {
+ return text;
+ }
+ }
+
+ public static void init() {
+ LoggingContext.clear();
+ LoggingContext.startTime();
+ LoggingContext.server();
+ LoggingContext.serverIpAddress();
+ }
+
+ public static void startTime() {
+ MDC.put(LoggingField.START_TIME.toString(), LogFormatTools.getCurrentDateTime());
+ }
+
+ public static UUID requestId() {
+ final String sUuid = MDC.get(LoggingField.REQUEST_ID.toString());
+
+ if (sUuid == null)
+ return null;
+
+ return UUID.fromString(sUuid);
+ }
+
+ public static void requestId(UUID requestId) {
+ MDC.put(LoggingField.REQUEST_ID.toString(), requestId.toString());
+ }
+
+ public static void requestId(String requestId) {
+ try {
+ if (requestId.contains(":")) {
+ String[] uuidParts = requestId.split(":");
+ requestId = uuidParts[0];
+ }
+ MDC.put(LoggingField.REQUEST_ID.toString(), UUID.fromString(requestId).toString());
+ } catch (IllegalArgumentException e) {
+ final UUID generatedRequestUuid = UUID.randomUUID();
+ MDC.put(LoggingField.REQUEST_ID.toString(), generatedRequestUuid.toString());
+ LoggingContext.save();
+ // set response code to 0 since we don't know what the outcome of this request is yet
+ String responseCode = LoggingContext.DATA_ERROR;
+ LoggingContext.responseCode(responseCode);
+ LoggingContext.responseDescription("Unable to use UUID " + requestId + " (Not formatted properly) ");
+ LoggingContext.statusCode(StatusCode.ERROR);
+
+ LOGGER.warn("Using generated UUID=" + generatedRequestUuid);
+ LoggingContext.restore();
+
+ }
+ }
+
+ public static void serviceInstanceId(String serviceInstanceId) {
+ MDC.put(LoggingField.SERVICE_INSTANCE_ID.toString(), serviceInstanceId);
+ }
+
+ public static void serverName(String serverName) {
+ MDC.put(LoggingField.SERVER_NAME.toString(), serverName);
+ }
+
+ public static void serviceName(String serviceName) {
+ MDC.put(LoggingField.SERVICE_NAME.toString(), serviceName);
+ }
+
+ public static void partnerName(String partnerName) {
+ MDC.put(LoggingField.PARTNER_NAME.toString(), partnerName);
+ }
+
+ public static void statusCode(StatusCode statusCode) {
+ MDC.put(LoggingField.STATUS_CODE.toString(), statusCode.toString());
+ }
+
+ public static String responseCode() {
+ return (String) MDC.get(LoggingField.RESPONSE_CODE.toString());
+ }
+
+ public static void responseCode(String responseCode) {
+ MDC.put(LoggingField.RESPONSE_CODE.toString(), responseCode);
+ }
+
+ public static void responseDescription(String responseDescription) {
+ MDC.put(LoggingField.RESPONSE_DESCRIPTION.toString(), responseDescription);
+ }
+
+ public static Object instanceUuid() {
+ return UUID.fromString(MDC.get(LoggingField.INSTANCE_UUID.toString()));
+ }
+
+ public static void instanceUuid(UUID instanceUuid) {
+ MDC.put(LoggingField.INSTANCE_UUID.toString(), instanceUuid.toString());
+ }
+
+ public static void severity(int severity) {
+ MDC.put(LoggingField.SEVERITY.toString(), String.valueOf(severity));
+ }
+
+ public static void successStatusFields() {
+ responseCode(SUCCESS);
+ statusCode(StatusCode.COMPLETE);
+ responseDescription("Success");
+ }
+
+ private static void serverIpAddress() {
+ try {
+ MDC.put(LoggingField.SERVER_IP_ADDRESS.toString(), InetAddress.getLocalHost().getHostAddress());
+ } catch (UnknownHostException e) {
+ LOGGER.warn("Unable to resolve server IP address - will not be displayed in logged events");
+ }
+ }
+
+ public static void elapsedTime(long elapsedTime, TimeUnit timeUnit) {
+ MDC.put(LoggingField.ELAPSED_TIME.toString(),
+ String.valueOf(TimeUnit.MILLISECONDS.convert(elapsedTime, timeUnit)));
+ }
+
+ private static void server() {
+ try {
+ MDC.put(LoggingField.SERVER.toString(), InetAddress.getLocalHost().getCanonicalHostName());
+ } catch (UnknownHostException e) {
+ LOGGER.warn("Unable to resolve server IP address - hostname will not be displayed in logged events");
+ }
+ }
+
+ public static void clientIpAddress(InetAddress clientIpAddress) {
+ MDC.put(LoggingField.CLIENT_IP_ADDRESS.toString(), clientIpAddress.getHostAddress());
+ }
+
+ public static void clientIpAddress(String clientIpAddress) {
+ try {
+ MDC.put(LoggingField.CLIENT_IP_ADDRESS.toString(), InetAddress.getByName(clientIpAddress).getHostAddress());
+ } catch (UnknownHostException e) {
+ // Ignore, will not be thrown since InetAddress.getByName(String) only
+ // checks the validity of the passed in string
+ }
+ }
+
+ public static void unused(String unused) {
+ LOGGER.warn("Using field '" + LoggingField.UNUSED + "' (seems like this should go unused...)");
+ MDC.put(LoggingField.UNUSED.toString(), unused);
+ }
+
+ public static void processKey(String processKey) {
+ MDC.put(LoggingField.PROCESS_KEY.toString(), processKey);
+ }
+
+ public static String customField1() {
+ return MDC.get(LoggingField.CUSTOM_FIELD_1.toString());
+ }
+
+ public static void customField1(String customField1) {
+ MDC.put(LoggingField.CUSTOM_FIELD_1.toString(), customField1);
+ }
+
+ public static void customField2(String customField2) {
+ MDC.put(LoggingField.CUSTOM_FIELD_2.toString(), customField2);
+ }
+
+ public static void customField3(String customField3) {
+ MDC.put(LoggingField.CUSTOM_FIELD_3.toString(), customField3);
+ }
+
+ public static void customField4(String customField4) {
+ MDC.put(LoggingField.CUSTOM_FIELD_4.toString(), customField4);
+ }
+
+ public static void component(String component) {
+ MDC.put(LoggingField.COMPONENT.toString(), component);
+ }
+
+ public static void targetEntity(String targetEntity) {
+ MDC.put(LoggingField.TARGET_ENTITY.toString(), targetEntity);
+ }
+
+ public static void targetServiceName(String targetServiceName) {
+ MDC.put(LoggingField.TARGET_SERVICE_NAME.toString(), targetServiceName);
+ }
+
+ public static boolean isStopWatchStarted() {
+ final String rawStopWatchStart = MDC.get(LoggingField.STOP_WATCH_START.toString());
+ if (rawStopWatchStart == null) {
+ return false;
+ }
+ return true;
+ }
+
+ public static void stopWatchStart() {
+ MDC.put(LoggingField.STOP_WATCH_START.toString(), String.valueOf(System.nanoTime()));
+ }
+
+ public static double stopWatchStop() {
+ final long stopWatchEnd = System.nanoTime();
+ final String rawStopWatchStart = MDC.get(LoggingField.STOP_WATCH_START.toString());
+
+ if (rawStopWatchStart == null)
+ throw new StopWatchNotStartedException();
+
+ final Long stopWatchStart = Long.valueOf(rawStopWatchStart);
+
+ MDC.remove(LoggingField.STOP_WATCH_START.toString());
+
+ final double elapsedTimeMillis = (stopWatchEnd - stopWatchStart) / 1000.0 / 1000.0;
+
+ LoggingContext.elapsedTime((long) elapsedTimeMillis, TimeUnit.MILLISECONDS);
+
+ return elapsedTimeMillis;
+ }
+
+ public static void put(String key, String value) {
+ MDC.put(key, value);
+ }
+
+ public static void clear() {
+ MDC.clear();
+ }
+
+ public static void remove(String key) {
+ MDC.remove(key);
+ }
+
+ public static void save() {
+ final JSONObject context = new JSONObject();
+
+ for (LoggingField field : LoggingField.values()) {
+ if (field == LoggingField.ELAPSED_TIME)
+ continue;
+
+ try {
+ context.put(field.toString(), MDC.get(field.toString()));
+ } catch (JSONException e) {
+ // Ignore - only occurs when the key is null (which can't happen)
+ // or the value is invalid (everything is converted to a string
+ // before it get put() to the MDC)
+ }
+ }
+
+ final String rawJsonArray = MDC.get(PREVIOUS_CONTEXTS_KEY);
+
+ if (rawJsonArray == null) {
+ final JSONArray stack = new JSONArray().put(context);
+
+ MDC.put(PREVIOUS_CONTEXTS_KEY, stack.toString());
+ } else {
+ try {
+ final JSONArray stack = new JSONArray(rawJsonArray).put(context);
+
+ MDC.put(PREVIOUS_CONTEXTS_KEY, stack.toString());
+ } catch (JSONException e) {
+ // Ignore
+ }
+ }
+ }
+
+ public static void restore() {
+
+ final String rawPreviousContexts = MDC.get(PREVIOUS_CONTEXTS_KEY);
+
+ if (rawPreviousContexts == null) {
+ throw new LoggingContextNotExistsException();
+ }
+
+ try {
+ final JSONArray previousContexts = new JSONArray(rawPreviousContexts);
+ final JSONObject previousContext = previousContexts.getJSONObject(previousContexts.length() - 1);
+
+ @SuppressWarnings("unchecked")
+ final Iterator<String> keys = previousContext.keys();
+ boolean foundElapsedTime = false;
+ while (keys.hasNext()) {
+ final String key = keys.next();
+ if (LoggingField.ELAPSED_TIME.toString().equals(key)) {
+ foundElapsedTime = true;
+ }
+ try {
+ MDC.put(key, previousContext.getString(key));
+ } catch (JSONException e) {
+ // Ignore, only occurs when the key is null (cannot happen)
+ // or the value is invalid (they are all strings)
+ }
+ }
+ if (!foundElapsedTime) {
+ MDC.remove(LoggingField.ELAPSED_TIME.toString());
+ }
+ MDC.put(PREVIOUS_CONTEXTS_KEY, removeLast(previousContexts).toString());
+ } catch (JSONException e) {
+ // Ignore, the previousContext is serialized from a JSONObject
+ }
+ }
+
+ public static void restoreIfPossible() {
+ try {
+ restore();
+ } catch (LoggingContextNotExistsException e) {
+ // Ignore
+ }
+ }
+
+ /**
+ * AJSC declares an ancient version of org.json:json in one of the parent POMs of this project.
+ * I tried to update our version of that library in our POM, but it's ignored because of the way
+ * AJSC has organized their <dependencies>. Had they put it into the <dependencyManagement> section,
+ * this method would not be necessary.
+ */
+ private static JSONArray removeLast(JSONArray previousContexts) {
+ final JSONArray result = new JSONArray();
+
+ for (int i = 0; i < previousContexts.length() - 1; i++) {
+ try {
+ result.put(previousContexts.getJSONObject(i));
+ } catch (JSONException e) {
+ // Ignore - not possible
+ }
+ }
+
+ return result;
+ }
+
+ public static Map<String, String> getCopy() {
+ final Map<String, String> copy = new HashMap<String, String>();
+
+ for (LoggingField field : LoggingField.values()) {
+ final String value = MDC.get(field.toString());
+
+ if (value != null)
+ copy.put(field.toString(), value);
+ }
+
+ return copy;
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/logging/LoggingContextNotExistsException.java b/aai-core/src/main/java/org/onap/aai/logging/LoggingContextNotExistsException.java
index fab59fcc..f1d4c59c 100644
--- a/aai-core/src/main/java/org/onap/aai/logging/LoggingContextNotExistsException.java
+++ b/aai-core/src/main/java/org/onap/aai/logging/LoggingContextNotExistsException.java
@@ -17,9 +17,10 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.logging;
public class LoggingContextNotExistsException extends RuntimeException {
- private static final long serialVersionUID = -4965807709525739623L;
+ private static final long serialVersionUID = -4965807709525739623L;
}
diff --git a/aai-core/src/main/java/org/onap/aai/logging/StopWatch.java b/aai-core/src/main/java/org/onap/aai/logging/StopWatch.java
index e305062a..0d93827f 100644
--- a/aai-core/src/main/java/org/onap/aai/logging/StopWatch.java
+++ b/aai-core/src/main/java/org/onap/aai/logging/StopWatch.java
@@ -17,35 +17,40 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.logging;
import org.onap.aai.logging.LoggingContext.LoggingField;
public final class StopWatch {
- private StopWatch() {}
-
- public static void start() {
- LoggingContext.stopWatchStart();
- }
-
- public static double stop() {
- return LoggingContext.stopWatchStop();
- }
- public static void conditionalStart() {
- if ( LoggingContext.isStopWatchStarted() ) {
- return;
- }
- start();
- }
- public static double stopIfStarted() {
- if ( LoggingContext.isStopWatchStarted() ) {
- return (stop());
- }
- return (0);
- }
- public static void clear() {
- LoggingContext.remove(LoggingField.STOP_WATCH_START.toString());
- LoggingContext.remove(LoggingField.ELAPSED_TIME.toString());
- }
+ private StopWatch() {
+ }
+
+ public static void start() {
+ LoggingContext.stopWatchStart();
+ }
+
+ public static double stop() {
+ return LoggingContext.stopWatchStop();
+ }
+
+ public static void conditionalStart() {
+ if (LoggingContext.isStopWatchStarted()) {
+ return;
+ }
+ start();
+ }
+
+ public static double stopIfStarted() {
+ if (LoggingContext.isStopWatchStarted()) {
+ return (stop());
+ }
+ return (0);
+ }
+
+ public static void clear() {
+ LoggingContext.remove(LoggingField.STOP_WATCH_START.toString());
+ LoggingContext.remove(LoggingField.ELAPSED_TIME.toString());
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/logging/StopWatchNotStartedException.java b/aai-core/src/main/java/org/onap/aai/logging/StopWatchNotStartedException.java
index b1ee5de6..e4819c5c 100644
--- a/aai-core/src/main/java/org/onap/aai/logging/StopWatchNotStartedException.java
+++ b/aai-core/src/main/java/org/onap/aai/logging/StopWatchNotStartedException.java
@@ -17,25 +17,26 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.logging;
public class StopWatchNotStartedException extends RuntimeException {
- private static final long serialVersionUID = -4540164295822859408L;
+ private static final long serialVersionUID = -4540164295822859408L;
- public StopWatchNotStartedException() {
- super();
- }
+ public StopWatchNotStartedException() {
+ super();
+ }
- public StopWatchNotStartedException(String message) {
- super(message);
- }
+ public StopWatchNotStartedException(String message) {
+ super(message);
+ }
- public StopWatchNotStartedException(Throwable cause) {
- super(cause);
- }
+ public StopWatchNotStartedException(Throwable cause) {
+ super(cause);
+ }
- public StopWatchNotStartedException(String message, Throwable cause) {
- super(message, cause);
- }
+ public StopWatchNotStartedException(String message, Throwable cause) {
+ super(message, cause);
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/parsers/exceptions/AAIIdentityMapParseException.java b/aai-core/src/main/java/org/onap/aai/parsers/exceptions/AAIIdentityMapParseException.java
index 4693840e..b09165ea 100644
--- a/aai-core/src/main/java/org/onap/aai/parsers/exceptions/AAIIdentityMapParseException.java
+++ b/aai-core/src/main/java/org/onap/aai/parsers/exceptions/AAIIdentityMapParseException.java
@@ -17,24 +17,25 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.parsers.exceptions;
import org.onap.aai.exceptions.AAIException;
public class AAIIdentityMapParseException extends AAIException {
- private static final long serialVersionUID = -888876613879411865L;
-
- public AAIIdentityMapParseException(String message) {
- super("AAI_3000", message);
- }
+ private static final long serialVersionUID = -888876613879411865L;
+
+ public AAIIdentityMapParseException(String message) {
+ super("AAI_3000", message);
+ }
- public AAIIdentityMapParseException(Throwable cause) {
- super("AAI_3000",cause);
- }
+ public AAIIdentityMapParseException(Throwable cause) {
+ super("AAI_3000", cause);
+ }
- public AAIIdentityMapParseException(String message, Throwable cause) {
- super("AAI_3000", cause, message);
- }
+ public AAIIdentityMapParseException(String message, Throwable cause) {
+ super("AAI_3000", cause, message);
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/parsers/exceptions/AmbiguousMapAAIException.java b/aai-core/src/main/java/org/onap/aai/parsers/exceptions/AmbiguousMapAAIException.java
index 7ee494a4..edd0b7fb 100644
--- a/aai-core/src/main/java/org/onap/aai/parsers/exceptions/AmbiguousMapAAIException.java
+++ b/aai-core/src/main/java/org/onap/aai/parsers/exceptions/AmbiguousMapAAIException.java
@@ -17,24 +17,25 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.parsers.exceptions;
import org.onap.aai.exceptions.AAIException;
public class AmbiguousMapAAIException extends AAIException {
-
- private static final long serialVersionUID = -878581771971431246L;
-
- public AmbiguousMapAAIException(String message) {
- super("AAI_6146", message);
- }
-
- public AmbiguousMapAAIException(Throwable cause) {
- super("AAI_6146",cause);
- }
-
- public AmbiguousMapAAIException(String message, Throwable cause) {
- super("AAI_6146", cause, message);
- }
+
+ private static final long serialVersionUID = -878581771971431246L;
+
+ public AmbiguousMapAAIException(String message) {
+ super("AAI_6146", message);
+ }
+
+ public AmbiguousMapAAIException(Throwable cause) {
+ super("AAI_6146", cause);
+ }
+
+ public AmbiguousMapAAIException(String message, Throwable cause) {
+ super("AAI_6146", cause, message);
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/parsers/exceptions/DoesNotStartWithValidNamespaceException.java b/aai-core/src/main/java/org/onap/aai/parsers/exceptions/DoesNotStartWithValidNamespaceException.java
index 88cdc47b..dedfa4c5 100644
--- a/aai-core/src/main/java/org/onap/aai/parsers/exceptions/DoesNotStartWithValidNamespaceException.java
+++ b/aai-core/src/main/java/org/onap/aai/parsers/exceptions/DoesNotStartWithValidNamespaceException.java
@@ -17,25 +17,25 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.parsers.exceptions;
import org.onap.aai.exceptions.AAIException;
public class DoesNotStartWithValidNamespaceException extends AAIException {
- private static final long serialVersionUID = -888876613879411865L;
-
- public DoesNotStartWithValidNamespaceException(String message) {
- super("AAI_3000", message);
- }
+ private static final long serialVersionUID = -888876613879411865L;
- public DoesNotStartWithValidNamespaceException(Throwable cause) {
- super("AAI_3000",cause);
- }
+ public DoesNotStartWithValidNamespaceException(String message) {
+ super("AAI_3000", message);
+ }
- public DoesNotStartWithValidNamespaceException(String message, Throwable cause) {
- super("AAI_3000", cause, message);
- }
+ public DoesNotStartWithValidNamespaceException(Throwable cause) {
+ super("AAI_3000", cause);
+ }
-}
+ public DoesNotStartWithValidNamespaceException(String message, Throwable cause) {
+ super("AAI_3000", cause, message);
+ }
+}
diff --git a/aai-core/src/main/java/org/onap/aai/parsers/query/LegacyQueryParser.java b/aai-core/src/main/java/org/onap/aai/parsers/query/LegacyQueryParser.java
index d20915c4..c9412733 100644
--- a/aai-core/src/main/java/org/onap/aai/parsers/query/LegacyQueryParser.java
+++ b/aai-core/src/main/java/org/onap/aai/parsers/query/LegacyQueryParser.java
@@ -17,10 +17,21 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.parsers.query;
import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.*;
+import java.util.Map.Entry;
+
+import javax.ws.rs.core.MultivaluedMap;
+
+import org.onap.aai.edges.enums.EdgeType;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.introspection.Introspector;
import org.onap.aai.introspection.Loader;
@@ -32,197 +43,202 @@ import org.onap.aai.parsers.uri.URIToObject;
import org.onap.aai.query.builder.QueryBuilder;
import org.onap.aai.restcore.util.URITools;
import org.onap.aai.schema.enums.PropertyMetadata;
-import org.onap.aai.edges.enums.EdgeType;
-
-import javax.ws.rs.core.MultivaluedMap;
-import java.io.UnsupportedEncodingException;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.util.*;
-import java.util.Map.Entry;
/**
* The Class LegacyQueryParser.
*/
public class LegacyQueryParser extends QueryParser implements Parsable {
- private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(LegacyQueryParser.class);
-
- private Introspector previous = null;
-
- /**
- * Instantiates a new legacy query parser.
- *
- * @param loader the loader
- * @param queryBuilder the query builder
- * @param uri the uri
- * @throws UnsupportedEncodingException the unsupported encoding exception
- * @throws AAIException the AAI exception
- */
- public LegacyQueryParser(Loader loader, QueryBuilder queryBuilder, URI uri) throws UnsupportedEncodingException, AAIException {
- super(loader, queryBuilder, uri);
- URIParser parser = new URIParser(loader, uri);
- parser.parse(this);
- }
-
- /**
- * Instantiates a new legacy query parser.
- *
- * @param loader the loader
- * @param queryBuilder the query builder
- * @param uri the uri
- * @param queryParams the query params
- * @throws UnsupportedEncodingException the unsupported encoding exception
- * @throws AAIException the AAI exception
- */
- public LegacyQueryParser(Loader loader, QueryBuilder queryBuilder, URI uri, MultivaluedMap<String, String> queryParams) throws UnsupportedEncodingException, AAIException {
- super(loader, queryBuilder, uri);
- URIParser parser = new URIParser(loader, uri, queryParams);
- parser.parse(this);
- }
-
- /**
- * Instantiates a new legacy query parser.
- *
- * @param loader the loader
- * @param queryBuilder the query builder
- */
- public LegacyQueryParser(Loader loader, QueryBuilder queryBuilder) {
- super(loader, queryBuilder);
- }
-
- /**
- * @throws AAIException
- * @{inheritDoc}
- */
- @Override
- public void processObject(Introspector obj, EdgeType type, MultivaluedMap<String, String> uriKeys) throws AAIException {
- if (previous != null) {
- this.parentResourceType = previous.getDbName();
- queryBuilder.createEdgeTraversal(type, previous, obj);
- }
- if (previous == null) {
- queryBuilder.createDBQuery(obj);
- this.handleUriKeys(obj, uriKeys);
- } else {
- queryBuilder.createKeyQuery(obj);
- this.handleUriKeys(obj, uriKeys);
- }
- previous = obj;
- this.resultResource = obj.getDbName();
- }
-
- /**
- * @{inheritDoc}
- */
- @Override
- public void processContainer(Introspector obj, EdgeType type, MultivaluedMap<String, String> uriKeys, boolean isFinalContainer) throws AAIException {
- if (isFinalContainer) {
- if (previous != null) {
- this.parentResourceType = previous.getDbName();
- queryBuilder.createEdgeTraversal(type, previous, obj);
- }
-
- if (previous == null) {
- queryBuilder.createContainerQuery(obj);
- queryBuilder.markParentBoundary();
- }
- if (!uriKeys.isEmpty()) {
-
- try {
- Introspector child = obj.newIntrospectorInstanceOfNestedProperty(obj.getChildName());
- this.handleUriKeys(child, uriKeys);
- } catch (AAIUnknownObjectException e) {
- LOGGER.warn("Skipping container child " + obj.getChildName() + " (Unknown Object) " +
- LogFormatTools.getStackTop(e));
- }
- }
-
- this.resultResource = obj.getChildDBName();
- this.containerResource = obj.getName();
- }
- }
- private void handleUriKeys(Introspector obj, MultivaluedMap<String, String> uriKeys) throws AAIException {
- for (String key : uriKeys.keySet()) {
- //to validate whether this property exists
- if (!obj.hasProperty(key)) {
- throw new AAIException("AAI_3000", "property: " + key + " not found on " + obj.getDbName());
- }
-
- List<String> values = uriKeys.get(key);
- String dbPropertyName = key;
- Map<String, String> linkedProperties = new HashMap<>();
- final Map<PropertyMetadata, String> metadata = obj.getPropertyMetadata(key);
- if (metadata.containsKey(PropertyMetadata.DATA_LINK)) {
- linkedProperties.put(key, metadata.get(PropertyMetadata.DATA_LINK));
- }
- if (metadata.containsKey(PropertyMetadata.DB_ALIAS)) {
- dbPropertyName = metadata.get(PropertyMetadata.DB_ALIAS);
- }
-
- if (!linkedProperties.containsKey(key)) {
- if (values.size() > 1) {
- queryBuilder.getVerticesByIndexedProperty(dbPropertyName, obj.castValueAccordingToSchema(key, values));
- } else {
- queryBuilder.getVerticesByIndexedProperty(dbPropertyName, obj.castValueAccordingToSchema(key, values.get(0)));
- }
- }
- handleLinkedProperties(obj, uriKeys, linkedProperties);
- }
- }
- private void handleLinkedProperties(Introspector obj, MultivaluedMap<String, String> uriKeys, Map<String, String> linkedProperties) throws AAIException {
-
- QueryBuilder[] builders = new QueryBuilder[linkedProperties.keySet().size()];
- Set<Entry<String, String>> entrySet = linkedProperties.entrySet();
- int i = 0;
- Iterator<Entry<String, String>> itr = entrySet.iterator();
-
- while (itr.hasNext()) {
- Entry<String, String> entry = itr.next();
- Introspector child;
- try {
- child = new URIToObject(this.latestLoader, new URI(URITools.replaceTemplates(obj, entry.getValue(), PropertyMetadata.DATA_LINK, true).orElse(""))).getEntity();
- } catch (IllegalArgumentException | UnsupportedEncodingException | URISyntaxException e) {
- throw new AAIException("AAI_4000", e);
- }
- List<String> values = uriKeys.get(entry.getKey());
- QueryBuilder builder = queryBuilder.newInstance();
- builder.createEdgeTraversal(EdgeType.TREE, obj, child);
- if (values.size() > 1) {
- builder.getVerticesByIndexedProperty(entry.getKey(), obj.castValueAccordingToSchema(entry.getKey(), values));
- } else {
- builder.getVerticesByIndexedProperty(entry.getKey(), obj.castValueAccordingToSchema(entry.getKey(), values.get(0)));
- }
-
- builders[i] = builder;
- i++;
- }
-
- queryBuilder.where(builders);
-
- }
-
- /**
- * @{inheritDoc}
- */
- @Override
- public void processNamespace(Introspector obj) {
-
- }
-
- /**
- * @{inheritDoc}
- */
- @Override
- public String getCloudRegionTransform() {
- return "add";
- }
-
- /**
- * @{inheritDoc}
- */
- @Override
- public boolean useOriginalLoader() {
- return false;
- }
+ private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(LegacyQueryParser.class);
+
+ private Introspector previous = null;
+
+ /**
+ * Instantiates a new legacy query parser.
+ *
+ * @param loader the loader
+ * @param queryBuilder the query builder
+ * @param uri the uri
+ * @throws UnsupportedEncodingException the unsupported encoding exception
+ * @throws AAIException the AAI exception
+ */
+ public LegacyQueryParser(Loader loader, QueryBuilder queryBuilder, URI uri)
+ throws UnsupportedEncodingException, AAIException {
+ super(loader, queryBuilder, uri);
+ URIParser parser = new URIParser(loader, uri);
+ parser.parse(this);
+ }
+
+ /**
+ * Instantiates a new legacy query parser.
+ *
+ * @param loader the loader
+ * @param queryBuilder the query builder
+ * @param uri the uri
+ * @param queryParams the query params
+ * @throws UnsupportedEncodingException the unsupported encoding exception
+ * @throws AAIException the AAI exception
+ */
+ public LegacyQueryParser(Loader loader, QueryBuilder queryBuilder, URI uri,
+ MultivaluedMap<String, String> queryParams) throws UnsupportedEncodingException, AAIException {
+ super(loader, queryBuilder, uri);
+ URIParser parser = new URIParser(loader, uri, queryParams);
+ parser.parse(this);
+ }
+
+ /**
+ * Instantiates a new legacy query parser.
+ *
+ * @param loader the loader
+ * @param queryBuilder the query builder
+ */
+ public LegacyQueryParser(Loader loader, QueryBuilder queryBuilder) {
+ super(loader, queryBuilder);
+ }
+
+ /**
+ * @throws AAIException
+ * @{inheritDoc}
+ */
+ @Override
+ public void processObject(Introspector obj, EdgeType type, MultivaluedMap<String, String> uriKeys)
+ throws AAIException {
+ if (previous != null) {
+ this.parentResourceType = previous.getDbName();
+ queryBuilder.createEdgeTraversal(type, previous, obj);
+ }
+ if (previous == null) {
+ queryBuilder.createDBQuery(obj);
+ this.handleUriKeys(obj, uriKeys);
+ } else {
+ queryBuilder.createKeyQuery(obj);
+ this.handleUriKeys(obj, uriKeys);
+ }
+ previous = obj;
+ this.resultResource = obj.getDbName();
+ }
+
+ /**
+ * @{inheritDoc}
+ */
+ @Override
+ public void processContainer(Introspector obj, EdgeType type, MultivaluedMap<String, String> uriKeys,
+ boolean isFinalContainer) throws AAIException {
+ if (isFinalContainer) {
+ if (previous != null) {
+ this.parentResourceType = previous.getDbName();
+ queryBuilder.createEdgeTraversal(type, previous, obj);
+ }
+
+ if (previous == null) {
+ queryBuilder.createContainerQuery(obj);
+ queryBuilder.markParentBoundary();
+ }
+ if (!uriKeys.isEmpty()) {
+
+ try {
+ Introspector child = obj.newIntrospectorInstanceOfNestedProperty(obj.getChildName());
+ this.handleUriKeys(child, uriKeys);
+ } catch (AAIUnknownObjectException e) {
+ LOGGER.warn("Skipping container child " + obj.getChildName() + " (Unknown Object) "
+ + LogFormatTools.getStackTop(e));
+ }
+ }
+
+ this.resultResource = obj.getChildDBName();
+ this.containerResource = obj.getName();
+ }
+ }
+
+ private void handleUriKeys(Introspector obj, MultivaluedMap<String, String> uriKeys) throws AAIException {
+ for (String key : uriKeys.keySet()) {
+ // to validate whether this property exists
+ if (!obj.hasProperty(key)) {
+ throw new AAIException("AAI_3000", "property: " + key + " not found on " + obj.getDbName());
+ }
+
+ List<String> values = uriKeys.get(key);
+ String dbPropertyName = key;
+ Map<String, String> linkedProperties = new HashMap<>();
+ final Map<PropertyMetadata, String> metadata = obj.getPropertyMetadata(key);
+ if (metadata.containsKey(PropertyMetadata.DATA_LINK)) {
+ linkedProperties.put(key, metadata.get(PropertyMetadata.DATA_LINK));
+ }
+ if (metadata.containsKey(PropertyMetadata.DB_ALIAS)) {
+ dbPropertyName = metadata.get(PropertyMetadata.DB_ALIAS);
+ }
+
+ if (!linkedProperties.containsKey(key)) {
+ if (values.size() > 1) {
+ queryBuilder.getVerticesByIndexedProperty(dbPropertyName,
+ obj.castValueAccordingToSchema(key, values));
+ } else {
+ queryBuilder.getVerticesByIndexedProperty(dbPropertyName,
+ obj.castValueAccordingToSchema(key, values.get(0)));
+ }
+ }
+ handleLinkedProperties(obj, uriKeys, linkedProperties);
+ }
+ }
+
+ private void handleLinkedProperties(Introspector obj, MultivaluedMap<String, String> uriKeys,
+ Map<String, String> linkedProperties) throws AAIException {
+
+ QueryBuilder[] builders = new QueryBuilder[linkedProperties.keySet().size()];
+ Set<Entry<String, String>> entrySet = linkedProperties.entrySet();
+ int i = 0;
+ Iterator<Entry<String, String>> itr = entrySet.iterator();
+
+ while (itr.hasNext()) {
+ Entry<String, String> entry = itr.next();
+ Introspector child;
+ try {
+ child = new URIToObject(this.latestLoader, new URI(
+ URITools.replaceTemplates(obj, entry.getValue(), PropertyMetadata.DATA_LINK, true).orElse("")))
+ .getEntity();
+ } catch (IllegalArgumentException | UnsupportedEncodingException | URISyntaxException e) {
+ throw new AAIException("AAI_4000", e);
+ }
+ List<String> values = uriKeys.get(entry.getKey());
+ QueryBuilder builder = queryBuilder.newInstance();
+ builder.createEdgeTraversal(EdgeType.TREE, obj, child);
+ if (values.size() > 1) {
+ builder.getVerticesByIndexedProperty(entry.getKey(),
+ obj.castValueAccordingToSchema(entry.getKey(), values));
+ } else {
+ builder.getVerticesByIndexedProperty(entry.getKey(),
+ obj.castValueAccordingToSchema(entry.getKey(), values.get(0)));
+ }
+
+ builders[i] = builder;
+ i++;
+ }
+
+ queryBuilder.where(builders);
+
+ }
+
+ /**
+ * @{inheritDoc}
+ */
+ @Override
+ public void processNamespace(Introspector obj) {
+
+ }
+
+ /**
+ * @{inheritDoc}
+ */
+ @Override
+ public String getCloudRegionTransform() {
+ return "add";
+ }
+
+ /**
+ * @{inheritDoc}
+ */
+ @Override
+ public boolean useOriginalLoader() {
+ return false;
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/parsers/query/ObjectNameQueryParser.java b/aai-core/src/main/java/org/onap/aai/parsers/query/ObjectNameQueryParser.java
index 29790225..776e4017 100644
--- a/aai-core/src/main/java/org/onap/aai/parsers/query/ObjectNameQueryParser.java
+++ b/aai-core/src/main/java/org/onap/aai/parsers/query/ObjectNameQueryParser.java
@@ -20,16 +20,17 @@
/**
*
*/
+
package org.onap.aai.parsers.query;
import org.onap.aai.introspection.Loader;
import org.onap.aai.query.builder.QueryBuilder;
public class ObjectNameQueryParser extends QueryParser {
-
- public ObjectNameQueryParser(Loader loader, QueryBuilder queryBuilder, String objName) {
- super(loader, queryBuilder);
- this.resultResource = objName;
- }
+
+ public ObjectNameQueryParser(Loader loader, QueryBuilder queryBuilder, String objName) {
+ super(loader, queryBuilder);
+ this.resultResource = objName;
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/parsers/query/QueryParser.java b/aai-core/src/main/java/org/onap/aai/parsers/query/QueryParser.java
index d7f1832c..0b1deb55 100644
--- a/aai-core/src/main/java/org/onap/aai/parsers/query/QueryParser.java
+++ b/aai-core/src/main/java/org/onap/aai/parsers/query/QueryParser.java
@@ -17,8 +17,11 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.parsers.query;
+import java.net.URI;
+
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.onap.aai.config.SpringContextAware;
import org.onap.aai.introspection.Loader;
@@ -27,124 +30,122 @@ import org.onap.aai.introspection.LoaderUtil;
import org.onap.aai.query.builder.QueryBuilder;
import org.onap.aai.setup.SchemaVersion;
import org.onap.aai.setup.SchemaVersions;
-import java.net.URI;
/**
* The Class QueryParser.
*/
public abstract class QueryParser {
- protected Loader loader = null;
- protected Loader latestLoader = null;
- protected QueryBuilder<Vertex> queryBuilder = null;
-
- protected QueryBuilder<Vertex> parentQueryBuilder = null;
-
- protected URI uri = null;
-
- protected String resultResource = "";
-
- protected String parentResourceType = "";
-
- protected String containerResource = "";
-
- /**
- * Instantiates a new query parser.
- *
- * @param loader the loader
- * @param queryBuilder the query builder
- * @param uri the uri
- */
- protected QueryParser(Loader loader, QueryBuilder<Vertex> queryBuilder, URI uri) {
- this.uri = uri;
- this.queryBuilder = queryBuilder;
- this.loader = loader;
- LoaderFactory loaderFactory = SpringContextAware.getBean(LoaderFactory.class);
- SchemaVersion latest = ((SchemaVersions) SpringContextAware.getBean("schemaVersions")).getDefaultVersion();
-
- this.latestLoader = loaderFactory.createLoaderForVersion(loader.getModelType(), latest);
- }
-
- /**
- * Instantiates a new query parser.
- *
- * @param loader the loader
- * @param queryBuilder the query builder
- */
- protected QueryParser(Loader loader, QueryBuilder<Vertex> queryBuilder) {
- this.queryBuilder = queryBuilder;
- this.loader = loader;
- this.latestLoader = LoaderUtil.getLatestVersion();
- }
-
- /**
- * Gets the container type.
- *
- * @return the container type
- */
- public String getContainerType() {
-
- return this.containerResource;
- }
-
- /**
- * Gets the parent result type.
- *
- * @return the parent result type
- */
- public String getParentResultType() {
- return this.parentResourceType;
- }
-
- /**
- * Gets the result type.
- *
- * @return the result type
- */
- public String getResultType() {
- return this.resultResource;
- }
-
- /**
- * Gets the query builder.
- *
- * @return the query builder
- */
- public QueryBuilder<Vertex> getQueryBuilder() {
- return this.queryBuilder;
- }
-
- /**
- * Gets the uri.
- *
- * @return the uri
- */
- public URI getUri() {
- return this.uri;
- }
-
- /**
- * Gets the parent query builder.
- *
- * @return the parent query builder
- */
- public QueryBuilder<Vertex> getParentQueryBuilder() {
- if (this.parentQueryBuilder != null) {
- return this.parentQueryBuilder;
- } else {
- return this.queryBuilder;
- }
- }
-
- /**
- * Checks if is dependent.
- *
- * @return true, if is dependent
- */
- public boolean isDependent() {
- return !this.queryBuilder.getQuery().toString().equals(this.queryBuilder.getParentQuery().getQuery().toString());
- }
+ protected Loader loader = null;
+ protected Loader latestLoader = null;
+ protected QueryBuilder<Vertex> queryBuilder = null;
+
+ protected QueryBuilder<Vertex> parentQueryBuilder = null;
+
+ protected URI uri = null;
+
+ protected String resultResource = "";
+
+ protected String parentResourceType = "";
+
+ protected String containerResource = "";
+
+ /**
+ * Instantiates a new query parser.
+ *
+ * @param loader the loader
+ * @param queryBuilder the query builder
+ * @param uri the uri
+ */
+ protected QueryParser(Loader loader, QueryBuilder<Vertex> queryBuilder, URI uri) {
+ this.uri = uri;
+ this.queryBuilder = queryBuilder;
+ this.loader = loader;
+ LoaderFactory loaderFactory = SpringContextAware.getBean(LoaderFactory.class);
+ SchemaVersion latest = ((SchemaVersions) SpringContextAware.getBean("schemaVersions")).getDefaultVersion();
+
+ this.latestLoader = loaderFactory.createLoaderForVersion(loader.getModelType(), latest);
+ }
+
+ /**
+ * Instantiates a new query parser.
+ *
+ * @param loader the loader
+ * @param queryBuilder the query builder
+ */
+ protected QueryParser(Loader loader, QueryBuilder<Vertex> queryBuilder) {
+ this.queryBuilder = queryBuilder;
+ this.loader = loader;
+ this.latestLoader = LoaderUtil.getLatestVersion();
+ }
+
+ /**
+ * Gets the container type.
+ *
+ * @return the container type
+ */
+ public String getContainerType() {
+
+ return this.containerResource;
+ }
+
+ /**
+ * Gets the parent result type.
+ *
+ * @return the parent result type
+ */
+ public String getParentResultType() {
+ return this.parentResourceType;
+ }
+
+ /**
+ * Gets the result type.
+ *
+ * @return the result type
+ */
+ public String getResultType() {
+ return this.resultResource;
+ }
+
+ /**
+ * Gets the query builder.
+ *
+ * @return the query builder
+ */
+ public QueryBuilder<Vertex> getQueryBuilder() {
+ return this.queryBuilder;
+ }
+
+ /**
+ * Gets the uri.
+ *
+ * @return the uri
+ */
+ public URI getUri() {
+ return this.uri;
+ }
+
+ /**
+ * Gets the parent query builder.
+ *
+ * @return the parent query builder
+ */
+ public QueryBuilder<Vertex> getParentQueryBuilder() {
+ if (this.parentQueryBuilder != null) {
+ return this.parentQueryBuilder;
+ } else {
+ return this.queryBuilder;
+ }
+ }
+
+ /**
+ * Checks if is dependent.
+ *
+ * @return true, if is dependent
+ */
+ public boolean isDependent() {
+ return !this.queryBuilder.getQuery().toString()
+ .equals(this.queryBuilder.getParentQuery().getQuery().toString());
+ }
}
-
-
diff --git a/aai-core/src/main/java/org/onap/aai/parsers/query/QueryParserStrategy.java b/aai-core/src/main/java/org/onap/aai/parsers/query/QueryParserStrategy.java
index e8ff60b3..18600b95 100644
--- a/aai-core/src/main/java/org/onap/aai/parsers/query/QueryParserStrategy.java
+++ b/aai-core/src/main/java/org/onap/aai/parsers/query/QueryParserStrategy.java
@@ -17,74 +17,78 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.parsers.query;
+import java.io.UnsupportedEncodingException;
+import java.net.URI;
+
+import javax.ws.rs.core.MultivaluedMap;
+
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.introspection.Introspector;
import org.onap.aai.introspection.Loader;
import org.onap.aai.query.builder.QueryBuilder;
-import javax.ws.rs.core.MultivaluedMap;
-import java.io.UnsupportedEncodingException;
-import java.net.URI;
-
/**
* The Class QueryParserStrategy.
*/
public abstract class QueryParserStrategy {
- protected Loader loader = null;
-
- protected QueryBuilder builder = null;
-
- /**
- * Instantiates a new query parser strategy.
- *
- * @param loader the loader
- * @param builder the builder
- */
- public QueryParserStrategy(Loader loader, QueryBuilder builder) {
-
- this.loader = loader;
- this.builder = builder;
- }
-
- /**
- * Builds the URI parser.
- *
- * @param uri the uri
- * @return the query parser
- * @throws UnsupportedEncodingException the unsupported encoding exception
- * @throws AAIException the AAI exception
- */
- public abstract QueryParser buildURIParser(URI uri) throws UnsupportedEncodingException, AAIException;
-
- /**
- * Builds the URI parser.
- *
- * @param uri the uri
- * @param queryParams the query params
- * @return the query parser
- * @throws UnsupportedEncodingException the unsupported encoding exception
- * @throws AAIException the AAI exception
- */
- public abstract QueryParser buildURIParser(URI uri,MultivaluedMap<String, String> queryParams) throws UnsupportedEncodingException, AAIException;
+ protected Loader loader = null;
+
+ protected QueryBuilder builder = null;
+
+ /**
+ * Instantiates a new query parser strategy.
+ *
+ * @param loader the loader
+ * @param builder the builder
+ */
+ public QueryParserStrategy(Loader loader, QueryBuilder builder) {
+
+ this.loader = loader;
+ this.builder = builder;
+ }
+
+ /**
+ * Builds the URI parser.
+ *
+ * @param uri the uri
+ * @return the query parser
+ * @throws UnsupportedEncodingException the unsupported encoding exception
+ * @throws AAIException the AAI exception
+ */
+ public abstract QueryParser buildURIParser(URI uri) throws UnsupportedEncodingException, AAIException;
+
+ /**
+ * Builds the URI parser.
+ *
+ * @param uri the uri
+ * @param queryParams the query params
+ * @return the query parser
+ * @throws UnsupportedEncodingException the unsupported encoding exception
+ * @throws AAIException the AAI exception
+ */
+ public abstract QueryParser buildURIParser(URI uri, MultivaluedMap<String, String> queryParams)
+ throws UnsupportedEncodingException, AAIException;
+
+ /**
+ * Builds the relationship parser.
+ *
+ * @param obj the obj
+ * @return the query parser
+ * @throws UnsupportedEncodingException the unsupported encoding exception
+ * @throws AAIException the AAI exception
+ */
+ public abstract QueryParser buildRelationshipParser(Introspector obj)
+ throws UnsupportedEncodingException, AAIException;
- /**
- * Builds the relationship parser.
- *
- * @param obj the obj
- * @return the query parser
- * @throws UnsupportedEncodingException the unsupported encoding exception
- * @throws AAIException the AAI exception
- */
- public abstract QueryParser buildRelationshipParser(Introspector obj) throws UnsupportedEncodingException, AAIException;
-
- /**
- * Builds an ObjectNameQueryParser.
- *
- * @param objName - the name of the object type as used in the database
- * @return
- */
- public abstract QueryParser buildObjectNameParser(String objName);
+ /**
+ * Builds an ObjectNameQueryParser.
+ *
+ * @param objName - the name of the object type as used in the database
+ * @return
+ */
+ public abstract QueryParser buildObjectNameParser(String objName);
}
diff --git a/aai-core/src/main/java/org/onap/aai/parsers/query/RelationshipQueryParser.java b/aai-core/src/main/java/org/onap/aai/parsers/query/RelationshipQueryParser.java
index c3ca5cba..0958a81e 100644
--- a/aai-core/src/main/java/org/onap/aai/parsers/query/RelationshipQueryParser.java
+++ b/aai-core/src/main/java/org/onap/aai/parsers/query/RelationshipQueryParser.java
@@ -17,10 +17,14 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.parsers.query;
import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
+
+import java.io.UnsupportedEncodingException;
+
import org.onap.aai.config.SpringContextAware;
import org.onap.aai.edges.EdgeIngestor;
import org.onap.aai.exceptions.AAIException;
@@ -32,49 +36,48 @@ import org.onap.aai.parsers.uri.URIParser;
import org.onap.aai.query.builder.QueryBuilder;
import org.springframework.context.ApplicationContext;
-import java.io.UnsupportedEncodingException;
-
/**
* The Class RelationshipQueryParser.
*/
public class RelationshipQueryParser extends LegacyQueryParser {
- private static final EELFLogger logger = EELFManager.getInstance().getLogger(RelationshipQueryParser.class);
+ private static final EELFLogger logger = EELFManager.getInstance().getLogger(RelationshipQueryParser.class);
+
+ private Introspector relationship = null;
+
+ private ModelType modelType = null;
+
+ private EdgeIngestor edgeRules = null;
- private Introspector relationship = null;
-
- private ModelType modelType = null;
-
- private EdgeIngestor edgeRules = null;
-
- /**
- * Instantiates a new relationship query parser.
- *
- * @param loader the loader
- * @param queryBuilder the query builder
- * @param obj the obj
- * @throws UnsupportedEncodingException the unsupported encoding exception
- * @throws AAIException the AAI exception
- */
- public RelationshipQueryParser(Loader loader, QueryBuilder queryBuilder, Introspector obj) throws UnsupportedEncodingException, AAIException {
- super(loader, queryBuilder);
- this.relationship = obj;
- this.modelType = obj.getModelType();
- initBeans();
- RelationshipToURI rToUri = new RelationshipToURI(loader, obj);
- this.uri = rToUri.getUri();
- URIParser parser = new URIParser(loader, uri);
- parser.parse(this);
- }
+ /**
+ * Instantiates a new relationship query parser.
+ *
+ * @param loader the loader
+ * @param queryBuilder the query builder
+ * @param obj the obj
+ * @throws UnsupportedEncodingException the unsupported encoding exception
+ * @throws AAIException the AAI exception
+ */
+ public RelationshipQueryParser(Loader loader, QueryBuilder queryBuilder, Introspector obj)
+ throws UnsupportedEncodingException, AAIException {
+ super(loader, queryBuilder);
+ this.relationship = obj;
+ this.modelType = obj.getModelType();
+ initBeans();
+ RelationshipToURI rToUri = new RelationshipToURI(loader, obj);
+ this.uri = rToUri.getUri();
+ URIParser parser = new URIParser(loader, uri);
+ parser.parse(this);
+ }
- private void initBeans() {
- ApplicationContext ctx = SpringContextAware.getApplicationContext();
- if (ctx == null) {
- logger.warn("Unable to retrieve the spring context");
- } else {
- EdgeIngestor ei = ctx.getBean(EdgeIngestor.class);
- this.edgeRules = ei;
- }
- }
+ private void initBeans() {
+ ApplicationContext ctx = SpringContextAware.getApplicationContext();
+ if (ctx == null) {
+ logger.warn("Unable to retrieve the spring context");
+ } else {
+ EdgeIngestor ei = ctx.getBean(EdgeIngestor.class);
+ this.edgeRules = ei;
+ }
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/parsers/query/TraversalStrategy.java b/aai-core/src/main/java/org/onap/aai/parsers/query/TraversalStrategy.java
index 64f8eebb..a0311c70 100644
--- a/aai-core/src/main/java/org/onap/aai/parsers/query/TraversalStrategy.java
+++ b/aai-core/src/main/java/org/onap/aai/parsers/query/TraversalStrategy.java
@@ -17,65 +17,65 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.parsers.query;
+import java.io.UnsupportedEncodingException;
+import java.net.URI;
+
+import javax.ws.rs.core.MultivaluedMap;
+
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.introspection.Introspector;
import org.onap.aai.introspection.Loader;
import org.onap.aai.query.builder.QueryBuilder;
-import javax.ws.rs.core.MultivaluedMap;
-import java.io.UnsupportedEncodingException;
-import java.net.URI;
-
/**
* The Class TraversalStrategy.
*/
public class TraversalStrategy extends QueryParserStrategy {
+ /**
+ * Instantiates a new traversal strategy.
+ *
+ * @param loader the loader
+ * @param builder the builder
+ */
+ public TraversalStrategy(Loader loader, QueryBuilder builder) {
+ super(loader, builder);
+ }
- /**
- * Instantiates a new traversal strategy.
- *
- * @param loader the loader
- * @param builder the builder
- */
- public TraversalStrategy(Loader loader, QueryBuilder builder) {
- super(loader, builder);
- }
-
- /**
- * @{inheritDoc}
- */
- @Override
- public QueryParser buildURIParser(URI uri) throws UnsupportedEncodingException, AAIException {
- return new LegacyQueryParser(loader, builder, uri);
- }
-
- /**
- * @{inheritDoc}
- */
- @Override
- public QueryParser buildRelationshipParser(Introspector obj) throws UnsupportedEncodingException, AAIException {
- return new RelationshipQueryParser(loader, builder, obj);
- }
+ /**
+ * @{inheritDoc}
+ */
+ @Override
+ public QueryParser buildURIParser(URI uri) throws UnsupportedEncodingException, AAIException {
+ return new LegacyQueryParser(loader, builder, uri);
+ }
- /**
- * @{inheritDoc}
- */
- @Override
- public QueryParser buildURIParser(URI uri, MultivaluedMap<String, String> queryParams)
- throws UnsupportedEncodingException, AAIException {
- return new LegacyQueryParser(loader, builder, uri, queryParams);
- }
+ /**
+ * @{inheritDoc}
+ */
+ @Override
+ public QueryParser buildRelationshipParser(Introspector obj) throws UnsupportedEncodingException, AAIException {
+ return new RelationshipQueryParser(loader, builder, obj);
+ }
- /**
- * @{inheritDoc}
- */
- @Override
- public QueryParser buildObjectNameParser(String objName) {
- return new ObjectNameQueryParser(loader, builder, objName);
- }
+ /**
+ * @{inheritDoc}
+ */
+ @Override
+ public QueryParser buildURIParser(URI uri, MultivaluedMap<String, String> queryParams)
+ throws UnsupportedEncodingException, AAIException {
+ return new LegacyQueryParser(loader, builder, uri, queryParams);
+ }
+ /**
+ * @{inheritDoc}
+ */
+ @Override
+ public QueryParser buildObjectNameParser(String objName) {
+ return new ObjectNameQueryParser(loader, builder, objName);
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/parsers/query/UniqueRelationshipQueryParser.java b/aai-core/src/main/java/org/onap/aai/parsers/query/UniqueRelationshipQueryParser.java
index f7f27053..126272a8 100644
--- a/aai-core/src/main/java/org/onap/aai/parsers/query/UniqueRelationshipQueryParser.java
+++ b/aai-core/src/main/java/org/onap/aai/parsers/query/UniqueRelationshipQueryParser.java
@@ -17,40 +17,41 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.parsers.query;
+import java.io.UnsupportedEncodingException;
+
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.introspection.Introspector;
import org.onap.aai.introspection.Loader;
import org.onap.aai.parsers.relationship.RelationshipToURI;
import org.onap.aai.query.builder.QueryBuilder;
-import java.io.UnsupportedEncodingException;
-
/**
* The Class UniqueRelationshipQueryParser.
*/
public class UniqueRelationshipQueryParser extends UniqueURIQueryParser {
+ /**
+ * Instantiates a new unique relationship query parser.
+ *
+ * @param loader the loader
+ * @param queryBuilder the query builder
+ * @param obj the obj
+ * @throws UnsupportedEncodingException the unsupported encoding exception
+ * @throws IllegalArgumentException the illegal argument exception
+ * @throws AAIException the AAI exception
+ */
+ public UniqueRelationshipQueryParser(Loader loader, QueryBuilder queryBuilder, Introspector obj)
+ throws UnsupportedEncodingException, IllegalArgumentException, AAIException {
+ super(loader, queryBuilder);
+ RelationshipToURI rToUri = new RelationshipToURI(loader, obj);
+ UniqueURIQueryParser parser = new UniqueURIQueryParser(loader, queryBuilder, rToUri.getUri());
+ this.containerResource = parser.getContainerType();
+ this.resultResource = parser.getResultType();
+ this.queryBuilder = parser.getQueryBuilder();
+ this.parentQueryBuilder = parser.getParentQueryBuilder();
+ }
- /**
- * Instantiates a new unique relationship query parser.
- *
- * @param loader the loader
- * @param queryBuilder the query builder
- * @param obj the obj
- * @throws UnsupportedEncodingException the unsupported encoding exception
- * @throws IllegalArgumentException the illegal argument exception
- * @throws AAIException the AAI exception
- */
- public UniqueRelationshipQueryParser(Loader loader, QueryBuilder queryBuilder, Introspector obj) throws UnsupportedEncodingException, IllegalArgumentException, AAIException {
- super(loader, queryBuilder);
- RelationshipToURI rToUri = new RelationshipToURI(loader, obj);
- UniqueURIQueryParser parser = new UniqueURIQueryParser(loader, queryBuilder, rToUri.getUri());
- this.containerResource = parser.getContainerType();
- this.resultResource = parser.getResultType();
- this.queryBuilder = parser.getQueryBuilder();
- this.parentQueryBuilder = parser.getParentQueryBuilder();
- }
-
}
diff --git a/aai-core/src/main/java/org/onap/aai/parsers/query/UniqueStrategy.java b/aai-core/src/main/java/org/onap/aai/parsers/query/UniqueStrategy.java
index 5712158a..16403c00 100644
--- a/aai-core/src/main/java/org/onap/aai/parsers/query/UniqueStrategy.java
+++ b/aai-core/src/main/java/org/onap/aai/parsers/query/UniqueStrategy.java
@@ -17,64 +17,65 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.parsers.query;
+import java.io.UnsupportedEncodingException;
+import java.net.URI;
+
+import javax.ws.rs.core.MultivaluedMap;
+
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.introspection.Introspector;
import org.onap.aai.introspection.Loader;
import org.onap.aai.query.builder.QueryBuilder;
-import javax.ws.rs.core.MultivaluedMap;
-import java.io.UnsupportedEncodingException;
-import java.net.URI;
-
/**
* The Class UniqueStrategy.
*/
public class UniqueStrategy extends QueryParserStrategy {
-
+ /**
+ * Instantiates a new unique strategy.
+ *
+ * @param loader the loader
+ * @param builder the builder
+ */
+ public UniqueStrategy(Loader loader, QueryBuilder builder) {
+ super(loader, builder);
+ }
+
+ /**
+ * @{inheritDoc}
+ */
+ @Override
+ public QueryParser buildURIParser(URI uri)
+ throws UnsupportedEncodingException, IllegalArgumentException, AAIException {
+ return new UniqueURIQueryParser(loader, builder, uri);
+ }
- /**
- * Instantiates a new unique strategy.
- *
- * @param loader the loader
- * @param builder the builder
- */
- public UniqueStrategy(Loader loader, QueryBuilder builder) {
- super(loader, builder);
- }
-
- /**
- * @{inheritDoc}
- */
- @Override
- public QueryParser buildURIParser(URI uri) throws UnsupportedEncodingException, IllegalArgumentException, AAIException {
- return new UniqueURIQueryParser(loader, builder, uri);
- }
-
- /**
- * @{inheritDoc}
- */
- @Override
- public QueryParser buildRelationshipParser(Introspector obj) throws UnsupportedEncodingException, AAIException {
- return new UniqueRelationshipQueryParser(loader, builder, obj);
- }
+ /**
+ * @{inheritDoc}
+ */
+ @Override
+ public QueryParser buildRelationshipParser(Introspector obj) throws UnsupportedEncodingException, AAIException {
+ return new UniqueRelationshipQueryParser(loader, builder, obj);
+ }
- /**
- * @{inheritDoc}
- */
- @Override
- public QueryParser buildURIParser(URI uri, MultivaluedMap<String, String> queryParams)
- throws UnsupportedEncodingException, AAIException {
- return new LegacyQueryParser(loader, builder, uri, queryParams);
- }
+ /**
+ * @{inheritDoc}
+ */
+ @Override
+ public QueryParser buildURIParser(URI uri, MultivaluedMap<String, String> queryParams)
+ throws UnsupportedEncodingException, AAIException {
+ return new LegacyQueryParser(loader, builder, uri, queryParams);
+ }
- /**
- * @{inheritDoc}
- */
- @Override
- public QueryParser buildObjectNameParser(String objName) {
- return new ObjectNameQueryParser(loader, builder, objName);
- }
+ /**
+ * @{inheritDoc}
+ */
+ @Override
+ public QueryParser buildObjectNameParser(String objName) {
+ return new ObjectNameQueryParser(loader, builder, objName);
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/parsers/query/UniqueURIQueryParser.java b/aai-core/src/main/java/org/onap/aai/parsers/query/UniqueURIQueryParser.java
index 3f14eecb..33baa40a 100644
--- a/aai-core/src/main/java/org/onap/aai/parsers/query/UniqueURIQueryParser.java
+++ b/aai-core/src/main/java/org/onap/aai/parsers/query/UniqueURIQueryParser.java
@@ -17,8 +17,16 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.parsers.query;
+import java.io.UnsupportedEncodingException;
+import java.net.URI;
+
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.core.UriBuilder;
+
+import org.onap.aai.edges.enums.EdgeType;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.introspection.Introspector;
import org.onap.aai.introspection.Loader;
@@ -26,138 +34,131 @@ import org.onap.aai.parsers.uri.Parsable;
import org.onap.aai.parsers.uri.URIParser;
import org.onap.aai.parsers.uri.URIToDBKey;
import org.onap.aai.query.builder.QueryBuilder;
-import org.onap.aai.edges.enums.EdgeType;
-
-import javax.ws.rs.core.MultivaluedMap;
-import javax.ws.rs.core.UriBuilder;
-import java.io.UnsupportedEncodingException;
-import java.net.URI;
-
/**
* The Class UniqueURIQueryParser.
*/
public class UniqueURIQueryParser extends QueryParser implements Parsable {
-
- private URIToDBKey dbKeyParser = null;
-
- private Introspector previous = null;
-
- private boolean endsInContainer = false;
-
- private Introspector finalContainer = null;
-
- private String parentName = "";
-
- /**
- * Instantiates a new unique URI query parser.
- *
- * @param loader the loader
- * @param queryBuilder the query builder
- * @param uri the uri
- * @throws UnsupportedEncodingException the unsupported encoding exception
- * @throws IllegalArgumentException the illegal argument exception
- * @throws AAIException the AAI exception
- */
- public UniqueURIQueryParser(Loader loader, QueryBuilder queryBuilder, URI uri) throws UnsupportedEncodingException, IllegalArgumentException, AAIException {
- super(loader, queryBuilder, uri);
- URIParser parser = new URIParser(loader, uri);
- parser.parse(this);
-
- if (!endsInContainer) {
- this.dbKeyParser = new URIToDBKey(loader, uri);
- String dbKey = (String)dbKeyParser.getResult();
- queryBuilder.getVerticesByIndexedProperty("aai-unique-key", dbKey);
- queryBuilder.markParentBoundary();
-
- if (!(parentName.equals("") || parentName.equals(this.resultResource))) {
- URI parentUri = UriBuilder.fromPath(uri.getRawPath().substring(0, uri.getRawPath().indexOf(containerResource))).build();
- this.dbKeyParser = new URIToDBKey(loader, parentUri);
- this.parentQueryBuilder = queryBuilder.newInstance().getVerticesByIndexedProperty("aai-unique-key", (String)dbKeyParser.getResult());
- this.parentResourceType = parentName;
- }
- this.containerResource = "";
- } else {
- URI parentUri = UriBuilder.fromPath(uri.getRawPath().substring(0, uri.getRawPath().indexOf(this.finalContainer.getDbName()))).build();
- this.dbKeyParser = new URIToDBKey(loader, parentUri);
- String dbKey = (String)dbKeyParser.getResult();
- this.parentResourceType = parentName;
-
- if (!dbKey.equals("")) {
- queryBuilder.getVerticesByIndexedProperty("aai-unique-key", dbKey);
- queryBuilder.markParentBoundary();
- queryBuilder.createEdgeTraversal(EdgeType.TREE, previous, finalContainer);
-
- }
-
- queryBuilder.createContainerQuery(finalContainer);
-
-
- }
- }
-
-
- /**
- * Instantiates a new unique URI query parser.
- *
- * @param loader the loader
- * @param queryBuilder the query builder
- */
- public UniqueURIQueryParser(Loader loader, QueryBuilder queryBuilder) {
- super(loader, queryBuilder);
- }
-
- /**
- * @{inheritDoc}
- */
- @Override
- public void processNamespace(Introspector obj) {
-
- }
-
- /**
- * @{inheritDoc}
- */
- @Override
- public String getCloudRegionTransform() {
- return "add";
- }
-
- /**
- * @{inheritDoc}
- */
- @Override
- public boolean useOriginalLoader() {
- return false;
- }
-
-
- @Override
- public void processObject(Introspector obj, EdgeType type, MultivaluedMap<String, String> uriKeys)
- throws AAIException {
- this.resultResource = obj.getDbName();
- if (previous != null) {
- this.parentName = previous.getDbName();
- }
- this.previous = obj;
-
- }
-
-
- @Override
- public void processContainer(Introspector obj, EdgeType type, MultivaluedMap<String, String> uriKeys,
- boolean isFinalContainer) throws AAIException {
- this.containerResource = obj.getName();
- if (previous != null) {
- this.parentName = previous.getDbName();
- }
- if (isFinalContainer) {
- this.endsInContainer = true;
- this.resultResource = obj.getChildDBName();
-
- this.finalContainer = obj;
- }
- }
-
+ private URIToDBKey dbKeyParser = null;
+
+ private Introspector previous = null;
+
+ private boolean endsInContainer = false;
+
+ private Introspector finalContainer = null;
+
+ private String parentName = "";
+
+ /**
+ * Instantiates a new unique URI query parser.
+ *
+ * @param loader the loader
+ * @param queryBuilder the query builder
+ * @param uri the uri
+ * @throws UnsupportedEncodingException the unsupported encoding exception
+ * @throws IllegalArgumentException the illegal argument exception
+ * @throws AAIException the AAI exception
+ */
+ public UniqueURIQueryParser(Loader loader, QueryBuilder queryBuilder, URI uri)
+ throws UnsupportedEncodingException, IllegalArgumentException, AAIException {
+ super(loader, queryBuilder, uri);
+ URIParser parser = new URIParser(loader, uri);
+ parser.parse(this);
+
+ if (!endsInContainer) {
+ this.dbKeyParser = new URIToDBKey(loader, uri);
+ String dbKey = (String) dbKeyParser.getResult();
+ queryBuilder.getVerticesByIndexedProperty("aai-unique-key", dbKey);
+ queryBuilder.markParentBoundary();
+
+ if (!(parentName.equals("") || parentName.equals(this.resultResource))) {
+ URI parentUri = UriBuilder
+ .fromPath(uri.getRawPath().substring(0, uri.getRawPath().indexOf(containerResource))).build();
+ this.dbKeyParser = new URIToDBKey(loader, parentUri);
+ this.parentQueryBuilder = queryBuilder.newInstance().getVerticesByIndexedProperty("aai-unique-key",
+ (String) dbKeyParser.getResult());
+ this.parentResourceType = parentName;
+ }
+ this.containerResource = "";
+ } else {
+ URI parentUri = UriBuilder
+ .fromPath(uri.getRawPath().substring(0, uri.getRawPath().indexOf(this.finalContainer.getDbName())))
+ .build();
+ this.dbKeyParser = new URIToDBKey(loader, parentUri);
+ String dbKey = (String) dbKeyParser.getResult();
+ this.parentResourceType = parentName;
+
+ if (!dbKey.equals("")) {
+ queryBuilder.getVerticesByIndexedProperty("aai-unique-key", dbKey);
+ queryBuilder.markParentBoundary();
+ queryBuilder.createEdgeTraversal(EdgeType.TREE, previous, finalContainer);
+
+ }
+
+ queryBuilder.createContainerQuery(finalContainer);
+
+ }
+ }
+
+ /**
+ * Instantiates a new unique URI query parser.
+ *
+ * @param loader the loader
+ * @param queryBuilder the query builder
+ */
+ public UniqueURIQueryParser(Loader loader, QueryBuilder queryBuilder) {
+ super(loader, queryBuilder);
+ }
+
+ /**
+ * @{inheritDoc}
+ */
+ @Override
+ public void processNamespace(Introspector obj) {
+
+ }
+
+ /**
+ * @{inheritDoc}
+ */
+ @Override
+ public String getCloudRegionTransform() {
+ return "add";
+ }
+
+ /**
+ * @{inheritDoc}
+ */
+ @Override
+ public boolean useOriginalLoader() {
+ return false;
+ }
+
+ @Override
+ public void processObject(Introspector obj, EdgeType type, MultivaluedMap<String, String> uriKeys)
+ throws AAIException {
+ this.resultResource = obj.getDbName();
+ if (previous != null) {
+ this.parentName = previous.getDbName();
+ }
+ this.previous = obj;
+
+ }
+
+ @Override
+ public void processContainer(Introspector obj, EdgeType type, MultivaluedMap<String, String> uriKeys,
+ boolean isFinalContainer) throws AAIException {
+ this.containerResource = obj.getName();
+ if (previous != null) {
+ this.parentName = previous.getDbName();
+ }
+ if (isFinalContainer) {
+ this.endsInContainer = true;
+ this.resultResource = obj.getChildDBName();
+
+ this.finalContainer = obj;
+ }
+ }
+
}
diff --git a/aai-core/src/main/java/org/onap/aai/parsers/relationship/RelationshipToURI.java b/aai-core/src/main/java/org/onap/aai/parsers/relationship/RelationshipToURI.java
index 8cbed6d6..0b072b88 100644
--- a/aai-core/src/main/java/org/onap/aai/parsers/relationship/RelationshipToURI.java
+++ b/aai-core/src/main/java/org/onap/aai/parsers/relationship/RelationshipToURI.java
@@ -17,275 +17,285 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.parsers.relationship;
import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Optional;
+
+import javax.ws.rs.core.UriBuilder;
+
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.onap.aai.config.SpringContextAware;
import org.onap.aai.edges.EdgeIngestor;
+import org.onap.aai.edges.EdgeRule;
import org.onap.aai.edges.EdgeRuleQuery;
+import org.onap.aai.edges.enums.AAIDirection;
+import org.onap.aai.edges.enums.EdgeType;
import org.onap.aai.edges.exceptions.AmbiguousRuleChoiceException;
import org.onap.aai.edges.exceptions.EdgeRuleNotFoundException;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.introspection.*;
-import org.onap.aai.setup.SchemaVersions;
-
import org.onap.aai.introspection.exceptions.AAIUnknownObjectException;
import org.onap.aai.parsers.exceptions.AAIIdentityMapParseException;
import org.onap.aai.parsers.exceptions.AmbiguousMapAAIException;
import org.onap.aai.parsers.uri.URIParser;
import org.onap.aai.schema.enums.ObjectMetadata;
-import org.onap.aai.edges.enums.AAIDirection;
-import org.onap.aai.edges.EdgeRule;
-import org.onap.aai.edges.enums.EdgeType;
+import org.onap.aai.setup.SchemaVersions;
import org.springframework.context.ApplicationContext;
-import javax.ws.rs.core.UriBuilder;
-import java.io.UnsupportedEncodingException;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Optional;
-
/**
* The Class RelationshipToURI.
*/
public class RelationshipToURI {
- private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(RelationshipToURI.class);
-
- private Introspector relationship = null;
-
- private Loader loader = null;
-
- private ModelType modelType = null;
-
- private EdgeIngestor edgeRules = null;
+ private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(RelationshipToURI.class);
+
+ private Introspector relationship = null;
+
+ private Loader loader = null;
+
+ private ModelType modelType = null;
+
+ private EdgeIngestor edgeRules = null;
+
+ private URI uri = null;
+
+ private SchemaVersions schemaVersions;
+
+ /**
+ * Instantiates a new relationship to URI.
+ *
+ * @param loader the loader
+ * @param relationship the relationship
+ * @throws UnsupportedEncodingException the unsupported encoding exception
+ * @throws AAIException the AAI exception
+ */
+ public RelationshipToURI(Loader loader, Introspector relationship)
+ throws UnsupportedEncodingException, AAIException {
+ this.relationship = relationship;
+ this.modelType = relationship.getModelType();
+ this.loader = loader;
+ this.initEdgeIngestor();
+ this.parse();
+
+ }
+
+ protected void initEdgeIngestor() {
+ // TODO proper spring wiring, but that requires a lot of refactoring so for now we have this
+ ApplicationContext ctx = SpringContextAware.getApplicationContext();
+ edgeRules = ctx.getBean(EdgeIngestor.class);
+ schemaVersions = (SchemaVersions) ctx.getBean("schemaVersions");
+ }
+
+ /**
+ * Parses the.
+ *
+ * @throws
+ *
+ * @throws UnsupportedEncodingException the unsupported encoding exception
+ * @throws AAIException the AAI exception
+ */
+ protected void parse() throws AAIException {
+ String relatedLink = (String) relationship.getValue("related-link");
+ Optional<URI> result;
+ try {
+ if (loader.getVersion().compareTo(schemaVersions.getRelatedLinkVersion()) >= 0) {
+ result = processRelatedLink(relatedLink);
+ if (!result.isPresent()) {
+ result = processRelationshipData();
+ }
+ } else {
+ result = processRelationshipData();
+ if (!result.isPresent()) {
+ result = processRelatedLink(relatedLink);
+ }
+ }
+ if (result.isPresent()) {
+ this.uri = result.get();
+ } else {
+ throw new AAIIdentityMapParseException("nothing to parse");
+ }
+ } catch (AAIException e) {
+ throw e;
+ } catch (Exception e) {
+ throw new AAIIdentityMapParseException("Could not parse relationship-list object: " + e.getMessage(), e);
+ }
+
+ }
+
+ private Optional<URI> processRelationshipData() throws AAIException, UnsupportedEncodingException {
+ Optional<URI> result = Optional.empty();
+ StringBuilder uriBuilder = new StringBuilder();
+ List<Object> data = (List<Object>) relationship.getValue("relationship-data");
+ Introspector wrapper;
+ String key;
+ String value;
+ String objectType;
+ String propertyName;
+ String topLevelType = null;
+ String[] split;
+ HashMap<String, Introspector> map = new HashMap<>();
+ for (Object datum : data) {
+ wrapper = IntrospectorFactory.newInstance(modelType, datum);
+ key = (String) wrapper.getValue("relationship-key");
+ value = (String) wrapper.getValue("relationship-value");
+ split = key.split("\\.");
+ if (split == null || split.length != 2) {
+ throw new AAIIdentityMapParseException(
+ "incorrect format for key must be of the form {node-type}.{property-name}");
+ }
+ // check node name ok
+ // check prop name ok
+ objectType = split[0];
+ propertyName = split[1];
+
+ try {
+ Introspector wrappedObj = loader.introspectorFromName(objectType);
+
+ if (!wrappedObj.hasProperty(propertyName)) {
+ throw new AAIIdentityMapParseException("invalid property name in map: " + propertyName);
+ }
+ if (map.containsKey(objectType)) {
+ wrappedObj = map.get(objectType);
+ } else {
+ map.put(objectType, wrappedObj);
+ }
+ if (wrappedObj.getValue(propertyName) == null) {
+ wrappedObj.setValue(propertyName, value);
+ } else {
+ throw new AmbiguousMapAAIException(
+ "cannot determine where key/value goes: " + propertyName + "/" + value);
+ }
- private URI uri = null;
+ if (wrappedObj.getMetadata(ObjectMetadata.NAMESPACE) != null) {
+ if (topLevelType == null) {
+ topLevelType = objectType;
+ } else if (!topLevelType.equals(objectType)) {
+ throw new AmbiguousMapAAIException(
+ "found two top level nodes of different types: " + topLevelType + " and " + objectType);
+ }
+ }
+ } catch (AAIUnknownObjectException e) {
+ throw new AAIIdentityMapParseException("invalid object name in map: " + objectType, e);
+ }
- private SchemaVersions schemaVersions;
-
- /**
- * Instantiates a new relationship to URI.
- *
- * @param loader the loader
- * @param relationship the relationship
- * @throws UnsupportedEncodingException the unsupported encoding exception
- * @throws AAIException the AAI exception
- */
- public RelationshipToURI(Loader loader, Introspector relationship) throws UnsupportedEncodingException, AAIException {
- this.relationship = relationship;
- this.modelType = relationship.getModelType();
- this.loader = loader;
- this.initEdgeIngestor();
- this.parse();
-
- }
+ }
+ if (!map.isEmpty()) {
+ String startType = (String) relationship.getValue("related-to");
+ List<String> nodeTypes = new ArrayList<>();
+ nodeTypes.addAll(map.keySet());
- protected void initEdgeIngestor() {
- //TODO proper spring wiring, but that requires a lot of refactoring so for now we have this
- ApplicationContext ctx = SpringContextAware.getApplicationContext();
- edgeRules = ctx.getBean(EdgeIngestor.class);
- schemaVersions = (SchemaVersions) ctx.getBean("schemaVersions");
- }
+ String displacedType;
+ for (int i = 0; i < nodeTypes.size(); i++) {
+ if (nodeTypes.get(i).equals(startType)) {
+ displacedType = nodeTypes.set(nodeTypes.size() - 1, startType);
+ nodeTypes.set(i, displacedType);
+ break;
+ }
+ }
+ sortRelationships(nodeTypes, startType, 1);
+ int startTypeIndex = nodeTypes.indexOf(startType);
+ int topLevelIndex = 0;
+ if (topLevelType != null) {
+ topLevelIndex = nodeTypes.indexOf(topLevelType);
+ }
+ // remove additional types not needed if they are there
+ List<String> nodeTypesSubList = nodeTypes;
+ if (topLevelIndex != 0) {
+ nodeTypesSubList = nodeTypes.subList(topLevelIndex, startTypeIndex + 1);
+ }
+ for (String type : nodeTypesSubList) {
+ uriBuilder.append(map.get(type).getURI());
+ }
+ if (!nodeTypesSubList.isEmpty()) {
+ result = Optional.of(UriBuilder.fromPath(uriBuilder.toString()).build());
+ }
+ }
+ return result;
+ }
- /**
- * Parses the.
- * @throws
- *
- * @throws UnsupportedEncodingException the unsupported encoding exception
- * @throws AAIException the AAI exception
- */
- protected void parse() throws AAIException {
- String relatedLink = (String)relationship.getValue("related-link");
- Optional<URI> result;
- try {
- if (loader.getVersion().compareTo(schemaVersions.getRelatedLinkVersion()) >= 0) {
- result = processRelatedLink(relatedLink);
- if (!result.isPresent()) {
- result = processRelationshipData();
- }
- } else {
- result = processRelationshipData();
- if (!result.isPresent()) {
- result = processRelatedLink(relatedLink);
- }
- }
- if (result.isPresent()) {
- this.uri = result.get();
- } else {
- throw new AAIIdentityMapParseException("nothing to parse");
- }
- } catch (AAIException e) {
- throw e;
- } catch (Exception e) {
- throw new AAIIdentityMapParseException("Could not parse relationship-list object: " + e.getMessage(), e);
- }
+ private Optional<URI> processRelatedLink(String relatedLink)
+ throws URISyntaxException, UnsupportedEncodingException, AAIIdentityMapParseException {
+ Optional<URI> result = Optional.empty();
+ if (relatedLink != null) {
+ URI resultUri = new URI(relatedLink);
+ String path = resultUri.toString();
+ resultUri = UriBuilder.fromPath(resultUri.getRawPath()).build();
+ URIParser uriParser = new URIParser(this.loader, resultUri);
+ try {
+ uriParser.validate();
+ } catch (AAIException e) {
+ throw new AAIIdentityMapParseException("related link is invalid: " + relatedLink, e);
+ }
+ result = Optional.of(resultUri);
+ }
- }
+ return result;
+ }
- private Optional<URI> processRelationshipData() throws AAIException, UnsupportedEncodingException {
- Optional<URI> result = Optional.empty();
- StringBuilder uriBuilder = new StringBuilder();
- List<Object> data = (List<Object>)relationship.getValue("relationship-data");
- Introspector wrapper;
- String key;
- String value;
- String objectType;
- String propertyName;
- String topLevelType = null;
- String[] split;
- HashMap<String, Introspector> map = new HashMap<>();
- for (Object datum : data) {
- wrapper = IntrospectorFactory.newInstance(modelType, datum);
- key = (String)wrapper.getValue("relationship-key");
- value = (String)wrapper.getValue("relationship-value");
- split = key.split("\\.");
- if (split == null || split.length != 2) {
- throw new AAIIdentityMapParseException("incorrect format for key must be of the form {node-type}.{property-name}");
- }
- //check node name ok
- //check prop name ok
- objectType = split[0];
- propertyName = split[1];
+ /**
+ * Sort relationships.
+ *
+ * @param data the data
+ * @param startType the start type
+ * @param i the i
+ * @return true, if successful
+ * @throws AAIException
+ */
+ private boolean sortRelationships(List<String> data, String startType, int i) throws AAIException {
- try {
- Introspector wrappedObj = loader.introspectorFromName(objectType);
+ if (i == data.size()) {
+ return true;
+ }
+ int j;
+ String objectType;
+ String displacedObject;
+ EdgeRule rule;
+ Direction direction;
+ for (j = (data.size() - i) - 1; j >= 0; j--) {
+ objectType = data.get(j);
+ try {
+ rule = edgeRules
+ .getRule(new EdgeRuleQuery.Builder(startType, objectType).edgeType(EdgeType.TREE).build());
+ direction = rule.getDirection();
+ if (direction != null) {
+ if ((rule.getContains().equals(AAIDirection.OUT.toString()) && direction.equals(Direction.IN))
+ || (rule.getContains().equals(AAIDirection.IN.toString())
+ && direction.equals(Direction.OUT))) {
+ displacedObject = data.set((data.size() - i) - 1, data.get(j));
+ data.set(j, displacedObject);
+ if (sortRelationships(data, objectType, i + 1)) {
+ return true;
+ } else {
+ // continue to process
+ }
+ }
+ }
+ } catch (AAIException | EdgeRuleNotFoundException | AmbiguousRuleChoiceException e) {
+ // ignore exceptions generated
+ continue;
+ }
+ }
- if (!wrappedObj.hasProperty(propertyName)) {
- throw new AAIIdentityMapParseException("invalid property name in map: " + propertyName);
- }
- if (map.containsKey(objectType)) {
- wrappedObj = map.get(objectType);
- } else {
- map.put(objectType, wrappedObj);
- }
- if (wrappedObj.getValue(propertyName) == null) {
- wrappedObj.setValue(propertyName, value);
- } else {
- throw new AmbiguousMapAAIException("cannot determine where key/value goes: " + propertyName + "/" + value);
- }
-
- if (wrappedObj.getMetadata(ObjectMetadata.NAMESPACE) != null) {
- if (topLevelType == null) {
- topLevelType = objectType;
- } else if (!topLevelType.equals(objectType)){
- throw new AmbiguousMapAAIException("found two top level nodes of different types: " + topLevelType + " and " + objectType);
- }
- }
- } catch (AAIUnknownObjectException e) {
- throw new AAIIdentityMapParseException("invalid object name in map: " + objectType, e);
- }
-
- }
- if (!map.isEmpty()) {
- String startType = (String)relationship.getValue("related-to");
- List<String> nodeTypes = new ArrayList<>();
- nodeTypes.addAll(map.keySet());
-
- String displacedType;
- for (int i = 0; i < nodeTypes.size(); i++) {
- if (nodeTypes.get(i).equals(startType)) {
- displacedType = nodeTypes.set(nodeTypes.size() - 1, startType);
- nodeTypes.set(i, displacedType);
- break;
- }
- }
- sortRelationships(nodeTypes, startType, 1);
- int startTypeIndex = nodeTypes.indexOf(startType);
- int topLevelIndex = 0;
- if (topLevelType != null) {
- topLevelIndex = nodeTypes.indexOf(topLevelType);
- }
- //remove additional types not needed if they are there
- List<String> nodeTypesSubList = nodeTypes;
- if (topLevelIndex != 0) {
- nodeTypesSubList = nodeTypes.subList(topLevelIndex, startTypeIndex+1);
- }
- for (String type : nodeTypesSubList) {
- uriBuilder.append(map.get(type).getURI());
- }
- if (!nodeTypesSubList.isEmpty()) {
- result = Optional.of(UriBuilder.fromPath(uriBuilder.toString()).build());
- }
- }
- return result;
- }
+ return false;
+ }
- private Optional<URI> processRelatedLink(String relatedLink) throws URISyntaxException, UnsupportedEncodingException, AAIIdentityMapParseException {
- Optional<URI> result = Optional.empty();
- if (relatedLink != null) {
- URI resultUri = new URI(relatedLink);
- String path = resultUri.toString();
- resultUri = UriBuilder.fromPath(resultUri.getRawPath()).build();
- URIParser uriParser = new URIParser(this.loader, resultUri);
- try {
- uriParser.validate();
- } catch (AAIException e) {
- throw new AAIIdentityMapParseException("related link is invalid: " + relatedLink, e);
- }
- result = Optional.of(resultUri);
- }
-
- return result;
- }
-
- /**
- * Sort relationships.
- *
- * @param data the data
- * @param startType the start type
- * @param i the i
- * @return true, if successful
- * @throws AAIException
- */
- private boolean sortRelationships(List<String> data, String startType, int i) throws AAIException {
-
- if (i == data.size()) {
- return true;
- }
- int j;
- String objectType;
- String displacedObject;
- EdgeRule rule;
- Direction direction;
- for (j = (data.size() - i) - 1; j >= 0; j--) {
- objectType = data.get(j);
- try {
- rule = edgeRules.getRule(new EdgeRuleQuery.Builder(startType, objectType).edgeType(EdgeType.TREE).build());
- direction = rule.getDirection();
- if (direction != null) {
- if ((rule.getContains().equals(AAIDirection.OUT.toString()) && direction.equals(Direction.IN)) || (rule.getContains().equals(AAIDirection.IN.toString()) && direction.equals(Direction.OUT))) {
- displacedObject = data.set((data.size() - i) - 1, data.get(j));
- data.set(j, displacedObject);
- if (sortRelationships(data, objectType, i+1)) {
- return true;
- } else {
- //continue to process
- }
- }
- }
- } catch (AAIException | EdgeRuleNotFoundException | AmbiguousRuleChoiceException e ) {
- //ignore exceptions generated
- continue;
- }
- }
-
+ /**
+ * Gets the uri.
+ *
+ * @return the uri
+ */
+ public URI getUri() {
+ return uri;
+ }
- return false;
- }
-
- /**
- * Gets the uri.
- *
- * @return the uri
- */
- public URI getUri() {
- return uri;
- }
-
}
diff --git a/aai-core/src/main/java/org/onap/aai/parsers/uri/Parsable.java b/aai-core/src/main/java/org/onap/aai/parsers/uri/Parsable.java
index f35b4fde..3bc40fd3 100644
--- a/aai-core/src/main/java/org/onap/aai/parsers/uri/Parsable.java
+++ b/aai-core/src/main/java/org/onap/aai/parsers/uri/Parsable.java
@@ -17,55 +17,58 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.parsers.uri;
+import javax.ws.rs.core.MultivaluedMap;
+
+import org.onap.aai.edges.enums.EdgeType;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.introspection.Introspector;
-import org.onap.aai.edges.enums.EdgeType;
-
-import javax.ws.rs.core.MultivaluedMap;
/**
* The Interface Parsable.
*/
public interface Parsable {
- /**
- *
- * @param obj
- * @param type
- * @param uriKeys
- * @throws AAIException
- */
- void processObject(Introspector obj, EdgeType type, MultivaluedMap<String, String> uriKeys) throws AAIException;
- /**
- * Process container.
- *
- * @param obj the obj
- * @param uriKeys the uri keys
- * @param isFinalContainer the is final container
- * @throws AAIException the AAI exception
- */
- void processContainer(Introspector obj, EdgeType type, MultivaluedMap<String, String> uriKeys, boolean isFinalContainer) throws AAIException;
+ /**
+ *
+ * @param obj
+ * @param type
+ * @param uriKeys
+ * @throws AAIException
+ */
+ void processObject(Introspector obj, EdgeType type, MultivaluedMap<String, String> uriKeys) throws AAIException;
+
+ /**
+ * Process container.
+ *
+ * @param obj the obj
+ * @param uriKeys the uri keys
+ * @param isFinalContainer the is final container
+ * @throws AAIException the AAI exception
+ */
+ void processContainer(Introspector obj, EdgeType type, MultivaluedMap<String, String> uriKeys,
+ boolean isFinalContainer) throws AAIException;
+
+ /**
+ * Process namespace.
+ *
+ * @param obj the obj
+ */
+ void processNamespace(Introspector obj);
- /**
- * Process namespace.
- *
- * @param obj the obj
- */
- void processNamespace(Introspector obj);
+ /**
+ * Gets the cloud region transform.
+ *
+ * @return the cloud region transform
+ */
+ String getCloudRegionTransform();
- /**
- * Gets the cloud region transform.
- *
- * @return the cloud region transform
- */
- String getCloudRegionTransform();
-
- /**
- * Use original loader.
- *
- * @return true, if successful
- */
- boolean useOriginalLoader();
+ /**
+ * Use original loader.
+ *
+ * @return true, if successful
+ */
+ boolean useOriginalLoader();
}
diff --git a/aai-core/src/main/java/org/onap/aai/parsers/uri/URIParser.java b/aai-core/src/main/java/org/onap/aai/parsers/uri/URIParser.java
index 5aece21c..d8f401ee 100644
--- a/aai-core/src/main/java/org/onap/aai/parsers/uri/URIParser.java
+++ b/aai-core/src/main/java/org/onap/aai/parsers/uri/URIParser.java
@@ -17,258 +17,263 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.parsers.uri;
+import java.io.UnsupportedEncodingException;
+import java.net.URI;
+import java.util.Set;
+
+import javax.ws.rs.core.MultivaluedHashMap;
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.core.UriBuilder;
+
import org.onap.aai.config.SpringContextAware;
+import org.onap.aai.edges.enums.EdgeType;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.introspection.Introspector;
import org.onap.aai.introspection.Loader;
import org.onap.aai.introspection.LoaderFactory;
-import org.onap.aai.setup.SchemaVersion;
import org.onap.aai.logging.ErrorLogHelper;
import org.onap.aai.parsers.exceptions.DoesNotStartWithValidNamespaceException;
import org.onap.aai.rest.RestTokens;
import org.onap.aai.schema.enums.ObjectMetadata;
-import org.onap.aai.edges.enums.EdgeType;
+import org.onap.aai.setup.SchemaVersion;
import org.onap.aai.util.AAIConfig;
import org.springframework.web.util.UriUtils;
-import javax.ws.rs.core.MultivaluedHashMap;
-import javax.ws.rs.core.MultivaluedMap;
-import javax.ws.rs.core.UriBuilder;
-import java.io.UnsupportedEncodingException;
-import java.net.URI;
-import java.util.Set;
-
-
/**
* The Class URIParser.
*/
public class URIParser {
-
- private URI uri = null;
-
- protected Loader loader = null;
-
- protected Loader originalLoader = null;
-
- private URI originalURI = null;
-
- private MultivaluedMap<String, String> queryParams = null;
-
-
- /**
- * Instantiates a new URI parser.
- *
- * @param loader the loader
- * @param uri the uri
- */
- public URIParser(Loader loader, URI uri) {
- this.uri = uri;
-
- this.originalLoader = loader;
- //Load the latest version because we need it for cloud region
-
- this.loader = loader;
- }
-
- /**
- * Instantiates a new URI parser.
- *
- * @param loader the loader
- * @param uri the uri
- * @param queryParams the query params
- */
- public URIParser(Loader loader, URI uri, MultivaluedMap<String, String> queryParams) {
- this(loader, uri);
- this.queryParams = queryParams;
- }
-
- public Loader getLoader() {
-
- return this.loader;
-
- }
-
- /**
- * Gets the original URI.
- *
- * @return the original URI
- */
- public URI getOriginalURI() {
- return this.originalURI;
- }
-
- /**
- * Parses the.
- *
- * @param p the p
- * @throws UnsupportedEncodingException the unsupported encoding exception
- * @throws AAIException the AAI exception
- */
- public void parse(Parsable p) throws UnsupportedEncodingException, AAIException {
- try {
- boolean isRelative = false;
- uri = this.trimURI(uri);
- uri = handleCloudRegion(p.getCloudRegionTransform(), uri);
- if (p.useOriginalLoader()) {
- this.loader = this.originalLoader;
- }
- this.originalURI = UriBuilder.fromPath(uri.getRawPath()).build();
- if (uri.getRawPath().startsWith("./")) {
- uri = new URI(uri.getRawPath().replaceFirst("\\./", ""));
- isRelative = true;
- }
- String[] parts = uri.getRawPath().split("/");
- Introspector validNamespaces = loader.introspectorFromName("inventory");
- Set<String> keys = null;
- String part = "";
- Introspector previousObj = null;
- EdgeType type = EdgeType.TREE;
- for (int i = 0; i < parts.length;) {
- part = parts[i];
- Introspector introspector = null;
- if (part.equals(RestTokens.COUSIN.toString())) {
- if (i == parts.length-1) {
- throw new AAIException("AAI_3000", uri + " not a valid path. Cannot end in " + RestTokens.COUSIN);
- }
- introspector = loader.introspectorFromName(parts[i+1]);
- if(null == previousObj) {
- throw new AAIException("AAI_3001");
- }
- if (previousObj.isContainer() && introspector.isContainer()) {
- throw new AAIException("AAI_3000", uri + " not a valid path. Cannot chain plurals together");
- }
- MultivaluedMap<String, String> uriKeys = new MultivaluedHashMap<>();
- if (i == parts.length-2 && queryParams != null) {
- Set<String> queryKeys = queryParams.keySet();
- for (String key : queryKeys) {
- uriKeys.put(key, queryParams.get(key));
-
- }
- }
- if (introspector.isContainer()) {
- boolean isFinalContainer = i == parts.length-2;
- /*
- * Related-to could be COUSIN OR TREE and in some cases BOTH. So Let EdgeRuleBuilder use all the edgeTypes
- */
- p.processContainer(introspector, EdgeType.ALL, uriKeys, isFinalContainer);
- }
- previousObj = introspector;
- type = EdgeType.ALL;
- i+=2;
- continue;
- }
- introspector = loader.introspectorFromName(part);
- if (introspector != null) {
-
- //previous has current as property
- if (previousObj != null && !previousObj.hasChild(introspector) && !previousObj.getDbName().equals("nodes")) {
- throw new AAIException("AAI_3001", uri + " not a valid path. " + part + " not valid");
- } else if (previousObj == null) {
- String abstractType = introspector.getMetadata(ObjectMetadata.ABSTRACT);
- if (abstractType == null) {
- abstractType = "";
- }
- //first time through, make sure it starts from a namespace
- //ignore abstract types
- if (!isRelative && !abstractType.equals("true") && !validNamespaces.hasChild(introspector)) {
- throw new DoesNotStartWithValidNamespaceException( uri + " not a valid path. It does not start from a valid namespace");
- }
- }
-
- keys = introspector.getKeys();
- if (keys.size() > 0) {
- MultivaluedMap<String, String> uriKeys = new MultivaluedHashMap<>();
- i++;
- if (i == parts.length && queryParams != null) {
- Set<String> queryKeys = queryParams.keySet();
- for (String key : queryKeys) {
- uriKeys.put(key, queryParams.get(key));
- }
- } else {
- for (String key : keys) {
- part = UriUtils.decode(parts[i], "UTF-8");
-
- introspector.setValue(key, part);
-
- //skip this for further processing
- i++;
- }
- }
-
- p.processObject(introspector, type, uriKeys);
- type = EdgeType.TREE;
- } else if (introspector.isContainer()) {
- boolean isFinalContainer = i == parts.length-1;
- MultivaluedMap<String, String> uriKeys = new MultivaluedHashMap<>();
-
- if (isFinalContainer && queryParams != null) {
- Set<String> queryKeys = queryParams.keySet();
- for (String key : queryKeys) {
- uriKeys.put(key, queryParams.get(key));
-
- }
- }
- p.processContainer(introspector, type, uriKeys, isFinalContainer);
- i++;
- } else {
- p.processNamespace(introspector);
- //namespace case
- i++;
- }
- previousObj = introspector;
- } else {
- //invalid item found should log
- //original said bad path
- throw new AAIException("AAI_3001", "invalid item found in path: " + part);
- }
- }
- } catch (AAIException e) {
- throw e;
- } catch (Exception e) {
- throw new AAIException("AAI_3001", e);
- }
- }
-
- public boolean validate() throws UnsupportedEncodingException, AAIException {
- this.parse(new URIValidate());
- return true;
- }
- /**
- * Handle cloud region.
- *
- * @param action the action
- * @param uri the uri
- * @return the uri
- */
- protected URI handleCloudRegion(String action, URI uri) {
-
- return uri;
-
- }
-
- /**
- * Trim URI.
- *
- * @param uri the uri
- * @return the uri
- */
- protected URI trimURI(URI uri) {
-
- String result = uri.getRawPath();
- if (result.startsWith("/")) {
- result = result.substring(1, result.length());
- }
-
- if (result.endsWith("/")) {
- result = result.substring(0, result.length() - 1);
- }
-
- // TODO - Check if this makes to do for model driven for base uri path
- result = result.replaceFirst("[a-z][a-z]*/v\\d+/", "");
-
- return UriBuilder.fromPath(result).build();
- }
+
+ private URI uri = null;
+
+ protected Loader loader = null;
+
+ protected Loader originalLoader = null;
+
+ private URI originalURI = null;
+
+ private MultivaluedMap<String, String> queryParams = null;
+
+ /**
+ * Instantiates a new URI parser.
+ *
+ * @param loader the loader
+ * @param uri the uri
+ */
+ public URIParser(Loader loader, URI uri) {
+ this.uri = uri;
+
+ this.originalLoader = loader;
+ // Load the latest version because we need it for cloud region
+
+ this.loader = loader;
+ }
+
+ /**
+ * Instantiates a new URI parser.
+ *
+ * @param loader the loader
+ * @param uri the uri
+ * @param queryParams the query params
+ */
+ public URIParser(Loader loader, URI uri, MultivaluedMap<String, String> queryParams) {
+ this(loader, uri);
+ this.queryParams = queryParams;
+ }
+
+ public Loader getLoader() {
+
+ return this.loader;
+
+ }
+
+ /**
+ * Gets the original URI.
+ *
+ * @return the original URI
+ */
+ public URI getOriginalURI() {
+ return this.originalURI;
+ }
+
+ /**
+ * Parses the.
+ *
+ * @param p the p
+ * @throws UnsupportedEncodingException the unsupported encoding exception
+ * @throws AAIException the AAI exception
+ */
+ public void parse(Parsable p) throws UnsupportedEncodingException, AAIException {
+ try {
+ boolean isRelative = false;
+ uri = this.trimURI(uri);
+ uri = handleCloudRegion(p.getCloudRegionTransform(), uri);
+ if (p.useOriginalLoader()) {
+ this.loader = this.originalLoader;
+ }
+ this.originalURI = UriBuilder.fromPath(uri.getRawPath()).build();
+ if (uri.getRawPath().startsWith("./")) {
+ uri = new URI(uri.getRawPath().replaceFirst("\\./", ""));
+ isRelative = true;
+ }
+ String[] parts = uri.getRawPath().split("/");
+ Introspector validNamespaces = loader.introspectorFromName("inventory");
+ Set<String> keys = null;
+ String part = "";
+ Introspector previousObj = null;
+ EdgeType type = EdgeType.TREE;
+ for (int i = 0; i < parts.length;) {
+ part = parts[i];
+ Introspector introspector = null;
+ if (part.equals(RestTokens.COUSIN.toString())) {
+ if (i == parts.length - 1) {
+ throw new AAIException("AAI_3000",
+ uri + " not a valid path. Cannot end in " + RestTokens.COUSIN);
+ }
+ introspector = loader.introspectorFromName(parts[i + 1]);
+ if (null == previousObj) {
+ throw new AAIException("AAI_3001");
+ }
+ if (previousObj.isContainer() && introspector.isContainer()) {
+ throw new AAIException("AAI_3000", uri + " not a valid path. Cannot chain plurals together");
+ }
+ MultivaluedMap<String, String> uriKeys = new MultivaluedHashMap<>();
+ if (i == parts.length - 2 && queryParams != null) {
+ Set<String> queryKeys = queryParams.keySet();
+ for (String key : queryKeys) {
+ uriKeys.put(key, queryParams.get(key));
+
+ }
+ }
+ if (introspector.isContainer()) {
+ boolean isFinalContainer = i == parts.length - 2;
+ /*
+ * Related-to could be COUSIN OR TREE and in some cases BOTH. So Let EdgeRuleBuilder use all the
+ * edgeTypes
+ */
+ p.processContainer(introspector, EdgeType.ALL, uriKeys, isFinalContainer);
+ }
+ previousObj = introspector;
+ type = EdgeType.ALL;
+ i += 2;
+ continue;
+ }
+ introspector = loader.introspectorFromName(part);
+ if (introspector != null) {
+
+ // previous has current as property
+ if (previousObj != null && !previousObj.hasChild(introspector)
+ && !previousObj.getDbName().equals("nodes")) {
+ throw new AAIException("AAI_3001", uri + " not a valid path. " + part + " not valid");
+ } else if (previousObj == null) {
+ String abstractType = introspector.getMetadata(ObjectMetadata.ABSTRACT);
+ if (abstractType == null) {
+ abstractType = "";
+ }
+ // first time through, make sure it starts from a namespace
+ // ignore abstract types
+ if (!isRelative && !abstractType.equals("true") && !validNamespaces.hasChild(introspector)) {
+ throw new DoesNotStartWithValidNamespaceException(
+ uri + " not a valid path. It does not start from a valid namespace");
+ }
+ }
+
+ keys = introspector.getKeys();
+ if (keys.size() > 0) {
+ MultivaluedMap<String, String> uriKeys = new MultivaluedHashMap<>();
+ i++;
+ if (i == parts.length && queryParams != null) {
+ Set<String> queryKeys = queryParams.keySet();
+ for (String key : queryKeys) {
+ uriKeys.put(key, queryParams.get(key));
+ }
+ } else {
+ for (String key : keys) {
+ part = UriUtils.decode(parts[i], "UTF-8");
+
+ introspector.setValue(key, part);
+
+ // skip this for further processing
+ i++;
+ }
+ }
+
+ p.processObject(introspector, type, uriKeys);
+ type = EdgeType.TREE;
+ } else if (introspector.isContainer()) {
+ boolean isFinalContainer = i == parts.length - 1;
+ MultivaluedMap<String, String> uriKeys = new MultivaluedHashMap<>();
+
+ if (isFinalContainer && queryParams != null) {
+ Set<String> queryKeys = queryParams.keySet();
+ for (String key : queryKeys) {
+ uriKeys.put(key, queryParams.get(key));
+
+ }
+ }
+ p.processContainer(introspector, type, uriKeys, isFinalContainer);
+ i++;
+ } else {
+ p.processNamespace(introspector);
+ // namespace case
+ i++;
+ }
+ previousObj = introspector;
+ } else {
+ // invalid item found should log
+ // original said bad path
+ throw new AAIException("AAI_3001", "invalid item found in path: " + part);
+ }
+ }
+ } catch (AAIException e) {
+ throw e;
+ } catch (Exception e) {
+ throw new AAIException("AAI_3001", e);
+ }
+ }
+
+ public boolean validate() throws UnsupportedEncodingException, AAIException {
+ this.parse(new URIValidate());
+ return true;
+ }
+
+ /**
+ * Handle cloud region.
+ *
+ * @param action the action
+ * @param uri the uri
+ * @return the uri
+ */
+ protected URI handleCloudRegion(String action, URI uri) {
+
+ return uri;
+
+ }
+
+ /**
+ * Trim URI.
+ *
+ * @param uri the uri
+ * @return the uri
+ */
+ protected URI trimURI(URI uri) {
+
+ String result = uri.getRawPath();
+ if (result.startsWith("/")) {
+ result = result.substring(1, result.length());
+ }
+
+ if (result.endsWith("/")) {
+ result = result.substring(0, result.length() - 1);
+ }
+
+ // TODO - Check if this makes to do for model driven for base uri path
+ result = result.replaceFirst("[a-z][a-z]*/v\\d+/", "");
+
+ return UriBuilder.fromPath(result).build();
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/parsers/uri/URIToDBKey.java b/aai-core/src/main/java/org/onap/aai/parsers/uri/URIToDBKey.java
index 007f1b3c..ae0b4911 100644
--- a/aai-core/src/main/java/org/onap/aai/parsers/uri/URIToDBKey.java
+++ b/aai-core/src/main/java/org/onap/aai/parsers/uri/URIToDBKey.java
@@ -17,20 +17,23 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.parsers.uri;
import com.google.common.base.Joiner;
-import org.onap.aai.exceptions.AAIException;
-import org.onap.aai.introspection.Introspector;
-import org.onap.aai.introspection.Loader;
-import org.onap.aai.edges.enums.EdgeType;
-import javax.ws.rs.core.MultivaluedMap;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
+import javax.ws.rs.core.MultivaluedMap;
+
+import org.onap.aai.edges.enums.EdgeType;
+import org.onap.aai.exceptions.AAIException;
+import org.onap.aai.introspection.Introspector;
+import org.onap.aai.introspection.Loader;
+
/**
* Creates a Unique database key from a URI
*
@@ -38,69 +41,69 @@ import java.util.List;
*/
public class URIToDBKey implements Parsable {
-
- private List<String> dbKeys = new ArrayList<>();
-
- /**
- * Instantiates a new URI to DB key.
- *
- * @param loader the loader
- * @param uri the uri
- * @throws IllegalArgumentException the illegal argument exception
- * @throws AAIException the AAI exception
- * @throws UnsupportedEncodingException the unsupported encoding exception
- */
- public URIToDBKey(Loader loader, URI uri) throws IllegalArgumentException, AAIException, UnsupportedEncodingException {
- URIParser parser = new URIParser(loader, uri);
- parser.parse(this);
- }
-
- /**
- * @{inheritDoc}
- */
- @Override
- public void processNamespace(Introspector obj) {
-
- }
-
- /**
- * @{inheritDoc}
- */
- @Override
- public String getCloudRegionTransform() {
- return "add";
- }
-
- /**
- * Gets the result.
- *
- * @return the result
- */
- public Object getResult() {
- return Joiner.on("/").join(this.dbKeys);
- }
-
- /**
- * @{inheritDoc}
- */
- @Override
- public boolean useOriginalLoader() {
- return false;
- }
-
- @Override
- public void processObject(Introspector obj, EdgeType type, MultivaluedMap<String, String> uriKeys)
- throws AAIException {
-
- dbKeys.add(obj.getDbName());
-
- for (String key : uriKeys.keySet()) {
- dbKeys.add(uriKeys.getFirst(key).toString());
- }
- }
-
- @Override
- public void processContainer(Introspector obj, EdgeType type, MultivaluedMap<String, String> uriKeys,
- boolean isFinalContainer) {
- }
+ private List<String> dbKeys = new ArrayList<>();
+
+ /**
+ * Instantiates a new URI to DB key.
+ *
+ * @param loader the loader
+ * @param uri the uri
+ * @throws IllegalArgumentException the illegal argument exception
+ * @throws AAIException the AAI exception
+ * @throws UnsupportedEncodingException the unsupported encoding exception
+ */
+ public URIToDBKey(Loader loader, URI uri)
+ throws IllegalArgumentException, AAIException, UnsupportedEncodingException {
+ URIParser parser = new URIParser(loader, uri);
+ parser.parse(this);
+ }
+
+ /**
+ * @{inheritDoc}
+ */
+ @Override
+ public void processNamespace(Introspector obj) {
+
+ }
+
+ /**
+ * @{inheritDoc}
+ */
+ @Override
+ public String getCloudRegionTransform() {
+ return "add";
+ }
+
+ /**
+ * Gets the result.
+ *
+ * @return the result
+ */
+ public Object getResult() {
+ return Joiner.on("/").join(this.dbKeys);
+ }
+
+ /**
+ * @{inheritDoc}
+ */
+ @Override
+ public boolean useOriginalLoader() {
+ return false;
+ }
+
+ @Override
+ public void processObject(Introspector obj, EdgeType type, MultivaluedMap<String, String> uriKeys)
+ throws AAIException {
+
+ dbKeys.add(obj.getDbName());
+
+ for (String key : uriKeys.keySet()) {
+ dbKeys.add(uriKeys.getFirst(key).toString());
+ }
+ }
+
+ @Override
+ public void processContainer(Introspector obj, EdgeType type, MultivaluedMap<String, String> uriKeys,
+ boolean isFinalContainer) {
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/parsers/uri/URIToExtensionInformation.java b/aai-core/src/main/java/org/onap/aai/parsers/uri/URIToExtensionInformation.java
index 1ecb3b4c..f3da24c3 100644
--- a/aai-core/src/main/java/org/onap/aai/parsers/uri/URIToExtensionInformation.java
+++ b/aai-core/src/main/java/org/onap/aai/parsers/uri/URIToExtensionInformation.java
@@ -17,154 +17,158 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.parsers.uri;
import com.google.common.base.CaseFormat;
import com.google.common.base.Joiner;
-import org.onap.aai.exceptions.AAIException;
-import org.onap.aai.introspection.Introspector;
-import org.onap.aai.introspection.Loader;
-import org.onap.aai.restcore.HttpMethod;
-import org.onap.aai.edges.enums.EdgeType;
-import javax.ws.rs.core.MultivaluedMap;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
+import javax.ws.rs.core.MultivaluedMap;
+
+import org.onap.aai.edges.enums.EdgeType;
+import org.onap.aai.exceptions.AAIException;
+import org.onap.aai.introspection.Introspector;
+import org.onap.aai.introspection.Loader;
+import org.onap.aai.restcore.HttpMethod;
+
/**
* The Class URIToExtensionInformation.
*/
public class URIToExtensionInformation implements Parsable {
- private String namespace = "";
-
- private String methodName = "";
-
- private String topObject = "";
-
- private List<String> pieces = null;
-
- /**
- * Instantiates a new URI to extension information.
- *
- * @param loader the loader
- * @param uri the uri
- * @throws IllegalArgumentException the illegal argument exception
- * @throws AAIException the AAI exception
- * @throws UnsupportedEncodingException the unsupported encoding exception
- */
- public URIToExtensionInformation(Loader loader, URI uri) throws IllegalArgumentException, AAIException, UnsupportedEncodingException {
- pieces = new ArrayList<>();
- URIParser parser = new URIParser(loader, uri);
- parser.parse(this);
-
- this.methodName = Joiner.on("").join(this.pieces);
- }
-
- /**
- * @{inheritDoc}
- */
- @Override
- public void processNamespace(Introspector obj) {
- this.namespace = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, obj.getDbName());
- pieces.add(toUpperCamel(obj.getDbName()));
-
- }
-
- /**
- * @{inheritDoc}
- */
- @Override
- public String getCloudRegionTransform() {
- return "remove";
- }
-
- /**
- * @{inheritDoc}
- */
- @Override
- public boolean useOriginalLoader() {
- return true;
- }
-
- /**
- * Gets the namespace.
- *
- * @return the namespace
- */
- public String getNamespace() {
- return this.namespace;
- }
-
- /**
- * Gets the top object.
- *
- * @return the top object
- */
- public String getTopObject() {
- return this.topObject;
- }
-
- /**
- * Gets the method name.
- *
- * @param httpMethod the http method
- * @param isPreprocess the is preprocess
- * @return the method name
- */
- public String getMethodName(HttpMethod httpMethod, boolean isPreprocess) {
- String result = "Dynamic";
- /*
- if (httpMethod.equals(HttpMethod.PUT) || httpMethod.equals(HttpMethod.PUT_EDGE)) {
- result += "Add";
- }
- */
- if (httpMethod.equals(HttpMethod.PUT) ) {
- result += "Add";
- } else if (httpMethod.equals(HttpMethod.PUT_EDGE)) {
- result += "AddEdge";
- } else if (httpMethod.equals(HttpMethod.DELETE)) {
- result += "Del";
- } else {
- throw new IllegalArgumentException("http method not supported: " + httpMethod);
- }
- result += this.methodName;
-
- if (isPreprocess) {
- result += "PreProc";
- } else {
- result += "PostProc";
- }
- return result;
- }
-
- /**
- * To upper camel.
- *
- * @param name the name
- * @return the string
- */
- private String toUpperCamel(String name) {
- String result = "";
- result = CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, name);
- return result;
- }
-
- @Override
- public void processObject(Introspector obj, EdgeType type, MultivaluedMap<String, String> uriKeys)
- throws AAIException {
- String upperCamel = toUpperCamel(obj.getDbName());
- if (topObject.equals("")) {
- topObject = upperCamel;
- }
- pieces.add(upperCamel);
- }
-
- @Override
- public void processContainer(Introspector obj, EdgeType type, MultivaluedMap<String, String> uriKeys,
- boolean isFinalContainer) throws AAIException {
- pieces.add(toUpperCamel(obj.getName()));
- }
+ private String namespace = "";
+
+ private String methodName = "";
+
+ private String topObject = "";
+
+ private List<String> pieces = null;
+
+ /**
+ * Instantiates a new URI to extension information.
+ *
+ * @param loader the loader
+ * @param uri the uri
+ * @throws IllegalArgumentException the illegal argument exception
+ * @throws AAIException the AAI exception
+ * @throws UnsupportedEncodingException the unsupported encoding exception
+ */
+ public URIToExtensionInformation(Loader loader, URI uri)
+ throws IllegalArgumentException, AAIException, UnsupportedEncodingException {
+ pieces = new ArrayList<>();
+ URIParser parser = new URIParser(loader, uri);
+ parser.parse(this);
+
+ this.methodName = Joiner.on("").join(this.pieces);
+ }
+
+ /**
+ * @{inheritDoc}
+ */
+ @Override
+ public void processNamespace(Introspector obj) {
+ this.namespace = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, obj.getDbName());
+ pieces.add(toUpperCamel(obj.getDbName()));
+
+ }
+
+ /**
+ * @{inheritDoc}
+ */
+ @Override
+ public String getCloudRegionTransform() {
+ return "remove";
+ }
+
+ /**
+ * @{inheritDoc}
+ */
+ @Override
+ public boolean useOriginalLoader() {
+ return true;
+ }
+
+ /**
+ * Gets the namespace.
+ *
+ * @return the namespace
+ */
+ public String getNamespace() {
+ return this.namespace;
+ }
+
+ /**
+ * Gets the top object.
+ *
+ * @return the top object
+ */
+ public String getTopObject() {
+ return this.topObject;
+ }
+
+ /**
+ * Gets the method name.
+ *
+ * @param httpMethod the http method
+ * @param isPreprocess the is preprocess
+ * @return the method name
+ */
+ public String getMethodName(HttpMethod httpMethod, boolean isPreprocess) {
+ String result = "Dynamic";
+ /*
+ * if (httpMethod.equals(HttpMethod.PUT) || httpMethod.equals(HttpMethod.PUT_EDGE)) {
+ * result += "Add";
+ * }
+ */
+ if (httpMethod.equals(HttpMethod.PUT)) {
+ result += "Add";
+ } else if (httpMethod.equals(HttpMethod.PUT_EDGE)) {
+ result += "AddEdge";
+ } else if (httpMethod.equals(HttpMethod.DELETE)) {
+ result += "Del";
+ } else {
+ throw new IllegalArgumentException("http method not supported: " + httpMethod);
+ }
+ result += this.methodName;
+
+ if (isPreprocess) {
+ result += "PreProc";
+ } else {
+ result += "PostProc";
+ }
+ return result;
+ }
+
+ /**
+ * To upper camel.
+ *
+ * @param name the name
+ * @return the string
+ */
+ private String toUpperCamel(String name) {
+ String result = "";
+ result = CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, name);
+ return result;
+ }
+
+ @Override
+ public void processObject(Introspector obj, EdgeType type, MultivaluedMap<String, String> uriKeys)
+ throws AAIException {
+ String upperCamel = toUpperCamel(obj.getDbName());
+ if (topObject.equals("")) {
+ topObject = upperCamel;
+ }
+ pieces.add(upperCamel);
+ }
+
+ @Override
+ public void processContainer(Introspector obj, EdgeType type, MultivaluedMap<String, String> uriKeys,
+ boolean isFinalContainer) throws AAIException {
+ pieces.add(toUpperCamel(obj.getName()));
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/parsers/uri/URIToObject.java b/aai-core/src/main/java/org/onap/aai/parsers/uri/URIToObject.java
index d8bdab83..186f2ee9 100644
--- a/aai-core/src/main/java/org/onap/aai/parsers/uri/URIToObject.java
+++ b/aai-core/src/main/java/org/onap/aai/parsers/uri/URIToObject.java
@@ -17,21 +17,23 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.parsers.uri;
+import java.io.UnsupportedEncodingException;
+import java.net.URI;
+import java.util.HashMap;
+import java.util.List;
+
+import javax.ws.rs.core.MultivaluedMap;
+
+import org.onap.aai.edges.enums.EdgeType;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.introspection.Introspector;
import org.onap.aai.introspection.Loader;
import org.onap.aai.schema.enums.ObjectMetadata;
-import org.onap.aai.edges.enums.EdgeType;
import org.onap.aai.setup.SchemaVersion;
-import javax.ws.rs.core.MultivaluedMap;
-import java.io.UnsupportedEncodingException;
-import java.net.URI;
-import java.util.HashMap;
-import java.util.List;
-
/**
* Given a URI this class returns an object, or series of nested objects
* with their keys populated based off the values in the URI.
@@ -40,177 +42,181 @@ import java.util.List;
*/
public class URIToObject implements Parsable {
-
- private Introspector topEntity = null;
-
- private String topEntityName = null;
-
- private String entityName = null;
-
- private Introspector entity = null;
-
- private Introspector previous = null;
-
- private List<Object> parentList = null;
-
- private SchemaVersion version = null;
- private Loader loader = null;
- private final HashMap<String, Introspector> relatedObjects;
-
- /**
- * Instantiates a new URI to object.
- *
- * @param loader the loader
- * @param uri the uri
- * @throws IllegalArgumentException the illegal argument exception
- * @throws AAIException the AAI exception
- * @throws UnsupportedEncodingException the unsupported encoding exception
- */
- public URIToObject(Loader loader, URI uri) throws AAIException, UnsupportedEncodingException {
-
- URIParser parser = new URIParser(loader, uri);
- this.relatedObjects = new HashMap<>();
-
- parser.parse(this);
- this.loader = parser.getLoader();
- this.version = loader.getVersion();
- }
- public URIToObject(Loader loader, URI uri, HashMap<String, Introspector> relatedObjects) throws AAIException, UnsupportedEncodingException {
-
- URIParser parser = new URIParser(loader, uri);
- this.relatedObjects = relatedObjects;
-
- parser.parse(this);
- this.loader = parser.getLoader();
- this.version = loader.getVersion();
-
- }
-
- /**
- * @{inheritDoc}
- */
- @Override
- public void processNamespace(Introspector obj) {
-
- }
-
- /**
- * @{inheritDoc}
- */
- @Override
- public String getCloudRegionTransform() {
- return "add";
- }
-
- /**
- * @{inheritDoc}
- */
- @Override
- public boolean useOriginalLoader() {
- // TODO Auto-generated method stub
- return false;
- }
-
- /**
- * Gets the top entity.
- *
- * @return the top entity
- */
- public Introspector getTopEntity() {
- return this.topEntity;
- }
-
- /**
- * Gets the entity.
- *
- * @return the entity
- */
- public Introspector getEntity() {
- return this.entity;
- }
-
- /**
- * Gets the parent list.
- *
- * @return the parent list
- */
- public List<Object> getParentList() {
- return this.parentList;
- }
-
- /**
- * Gets the entity name.
- *
- * @return the entity name
- */
- public String getEntityName() {
- return this.entityName;
- }
-
- /**
- * Gets the top entity name.
- *
- * @return the top entity name
- */
- public String getTopEntityName() {
- return this.topEntityName;
- }
-
- /**
- * Gets the object version.
- *
- * @return the object version
- */
- public SchemaVersion getObjectVersion() {
- return this.loader.getVersion();
- }
- public Loader getLoader() {
- return this.loader;
- }
- @Override
- public void processObject(Introspector obj, EdgeType type, MultivaluedMap<String, String> uriKeys)
- throws AAIException {
-
- if (this.entityName == null) {
- this.topEntityName = obj.getDbName();
- this.topEntity = obj;
- }
- this.entityName = obj.getDbName();
- this.entity = obj;
- this.parentList = (List<Object>)this.previous.getValue(obj.getName());
- this.parentList.add(entity.getUnderlyingObject());
-
- for (String key : uriKeys.keySet()) {
- entity.setValue(key, uriKeys.getFirst(key));
- }
- try {
- if (relatedObjects.containsKey(entity.getObjectId())) {
- Introspector relatedObject = relatedObjects.get(entity.getObjectId());
- String nameProp = relatedObject.getMetadata(ObjectMetadata.NAME_PROPS);
- if (nameProp == null) {
- nameProp = "";
- }
- if (nameProp != null && !nameProp.equals("")) {
- String[] nameProps = nameProp.split(",");
- for (String prop : nameProps) {
- entity.setValue(prop, relatedObject.getValue(prop));
- }
- }
- }
- } catch (UnsupportedEncodingException e) {
- }
- this.previous = entity;
- }
- @Override
- public void processContainer(Introspector obj, EdgeType type, MultivaluedMap<String, String> uriKeys,
- boolean isFinalContainer) throws AAIException {
- this.previous = obj;
-
- if (this.entity != null) {
- this.entity.setValue(obj.getName(), obj.getUnderlyingObject());
- } else {
- this.entity = obj;
- this.topEntity = obj;
- }
- }
+ private Introspector topEntity = null;
+
+ private String topEntityName = null;
+
+ private String entityName = null;
+
+ private Introspector entity = null;
+
+ private Introspector previous = null;
+
+ private List<Object> parentList = null;
+
+ private SchemaVersion version = null;
+ private Loader loader = null;
+ private final HashMap<String, Introspector> relatedObjects;
+
+ /**
+ * Instantiates a new URI to object.
+ *
+ * @param loader the loader
+ * @param uri the uri
+ * @throws IllegalArgumentException the illegal argument exception
+ * @throws AAIException the AAI exception
+ * @throws UnsupportedEncodingException the unsupported encoding exception
+ */
+ public URIToObject(Loader loader, URI uri) throws AAIException, UnsupportedEncodingException {
+
+ URIParser parser = new URIParser(loader, uri);
+ this.relatedObjects = new HashMap<>();
+
+ parser.parse(this);
+ this.loader = parser.getLoader();
+ this.version = loader.getVersion();
+ }
+
+ public URIToObject(Loader loader, URI uri, HashMap<String, Introspector> relatedObjects)
+ throws AAIException, UnsupportedEncodingException {
+
+ URIParser parser = new URIParser(loader, uri);
+ this.relatedObjects = relatedObjects;
+
+ parser.parse(this);
+ this.loader = parser.getLoader();
+ this.version = loader.getVersion();
+
+ }
+
+ /**
+ * @{inheritDoc}
+ */
+ @Override
+ public void processNamespace(Introspector obj) {
+
+ }
+
+ /**
+ * @{inheritDoc}
+ */
+ @Override
+ public String getCloudRegionTransform() {
+ return "add";
+ }
+
+ /**
+ * @{inheritDoc}
+ */
+ @Override
+ public boolean useOriginalLoader() {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ /**
+ * Gets the top entity.
+ *
+ * @return the top entity
+ */
+ public Introspector getTopEntity() {
+ return this.topEntity;
+ }
+
+ /**
+ * Gets the entity.
+ *
+ * @return the entity
+ */
+ public Introspector getEntity() {
+ return this.entity;
+ }
+
+ /**
+ * Gets the parent list.
+ *
+ * @return the parent list
+ */
+ public List<Object> getParentList() {
+ return this.parentList;
+ }
+
+ /**
+ * Gets the entity name.
+ *
+ * @return the entity name
+ */
+ public String getEntityName() {
+ return this.entityName;
+ }
+
+ /**
+ * Gets the top entity name.
+ *
+ * @return the top entity name
+ */
+ public String getTopEntityName() {
+ return this.topEntityName;
+ }
+
+ /**
+ * Gets the object version.
+ *
+ * @return the object version
+ */
+ public SchemaVersion getObjectVersion() {
+ return this.loader.getVersion();
+ }
+
+ public Loader getLoader() {
+ return this.loader;
+ }
+
+ @Override
+ public void processObject(Introspector obj, EdgeType type, MultivaluedMap<String, String> uriKeys)
+ throws AAIException {
+
+ if (this.entityName == null) {
+ this.topEntityName = obj.getDbName();
+ this.topEntity = obj;
+ }
+ this.entityName = obj.getDbName();
+ this.entity = obj;
+ this.parentList = (List<Object>) this.previous.getValue(obj.getName());
+ this.parentList.add(entity.getUnderlyingObject());
+
+ for (String key : uriKeys.keySet()) {
+ entity.setValue(key, uriKeys.getFirst(key));
+ }
+ try {
+ if (relatedObjects.containsKey(entity.getObjectId())) {
+ Introspector relatedObject = relatedObjects.get(entity.getObjectId());
+ String nameProp = relatedObject.getMetadata(ObjectMetadata.NAME_PROPS);
+ if (nameProp == null) {
+ nameProp = "";
+ }
+ if (nameProp != null && !nameProp.equals("")) {
+ String[] nameProps = nameProp.split(",");
+ for (String prop : nameProps) {
+ entity.setValue(prop, relatedObject.getValue(prop));
+ }
+ }
+ }
+ } catch (UnsupportedEncodingException e) {
+ }
+ this.previous = entity;
+ }
+
+ @Override
+ public void processContainer(Introspector obj, EdgeType type, MultivaluedMap<String, String> uriKeys,
+ boolean isFinalContainer) throws AAIException {
+ this.previous = obj;
+
+ if (this.entity != null) {
+ this.entity.setValue(obj.getName(), obj.getUnderlyingObject());
+ } else {
+ this.entity = obj;
+ this.topEntity = obj;
+ }
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/parsers/uri/URIToRelationshipObject.java b/aai-core/src/main/java/org/onap/aai/parsers/uri/URIToRelationshipObject.java
index 08eca16d..57f48d4c 100644
--- a/aai-core/src/main/java/org/onap/aai/parsers/uri/URIToRelationshipObject.java
+++ b/aai-core/src/main/java/org/onap/aai/parsers/uri/URIToRelationshipObject.java
@@ -17,150 +17,152 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.parsers.uri;
+import java.io.UnsupportedEncodingException;
+import java.net.MalformedURLException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.List;
+
+import javax.ws.rs.core.MultivaluedMap;
+
import org.onap.aai.config.SpringContextAware;
+import org.onap.aai.edges.enums.EdgeType;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.introspection.Introspector;
import org.onap.aai.introspection.Loader;
-import org.onap.aai.setup.SchemaVersion;
import org.onap.aai.introspection.exceptions.AAIUnknownObjectException;
-import org.onap.aai.edges.enums.EdgeType;
+import org.onap.aai.setup.SchemaVersion;
import org.onap.aai.setup.SchemaVersions;
import org.onap.aai.util.AAIConfig;
import org.onap.aai.util.AAIConstants;
-import javax.ws.rs.core.MultivaluedMap;
-import java.io.UnsupportedEncodingException;
-import java.net.MalformedURLException;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.util.List;
-
/**
* Given a URI a Relationship Object is returned.
*
* The relationship-data objects are created from the keys in the model.
* The keys are processed in the order they appear in the model.
-
*
+ *
*/
public class URIToRelationshipObject implements Parsable {
-
- private Introspector result = null;
-
- private SchemaVersion originalVersion = null;
-
- private Introspector relationship = null;
-
- private Loader loader = null;
-
- private String baseURL;
-
- private final URI uri;
- /**
- * Instantiates a new URI to relationship object.
- *
- * @param loader the loader
- * @param uri the uri
- * @throws IllegalArgumentException the illegal argument exception
- * @throws AAIException the AAI exception
- * @throws UnsupportedEncodingException the unsupported encoding exception
- * @throws MalformedURLException the malformed URL exception
- */
- public URIToRelationshipObject(Loader loader, URI uri) throws AAIException {
-
- this.loader = loader;
- originalVersion = loader.getVersion();
-
- try {
- relationship = loader.introspectorFromName("relationship");
- } catch (AAIUnknownObjectException e1) {
- throw new RuntimeException("Fatal error - could not load relationship object!", e1);
- }
-
- this.baseURL = AAIConfig.get(AAIConstants.AAI_SERVER_URL_BASE);
- this.uri = uri;
-
- }
-
- public URIToRelationshipObject(Loader loader, URI uri, String baseURL) throws AAIException {
- this(loader, uri);
-
- if (baseURL != null) {
- this.baseURL = baseURL;
- }
- }
-
-
- /**
- * @{inheritDoc}
- */
- @Override
- public String getCloudRegionTransform(){
- return "remove";
- }
-
- /**
- * @{inheritDoc}
- */
- @Override
- public void processNamespace(Introspector obj) {
-
- }
-
- /**
- * @{inheritDoc}
- */
- @Override
- public boolean useOriginalLoader() {
- return true;
- }
-
- /**
- * Gets the result.
- *
- * @return the result
- * @throws AAIException
- * @throws UnsupportedEncodingException
- * @throws URISyntaxException
- */
- public Introspector getResult() throws UnsupportedEncodingException, AAIException, URISyntaxException {
- URIParser parser = new URIParser(this.loader, this.uri);
- parser.parse(this);
- URI originalUri = parser.getOriginalURI();
-
- URI relatedLink = new URI(this.baseURL + this.originalVersion + "/" + originalUri);
- SchemaVersions schemaVersions = (SchemaVersions)SpringContextAware.getBean("schemaVersions");
- if (this.originalVersion.compareTo(schemaVersions.getRelatedLinkVersion()) >= 0) {
- //only return the path section of the URI past v10
- relatedLink = new URI(relatedLink.getRawPath());
- }
-
- this.relationship.setValue("related-link", relatedLink.toString());
-
- this.result = relationship;
- return this.result;
- }
-
- @Override
- public void processObject(Introspector obj, EdgeType type, MultivaluedMap<String, String> uriKeys) {
- for (String key : obj.getKeys()) {
- try {
- Introspector data = loader.introspectorFromName("relationship-data");
- data.setValue("relationship-key", obj.getDbName() + "." + key);
- data.setValue("relationship-value", obj.getValue(key));
-
- ((List<Object>)relationship.getValue("relationship-data")).add(data.getUnderlyingObject());
- } catch (AAIUnknownObjectException e) {
- throw new RuntimeException("Fatal error - relationship-data object not found!");
- }
- }
- relationship.setValue("related-to", obj.getDbName());
- }
-
- @Override
- public void processContainer(Introspector obj, EdgeType type, MultivaluedMap<String, String> uriKeys,
- boolean isFinalContainer) throws AAIException {
- }
+
+ private Introspector result = null;
+
+ private SchemaVersion originalVersion = null;
+
+ private Introspector relationship = null;
+
+ private Loader loader = null;
+
+ private String baseURL;
+
+ private final URI uri;
+
+ /**
+ * Instantiates a new URI to relationship object.
+ *
+ * @param loader the loader
+ * @param uri the uri
+ * @throws IllegalArgumentException the illegal argument exception
+ * @throws AAIException the AAI exception
+ * @throws UnsupportedEncodingException the unsupported encoding exception
+ * @throws MalformedURLException the malformed URL exception
+ */
+ public URIToRelationshipObject(Loader loader, URI uri) throws AAIException {
+
+ this.loader = loader;
+ originalVersion = loader.getVersion();
+
+ try {
+ relationship = loader.introspectorFromName("relationship");
+ } catch (AAIUnknownObjectException e1) {
+ throw new RuntimeException("Fatal error - could not load relationship object!", e1);
+ }
+
+ this.baseURL = AAIConfig.get(AAIConstants.AAI_SERVER_URL_BASE);
+ this.uri = uri;
+
+ }
+
+ public URIToRelationshipObject(Loader loader, URI uri, String baseURL) throws AAIException {
+ this(loader, uri);
+
+ if (baseURL != null) {
+ this.baseURL = baseURL;
+ }
+ }
+
+ /**
+ * @{inheritDoc}
+ */
+ @Override
+ public String getCloudRegionTransform() {
+ return "remove";
+ }
+
+ /**
+ * @{inheritDoc}
+ */
+ @Override
+ public void processNamespace(Introspector obj) {
+
+ }
+
+ /**
+ * @{inheritDoc}
+ */
+ @Override
+ public boolean useOriginalLoader() {
+ return true;
+ }
+
+ /**
+ * Gets the result.
+ *
+ * @return the result
+ * @throws AAIException
+ * @throws UnsupportedEncodingException
+ * @throws URISyntaxException
+ */
+ public Introspector getResult() throws UnsupportedEncodingException, AAIException, URISyntaxException {
+ URIParser parser = new URIParser(this.loader, this.uri);
+ parser.parse(this);
+ URI originalUri = parser.getOriginalURI();
+
+ URI relatedLink = new URI(this.baseURL + this.originalVersion + "/" + originalUri);
+ SchemaVersions schemaVersions = (SchemaVersions) SpringContextAware.getBean("schemaVersions");
+ if (this.originalVersion.compareTo(schemaVersions.getRelatedLinkVersion()) >= 0) {
+ // only return the path section of the URI past v10
+ relatedLink = new URI(relatedLink.getRawPath());
+ }
+
+ this.relationship.setValue("related-link", relatedLink.toString());
+
+ this.result = relationship;
+ return this.result;
+ }
+
+ @Override
+ public void processObject(Introspector obj, EdgeType type, MultivaluedMap<String, String> uriKeys) {
+ for (String key : obj.getKeys()) {
+ try {
+ Introspector data = loader.introspectorFromName("relationship-data");
+ data.setValue("relationship-key", obj.getDbName() + "." + key);
+ data.setValue("relationship-value", obj.getValue(key));
+
+ ((List<Object>) relationship.getValue("relationship-data")).add(data.getUnderlyingObject());
+ } catch (AAIUnknownObjectException e) {
+ throw new RuntimeException("Fatal error - relationship-data object not found!");
+ }
+ }
+ relationship.setValue("related-to", obj.getDbName());
+ }
+
+ @Override
+ public void processContainer(Introspector obj, EdgeType type, MultivaluedMap<String, String> uriKeys,
+ boolean isFinalContainer) throws AAIException {
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/parsers/uri/URIValidate.java b/aai-core/src/main/java/org/onap/aai/parsers/uri/URIValidate.java
index 6af835ee..367fc578 100644
--- a/aai-core/src/main/java/org/onap/aai/parsers/uri/URIValidate.java
+++ b/aai-core/src/main/java/org/onap/aai/parsers/uri/URIValidate.java
@@ -17,46 +17,47 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.parsers.uri;
+import javax.ws.rs.core.MultivaluedMap;
+
+import org.onap.aai.edges.enums.EdgeType;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.introspection.Introspector;
-import org.onap.aai.edges.enums.EdgeType;
-
-import javax.ws.rs.core.MultivaluedMap;
class URIValidate implements Parsable {
- @Override
- public void processNamespace(Introspector obj) {
- //NO-OP
- //just want to make sure this URI has valid tokens
-
- }
-
- @Override
- public String getCloudRegionTransform() {
- return "none";
- }
-
- @Override
- public boolean useOriginalLoader() {
-
- return true;
- }
-
- @Override
- public void processObject(Introspector obj, EdgeType type, MultivaluedMap<String, String> uriKeys)
- throws AAIException {
- //NO-OP
- //just want to make sure this URI has valid tokens
- }
-
- @Override
- public void processContainer(Introspector obj, EdgeType type, MultivaluedMap<String, String> uriKeys,
- boolean isFinalContainer) throws AAIException {
- //NO-OP
- //just want to make sure this URI has valid tokens
- }
+ @Override
+ public void processNamespace(Introspector obj) {
+ // NO-OP
+ // just want to make sure this URI has valid tokens
+
+ }
+
+ @Override
+ public String getCloudRegionTransform() {
+ return "none";
+ }
+
+ @Override
+ public boolean useOriginalLoader() {
+
+ return true;
+ }
+
+ @Override
+ public void processObject(Introspector obj, EdgeType type, MultivaluedMap<String, String> uriKeys)
+ throws AAIException {
+ // NO-OP
+ // just want to make sure this URI has valid tokens
+ }
+
+ @Override
+ public void processContainer(Introspector obj, EdgeType type, MultivaluedMap<String, String> uriKeys,
+ boolean isFinalContainer) throws AAIException {
+ // NO-OP
+ // just want to make sure this URI has valid tokens
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/query/builder/GraphTraversalBuilder.java b/aai-core/src/main/java/org/onap/aai/query/builder/GraphTraversalBuilder.java
index bf9dd17f..272a2c21 100644
--- a/aai-core/src/main/java/org/onap/aai/query/builder/GraphTraversalBuilder.java
+++ b/aai-core/src/main/java/org/onap/aai/query/builder/GraphTraversalBuilder.java
@@ -17,8 +17,14 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.query.builder;
+import com.google.common.collect.ArrayListMultimap;
+import com.google.common.collect.Multimap;
+
+import java.util.*;
+
import org.apache.tinkerpop.gremlin.process.traversal.P;
import org.apache.tinkerpop.gremlin.process.traversal.Path;
import org.apache.tinkerpop.gremlin.process.traversal.Traversal;
@@ -32,98 +38,93 @@ import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.onap.aai.db.props.AAIProperties;
+import org.onap.aai.edges.EdgeRule;
+import org.onap.aai.edges.EdgeRuleQuery;
+import org.onap.aai.edges.enums.EdgeType;
+import org.onap.aai.edges.exceptions.EdgeRuleNotFoundException;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.introspection.Introspector;
import org.onap.aai.introspection.Loader;
import org.onap.aai.schema.enums.ObjectMetadata;
import org.onap.aai.schema.enums.PropertyMetadata;
-import org.onap.aai.edges.EdgeRule;
-import org.onap.aai.edges.EdgeRuleQuery;
-import org.onap.aai.edges.enums.EdgeType;
-import org.onap.aai.edges.exceptions.EdgeRuleNotFoundException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
-import com.google.common.collect.ArrayListMultimap;
-import com.google.common.collect.Multimap;
-
-import java.util.*;
-
/**
* The Class GraphTraversalBuilder.
*/
public abstract class GraphTraversalBuilder<E> extends QueryBuilder<E> {
- protected GraphTraversal<Vertex, E> traversal = null;
- protected Admin<Vertex, E> completeTraversal = null;
+ protected GraphTraversal<Vertex, E> traversal = null;
+ protected Admin<Vertex, E> completeTraversal = null;
- /**
- * Instantiates a new graph traversal builder.
- *
- * @param loader the loader
- */
- public GraphTraversalBuilder(Loader loader, GraphTraversalSource source) {
- super(loader, source);
+ /**
+ * Instantiates a new graph traversal builder.
+ *
+ * @param loader the loader
+ */
+ public GraphTraversalBuilder(Loader loader, GraphTraversalSource source) {
+ super(loader, source);
- traversal = (GraphTraversal<Vertex, E>) __.<E>start();
+ traversal = (GraphTraversal<Vertex, E>) __.<E>start();
- }
+ }
- /**
- * Instantiates a new graph traversal builder.
- *
- * @param loader the loader
- * @param start the start
- */
- public GraphTraversalBuilder(Loader loader, GraphTraversalSource source, Vertex start) {
- super(loader, source, start);
+ /**
+ * Instantiates a new graph traversal builder.
+ *
+ * @param loader the loader
+ * @param start the start
+ */
+ public GraphTraversalBuilder(Loader loader, GraphTraversalSource source, Vertex start) {
+ super(loader, source, start);
- traversal = (GraphTraversal<Vertex, E>) __.__(start);
+ traversal = (GraphTraversal<Vertex, E>) __.__(start);
- }
+ }
- /**
- * @{inheritDoc}
- */
- @Override
- public QueryBuilder<Vertex> getVerticesByProperty(String key, Object value) {
+ /**
+ * @{inheritDoc}
+ */
+ @Override
+ public QueryBuilder<Vertex> getVerticesByProperty(String key, Object value) {
- // correct value call because the index is registered as an Integer
- traversal.has(key, this.correctObjectType(value));
+ // correct value call because the index is registered as an Integer
+ traversal.has(key, this.correctObjectType(value));
- stepIndex++;
- return (QueryBuilder<Vertex>) this;
- }
+ stepIndex++;
+ return (QueryBuilder<Vertex>) this;
+ }
- /**
- * @{inheritDoc}
- */
- @Override
- public QueryBuilder<Vertex> getVerticesByProperty(final String key, final List<?> values) {
+ /**
+ * @{inheritDoc}
+ */
+ @Override
+ public QueryBuilder<Vertex> getVerticesByProperty(final String key, final List<?> values) {
- //this is because the index is registered as an Integer
- List<Object> correctedValues = new ArrayList<>();
- for (Object item : values) {
- correctedValues.add(this.correctObjectType(item));
- }
+ // this is because the index is registered as an Integer
+ List<Object> correctedValues = new ArrayList<>();
+ for (Object item : values) {
+ correctedValues.add(this.correctObjectType(item));
+ }
- traversal.has(key, P.within(correctedValues));
+ traversal.has(key, P.within(correctedValues));
- stepIndex++;
- return (QueryBuilder<Vertex>) this;
- }
+ stepIndex++;
+ return (QueryBuilder<Vertex>) this;
+ }
- /**
- * @{inheritDoc}
- */
- @Override
- public QueryBuilder<Vertex> getVerticesStartsWithProperty(String key, Object value) {
+ /**
+ * @{inheritDoc}
+ */
+ @Override
+ public QueryBuilder<Vertex> getVerticesStartsWithProperty(String key, Object value) {
- // correct value call because the index is registered as an Integer
- traversal.has(key, org.janusgraph.core.attribute.Text.textPrefix(value));
+ // correct value call because the index is registered as an Integer
+ traversal.has(key, org.janusgraph.core.attribute.Text.textPrefix(value));
- stepIndex++;
- return (QueryBuilder<Vertex>) this;
- }
+ stepIndex++;
+ return (QueryBuilder<Vertex>) this;
+ }
/**
* @{inheritDoc}
@@ -147,37 +148,36 @@ public abstract class GraphTraversalBuilder<E> extends QueryBuilder<E> {
return (QueryBuilder<Vertex>) this;
}
+ /**
+ * @{inheritDoc}
+ */
+ @Override
+ public QueryBuilder<Vertex> getVerticesExcludeByProperty(String key, Object value) {
- /**
- * @{inheritDoc}
- */
- @Override
- public QueryBuilder<Vertex> getVerticesExcludeByProperty(String key, Object value) {
-
- // correct value call because the index is registered as an Integer
- traversal.has(key, P.neq(this.correctObjectType(value)));
+ // correct value call because the index is registered as an Integer
+ traversal.has(key, P.neq(this.correctObjectType(value)));
- stepIndex++;
- return (QueryBuilder<Vertex>) this;
- }
+ stepIndex++;
+ return (QueryBuilder<Vertex>) this;
+ }
- /**
- * @{inheritDoc}
- */
- @Override
- public QueryBuilder<Vertex> getVerticesExcludeByProperty(final String key, final List<?> values) {
+ /**
+ * @{inheritDoc}
+ */
+ @Override
+ public QueryBuilder<Vertex> getVerticesExcludeByProperty(final String key, final List<?> values) {
- //this is because the index is registered as an Integer
- List<Object> correctedValues = new ArrayList<>();
- for (Object item : values) {
- correctedValues.add(this.correctObjectType(item));
- }
+ // this is because the index is registered as an Integer
+ List<Object> correctedValues = new ArrayList<>();
+ for (Object item : values) {
+ correctedValues.add(this.correctObjectType(item));
+ }
- traversal.has(key, P.without(correctedValues));
+ traversal.has(key, P.without(correctedValues));
- stepIndex++;
- return (QueryBuilder<Vertex>) this;
- }
+ stepIndex++;
+ return (QueryBuilder<Vertex>) this;
+ }
@Override
public QueryBuilder<Vertex> getVerticesGreaterThanProperty(final String key, Object value) {
@@ -197,703 +197,709 @@ public abstract class GraphTraversalBuilder<E> extends QueryBuilder<E> {
return (QueryBuilder<Vertex>) this;
}
+ /**
+ * @{inheritDoc}
+ */
+ @Override
+ public QueryBuilder<Vertex> getChildVerticesFromParent(String parentKey, String parentValue, String childType) {
+ traversal.has(parentKey, parentValue).has(AAIProperties.NODE_TYPE, childType);
+ stepIndex++;
+ return (QueryBuilder<Vertex>) this;
+ }
+
+ /**
+ * @{inheritDoc}
+ */
+ @Override
+ public QueryBuilder<Vertex> getTypedVerticesByMap(String type, Map<String, String> map) {
+
+ for (Map.Entry<String, String> es : map.entrySet()) {
+ traversal.has(es.getKey(), es.getValue());
+ stepIndex++;
+ }
+ traversal.has(AAIProperties.NODE_TYPE, type);
+ stepIndex++;
+ return (QueryBuilder<Vertex>) this;
+ }
+
+ @Override
+ public QueryBuilder<Vertex> getVerticesByBooleanProperty(String key, Object value) {
+
+ if (value != null && !"".equals(value)) {
+ boolean bValue = false;
+
+ if (value instanceof String) {// "true"
+ bValue = Boolean.valueOf(value.toString());
+ } else if (value instanceof Boolean) {// true
+ bValue = (Boolean) value;
+ }
+
+ traversal.has(key, bValue);
+ stepIndex++;
+ }
+ return (QueryBuilder<Vertex>) this;
+ }
+
+ /**
+ * @{inheritDoc}
+ */
+ @Override
+ public QueryBuilder<Vertex> createKeyQuery(Introspector obj) {
+ Set<String> keys = obj.getKeys();
+ Object val;
+ for (String key : keys) {
+ val = obj.getValue(key);
+ Optional<String> metadata = obj.getPropertyMetadata(key, PropertyMetadata.DB_ALIAS);
+ if (metadata.isPresent()) {
+ // use the db name for the field rather than the object model
+ key = metadata.get();
+ }
+ if (val != null) {
+ // this is because the index is registered as an Integer
+ if (val.getClass().equals(Long.class)) {
+ traversal.has(key, new Integer(val.toString()));
+ } else {
+ traversal.has(key, val);
+ }
+ stepIndex++;
+ }
+ }
+ return (QueryBuilder<Vertex>) this;
+ }
+
+ @Override
+ public QueryBuilder<Vertex> exactMatchQuery(Introspector obj) {
+ this.createKeyQuery(obj);
+ allPropertiesQuery(obj);
+ this.createContainerQuery(obj);
+ return (QueryBuilder<Vertex>) this;
+ }
+
+ private void allPropertiesQuery(Introspector obj) {
+ Set<String> props = obj.getProperties();
+ Set<String> keys = obj.getKeys();
+ Object val;
+ for (String prop : props) {
+ if (obj.isSimpleType(prop) && !keys.contains(prop)) {
+ val = obj.getValue(prop);
+ if (val != null) {
+ Optional<String> metadata = obj.getPropertyMetadata(prop, PropertyMetadata.DB_ALIAS);
+ if (metadata.isPresent()) {
+ // use the db name for the field rather than the object model
+ prop = metadata.get();
+ }
+ // this is because the index is registered as an Integer
+ if (val.getClass().equals(Long.class)) {
+ traversal.has(prop, new Integer(val.toString()));
+ } else {
+ traversal.has(prop, val);
+ }
+ stepIndex++;
+ }
+ }
+ }
+ }
+
+ /**
+ * @{inheritDoc}
+ */
+ @Override
+
+ public QueryBuilder<Vertex> createContainerQuery(Introspector obj) {
+ String type = obj.getChildDBName();
+ String abstractType = obj.getMetadata(ObjectMetadata.ABSTRACT);
+ if (abstractType != null) {
+ String[] inheritors = obj.getMetadata(ObjectMetadata.INHERITORS).split(",");
+ traversal.has(AAIProperties.NODE_TYPE, P.within(inheritors));
+ } else {
+ traversal.has(AAIProperties.NODE_TYPE, type);
+ }
+ stepIndex++;
+ markContainer();
+ return (QueryBuilder<Vertex>) this;
+ }
+
+ /**
+ * @throws NoEdgeRuleFoundException
+ * @throws AAIException
+ * @{inheritDoc}
+ */
+ @Override
+ public QueryBuilder<Vertex> createEdgeTraversal(EdgeType type, Introspector parent, Introspector child)
+ throws AAIException {
+ createTraversal(type, parent, child, false);
+ return (QueryBuilder<Vertex>) this;
+
+ }
+
+ @Override
+ public QueryBuilder<Vertex> createPrivateEdgeTraversal(EdgeType type, Introspector parent, Introspector child)
+ throws AAIException {
+ this.createTraversal(type, parent, child, true);
+ return (QueryBuilder<Vertex>) this;
+ }
+
+ private void createTraversal(EdgeType type, Introspector parent, Introspector child, boolean isPrivateEdge)
+ throws AAIException {
+ String isAbstractType = parent.getMetadata(ObjectMetadata.ABSTRACT);
+ if ("true".equals(isAbstractType)) {
+ markParentBoundary();
+ traversal.union(handleAbstractEdge(type, parent, child, isPrivateEdge));
+ stepIndex++;
+ } else {
+ this.edgeQueryToVertex(type, parent, child, null);
+ }
+ }
+
+ /**
+ *
+ * @{inheritDoc}
+ */
+ @Override
+ public QueryBuilder<Vertex> createEdgeTraversalWithLabels(EdgeType type, Introspector out, Introspector in,
+ List<String> labels) throws AAIException {
+ this.edgeQueryToVertex(type, out, in, labels);
+ return (QueryBuilder<Vertex>) this;
+ }
+
+ private Traversal<Vertex, Vertex>[] handleAbstractEdge(EdgeType type, Introspector abstractParent,
+ Introspector child, boolean isPrivateEdge) throws AAIException {
+ String childName = child.getDbName();
+ String inheritorMetadata = abstractParent.getMetadata(ObjectMetadata.INHERITORS);
+ String[] inheritors = inheritorMetadata.split(",");
+ List<Traversal<Vertex, Vertex>> unionTraversals = new ArrayList<>(inheritors.length);
+
+ for (int i = 0; i < inheritors.length; i++) {
+ String inheritor = inheritors[i];
+ EdgeRuleQuery.Builder qB = new EdgeRuleQuery.Builder(inheritor, childName);
+ if (edgeRules.hasRule(qB.build())) {
+ Multimap<String, EdgeRule> rules = ArrayListMultimap.create();
+ try {
+ rules = edgeRules.getRules(qB.edgeType(type).build());
+ } catch (EdgeRuleNotFoundException e) {
+ throw new NoEdgeRuleFoundException(e);
+ }
+
+ GraphTraversal<Vertex, Vertex> innerTraversal = __.start();
+
+ final List<String> inLabels = new ArrayList<>();
+ final List<String> outLabels = new ArrayList<>();
+
+ rules.values().forEach(rule -> {
+ if (rule.getDirection().equals(Direction.IN)) {
+ inLabels.add(rule.getLabel());
+ } else {
+ outLabels.add(rule.getLabel());
+ }
+ });
+
+ if (inLabels.isEmpty() && !outLabels.isEmpty()) {
+ innerTraversal.out(outLabels.toArray(new String[outLabels.size()]));
+ } else if (outLabels.isEmpty() && !inLabels.isEmpty()) {
+ innerTraversal.in(inLabels.toArray(new String[inLabels.size()]));
+ } else {
+ innerTraversal.union(__.out(outLabels.toArray(new String[outLabels.size()])),
+ __.in(inLabels.toArray(new String[inLabels.size()])));
+ }
+
+ innerTraversal.has(AAIProperties.NODE_TYPE, childName);
+ unionTraversals.add(innerTraversal);
+ }
+ }
+
+ return unionTraversals.toArray(new Traversal[unionTraversals.size()]);
+ }
+
+ public QueryBuilder<Edge> getEdgesBetweenWithLabels(EdgeType type, String outNodeType, String inNodeType,
+ List<String> labels) throws AAIException {
+ Introspector outObj = loader.introspectorFromName(outNodeType);
+ Introspector inObj = loader.introspectorFromName(inNodeType);
+ this.edgeQuery(type, outObj, inObj, labels);
+
+ return (QueryBuilder<Edge>) this;
+ }
+
+ /**
+ * @{inheritDoc}
+ */
+ @Override
+ public QueryBuilder<E> union(QueryBuilder... builder) {
+ GraphTraversal<Vertex, Vertex>[] traversals = new GraphTraversal[builder.length];
+ for (int i = 0; i < builder.length; i++) {
+ traversals[i] = (GraphTraversal<Vertex, Vertex>) builder[i].getQuery();
+ }
+ this.traversal.union(traversals);
+ stepIndex++;
+
+ return this;
+ }
+
+ /**
+ * @{inheritDoc}
+ */
+ @Override
+ public QueryBuilder<E> where(QueryBuilder... builder) {
+ for (int i = 0; i < builder.length; i++) {
+ this.traversal.where((GraphTraversal<Vertex, Vertex>) builder[i].getQuery());
+ stepIndex++;
+ }
- /**
- * @{inheritDoc}
- */
- @Override
- public QueryBuilder<Vertex> getChildVerticesFromParent(String parentKey, String parentValue, String childType) {
- traversal.has(parentKey, parentValue).has(AAIProperties.NODE_TYPE, childType);
- stepIndex++;
- return (QueryBuilder<Vertex>) this;
- }
-
- /**
- * @{inheritDoc}
- */
- @Override
- public QueryBuilder<Vertex> getTypedVerticesByMap(String type, Map<String, String> map) {
-
- for (Map.Entry<String, String> es : map.entrySet()) {
- traversal.has(es.getKey(), es.getValue());
- stepIndex++;
- }
- traversal.has(AAIProperties.NODE_TYPE, type);
- stepIndex++;
- return (QueryBuilder<Vertex>) this;
- }
-
- @Override
- public QueryBuilder<Vertex> getVerticesByBooleanProperty(String key, Object value) {
-
- if(value!=null && !"".equals(value)) {
- boolean bValue = false;
-
- if(value instanceof String){//"true"
- bValue = Boolean.valueOf(value.toString());
- } else if(value instanceof Boolean){//true
- bValue = (Boolean) value;
- }
-
- traversal.has(key, bValue);
- stepIndex++;
- }
- return (QueryBuilder<Vertex>) this;
- }
-
- /**
- * @{inheritDoc}
- */
- @Override
- public QueryBuilder<Vertex> createKeyQuery(Introspector obj) {
- Set<String> keys = obj.getKeys();
- Object val;
- for (String key : keys) {
- val = obj.getValue(key);
- Optional<String> metadata = obj.getPropertyMetadata(key, PropertyMetadata.DB_ALIAS);
- if (metadata.isPresent()) {
- //use the db name for the field rather than the object model
- key = metadata.get();
- }
- if (val != null) {
- //this is because the index is registered as an Integer
- if (val.getClass().equals(Long.class)) {
- traversal.has(key,new Integer(val.toString()));
- } else {
- traversal.has(key, val);
- }
- stepIndex++;
- }
- }
- return (QueryBuilder<Vertex>) this;
- }
-
- @Override
- public QueryBuilder<Vertex> exactMatchQuery(Introspector obj) {
- this.createKeyQuery(obj);
- allPropertiesQuery(obj);
- this.createContainerQuery(obj);
- return (QueryBuilder<Vertex>) this;
- }
-
- private void allPropertiesQuery(Introspector obj) {
- Set<String> props = obj.getProperties();
- Set<String> keys = obj.getKeys();
- Object val;
- for (String prop : props) {
- if (obj.isSimpleType(prop) && !keys.contains(prop)) {
- val = obj.getValue(prop);
- if (val != null) {
- Optional<String> metadata = obj.getPropertyMetadata(prop, PropertyMetadata.DB_ALIAS);
- if (metadata.isPresent()) {
- //use the db name for the field rather than the object model
- prop = metadata.get();
- }
- //this is because the index is registered as an Integer
- if (val.getClass().equals(Long.class)) {
- traversal.has(prop,new Integer(val.toString()));
- } else {
- traversal.has(prop, val);
- }
- stepIndex++;
- }
- }
- }
- }
-
- /**
- * @{inheritDoc}
- */
- @Override
-
- public QueryBuilder<Vertex> createContainerQuery(Introspector obj) {
- String type = obj.getChildDBName();
- String abstractType = obj.getMetadata(ObjectMetadata.ABSTRACT);
- if (abstractType != null) {
- String[] inheritors = obj.getMetadata(ObjectMetadata.INHERITORS).split(",");
- traversal.has(AAIProperties.NODE_TYPE, P.within(inheritors));
- } else {
- traversal.has(AAIProperties.NODE_TYPE, type);
- }
- stepIndex++;
- markContainer();
- return (QueryBuilder<Vertex>) this;
- }
-
- /**
- * @throws NoEdgeRuleFoundException
- * @throws AAIException
- * @{inheritDoc}
- */
- @Override
- public QueryBuilder<Vertex> createEdgeTraversal(EdgeType type, Introspector parent, Introspector child) throws AAIException {
- createTraversal(type, parent, child, false);
- return (QueryBuilder<Vertex>) this;
-
- }
-
- @Override
- public QueryBuilder<Vertex> createPrivateEdgeTraversal(EdgeType type, Introspector parent, Introspector child) throws AAIException {
- this.createTraversal(type, parent, child, true);
- return (QueryBuilder<Vertex>) this;
- }
-
- private void createTraversal(EdgeType type, Introspector parent, Introspector child, boolean isPrivateEdge) throws AAIException {
- String isAbstractType = parent.getMetadata(ObjectMetadata.ABSTRACT);
- if ("true".equals(isAbstractType)) {
- markParentBoundary();
- traversal.union(handleAbstractEdge(type, parent, child, isPrivateEdge));
- stepIndex++;
- } else {
- this.edgeQueryToVertex(type, parent, child, null);
- }
- }
-
- /**
- *
- * @{inheritDoc}
- */
- @Override
- public QueryBuilder<Vertex> createEdgeTraversalWithLabels(EdgeType type, Introspector out, Introspector in, List<String> labels) throws AAIException {
- this.edgeQueryToVertex(type, out, in, labels);
- return (QueryBuilder<Vertex>) this;
- }
-
- private Traversal<Vertex, Vertex>[] handleAbstractEdge(EdgeType type, Introspector abstractParent, Introspector child, boolean isPrivateEdge) throws AAIException {
- String childName = child.getDbName();
- String inheritorMetadata = abstractParent.getMetadata(ObjectMetadata.INHERITORS);
- String[] inheritors = inheritorMetadata.split(",");
- List<Traversal<Vertex, Vertex>> unionTraversals = new ArrayList<>(inheritors.length);
-
- for (int i = 0; i < inheritors.length; i++) {
- String inheritor = inheritors[i];
- EdgeRuleQuery.Builder qB = new EdgeRuleQuery.Builder(inheritor, childName);
- if (edgeRules.hasRule(qB.build())) {
- Multimap<String, EdgeRule> rules = ArrayListMultimap.create();
- try {
- rules = edgeRules.getRules(qB.edgeType(type).build());
- } catch (EdgeRuleNotFoundException e) {
- throw new NoEdgeRuleFoundException(e);
- }
-
- GraphTraversal<Vertex, Vertex> innerTraversal = __.start();
-
- final List<String> inLabels = new ArrayList<>();
- final List<String> outLabels = new ArrayList<>();
-
- rules.values().forEach(rule -> {
- if (rule.getDirection().equals(Direction.IN)) {
- inLabels.add(rule.getLabel());
- } else {
- outLabels.add(rule.getLabel());
- }
- } );
-
- if (inLabels.isEmpty() && !outLabels.isEmpty()) {
- innerTraversal.out(outLabels.toArray(new String[outLabels.size()]));
- } else if (outLabels.isEmpty() && !inLabels.isEmpty()) {
- innerTraversal.in(inLabels.toArray(new String[inLabels.size()]));
- } else {
- innerTraversal.union(__.out(outLabels.toArray(new String[outLabels.size()])), __.in(inLabels.toArray(new String[inLabels.size()])));
- }
-
- innerTraversal.has(AAIProperties.NODE_TYPE, childName);
- unionTraversals.add(innerTraversal);
- }
- }
-
- return unionTraversals.toArray(new Traversal[unionTraversals.size()]);
- }
-
- public QueryBuilder<Edge> getEdgesBetweenWithLabels(EdgeType type, String outNodeType, String inNodeType, List<String> labels) throws AAIException {
- Introspector outObj = loader.introspectorFromName(outNodeType);
- Introspector inObj = loader.introspectorFromName(inNodeType);
- this.edgeQuery(type, outObj, inObj, labels);
-
- return (QueryBuilder<Edge>)this;
- }
-
-
- /**
- * @{inheritDoc}
- */
- @Override
- public QueryBuilder<E> union(QueryBuilder... builder) {
- GraphTraversal<Vertex, Vertex>[] traversals = new GraphTraversal[builder.length];
- for (int i = 0; i < builder.length; i++) {
- traversals[i] = (GraphTraversal<Vertex, Vertex>)builder[i].getQuery();
- }
- this.traversal.union(traversals);
- stepIndex++;
-
- return this;
- }
-
- /**
- * @{inheritDoc}
- */
- @Override
- public QueryBuilder<E> where(QueryBuilder... builder) {
- for (int i = 0; i < builder.length; i++) {
- this.traversal.where((GraphTraversal<Vertex, Vertex>)builder[i].getQuery());
- stepIndex++;
- }
-
- return this;
- }
-
- /**
- * @{inheritDoc}
- */
- @Override
- public QueryBuilder<E> or(QueryBuilder... builder) {
- GraphTraversal<Vertex, Vertex>[] traversals = new GraphTraversal[builder.length];
- for (int i = 0; i < builder.length; i++) {
- traversals[i] = (GraphTraversal<Vertex, Vertex>)builder[i].getQuery();
- }
- this.traversal.or(traversals);
- stepIndex++;
-
- return this;
- }
-
- @Override
- public QueryBuilder<E> store(String name) {
-
- this.traversal.store(name);
- stepIndex++;
-
- return this;
- }
-
- @Override
- public QueryBuilder<E> cap(String name) {
- this.traversal.cap(name);
- stepIndex++;
-
- return this;
- }
-
- @Override
- public QueryBuilder<E> unfold() {
- this.traversal.unfold();
- stepIndex++;
-
- return this;
- }
-
- @Override
- public QueryBuilder<E> dedup() {
-
- this.traversal.dedup();
- stepIndex++;
-
- return this;
- }
-
- @Override
- public QueryBuilder<E> emit() {
-
- this.traversal.emit();
- stepIndex++;
-
- return this;
-
- }
-
- @Override
- public QueryBuilder<E> repeat(QueryBuilder<E> builder) {
-
- this.traversal.repeat((GraphTraversal<Vertex, E>)builder.getQuery());
- stepIndex++;
-
- return this;
- }
-
- @Override
- public QueryBuilder<E> until(QueryBuilder<E> builder) {
- this.traversal.until((GraphTraversal<Vertex,E>)builder.getQuery());
- stepIndex++;
-
- return this;
- }
-
- @Override
- public QueryBuilder<E> groupCount() {
- this.traversal.groupCount();
- stepIndex++;
-
- return this;
- }
-
- @Override
- public QueryBuilder<E> both() {
- this.traversal.both();
- stepIndex++;
-
- return this;
- }
-
- @Override
- public QueryBuilder<Tree> tree() {
-
- this.traversal.tree();
- stepIndex++;
-
- return (QueryBuilder<Tree>)this;
- }
-
- @Override
- public QueryBuilder<E> by(String name) {
- this.traversal.by(name);
- stepIndex++;
-
- return this;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public QueryBuilder<E> simplePath(){
- this.traversal.simplePath();
- stepIndex++;
- return this;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public QueryBuilder<Path> path(){
- this.traversal.path();
- stepIndex++;
- return (QueryBuilder<Path>)this;
- }
-
- @Override
- public QueryBuilder<Edge> outE() {
- this.traversal.outE();
- stepIndex++;
- return (QueryBuilder<Edge>)this;
- }
-
- @Override
- public QueryBuilder<Edge> inE() {
- this.traversal.inE();
- stepIndex++;
- return (QueryBuilder<Edge>)this;
- }
-
- @Override
- public QueryBuilder<Vertex> outV() {
- this.traversal.outV();
- stepIndex++;
- return (QueryBuilder<Vertex>)this;
- }
-
- @Override
- public QueryBuilder<Vertex> inV() {
- this.traversal.inV();
- stepIndex++;
- return (QueryBuilder<Vertex>)this;
- }
-
- @Override
- public QueryBuilder<E> as(String name) {
- this.traversal.as(name);
-
- stepIndex++;
- return this;
- }
-
- @Override
- public QueryBuilder<E> not(QueryBuilder<E> builder) {
- this.traversal.not(builder.getQuery());
-
- stepIndex++;
- return this;
- }
-
- @Override
- public QueryBuilder<E> select(String name) {
- this.traversal.select(name);
-
- stepIndex++;
-
- return this;
- }
-
- @Override
- public QueryBuilder<E> select(String... names) {
- if(names.length == 1) {
- this.traversal.select(names[0]);
- }
- else if(names.length == 2) {
- this.traversal.select(names[0], names[1]);
- }
- else if(names.length > 2){
- String[] otherNames = Arrays.copyOfRange(names, 2, names.length);
- this.traversal.select(names[0], names[1], otherNames);
- }
-
- stepIndex++;
-
- return this;
- }
-
- /**
- * Edge query.
- *
- * @param outObj the out type
- * @param inObj the in type
- * @throws NoEdgeRuleFoundException
- * @throws AAIException
- */
- private void edgeQueryToVertex(EdgeType type, Introspector outObj, Introspector inObj, List<String> labels) throws AAIException {
- String outType = outObj.getDbName();
- String inType = inObj.getDbName();
-
- if (outObj.isContainer()) {
- outType = outObj.getChildDBName();
- }
- if (inObj.isContainer()) {
- inType = inObj.getChildDBName();
- }
- markParentBoundary();
- Multimap<String, EdgeRule> rules = ArrayListMultimap.create();
- EdgeRuleQuery.Builder qB = new EdgeRuleQuery.Builder(outType, inType).edgeType(type);
-
- if (labels == null) {
- try {
- rules.putAll(edgeRules.getRules(qB.build()));
- } catch (EdgeRuleNotFoundException e) {
- //is ok per original functioning of this section
- //TODO add "best try" sort of flag to the EdgeRuleQuery
- // to indicate if the exception should be thrown or not
- }
- } else {
- for (String label : labels) {
- try {
- rules.putAll(edgeRules.getRules(qB.label(label).build()));
- } catch (EdgeRuleNotFoundException e) {
- throw new NoEdgeRuleFoundException(e);
- }
- }
- if (rules.isEmpty()) {
- throw new NoEdgeRuleFoundException("No edge rules found for " + outType + " and " + inType + " of type " + type.toString());
- }
- }
-
-
- final List<String> inLabels = new ArrayList<>();
- final List<String> outLabels = new ArrayList<>();
-
- for (EdgeRule rule : rules.values()) {
- if (labels != null && !labels.contains(rule.getLabel())) {
- return;
- } else {
- if (Direction.IN.equals(rule.getDirection())) {
- inLabels.add(rule.getLabel());
- } else {
- outLabels.add(rule.getLabel());
- }
- }
- }
-
- if (inLabels.isEmpty() && !outLabels.isEmpty()) {
- traversal.out(outLabels.toArray(new String[outLabels.size()]));
- } else if (outLabels.isEmpty() && !inLabels.isEmpty()) {
- traversal.in(inLabels.toArray(new String[inLabels.size()]));
- } else {
- traversal.union(__.out(outLabels.toArray(new String[outLabels.size()])), __.in(inLabels.toArray(new String[inLabels.size()])));
- }
-
- stepIndex++;
-
- this.createContainerQuery(inObj);
-
- }
-
- /**
- * Edge query.
- *
- * @param outObj the out type
- * @param inObj the in type
- * @throws NoEdgeRuleFoundException
- * @throws AAIException
- */
- private void edgeQuery(EdgeType type, Introspector outObj, Introspector inObj, List<String> labels) throws AAIException {
- String outType = outObj.getDbName();
- String inType = inObj.getDbName();
-
- if (outObj.isContainer()) {
- outType = outObj.getChildDBName();
- }
- if (inObj.isContainer()) {
- inType = inObj.getChildDBName();
- }
-
- markParentBoundary();
- Multimap<String, EdgeRule> rules = ArrayListMultimap.create();
- EdgeRuleQuery.Builder qB = new EdgeRuleQuery.Builder(outType, inType).edgeType(type);
-
- try {
- if (labels == null) {
- rules.putAll(edgeRules.getRules(qB.build()));
- } else {
- for (String label : labels) {
- rules.putAll(edgeRules.getRules(qB.label(label).build()));
- }
- }
- } catch (EdgeRuleNotFoundException e) {
- throw new NoEdgeRuleFoundException(e);
- }
-
- final List<String> inLabels = new ArrayList<>();
- final List<String> outLabels = new ArrayList<>();
-
- for (EdgeRule rule : rules.values()) {
- if (labels != null && !labels.contains(rule.getLabel())) {
- return;
- } else {
- if (Direction.IN.equals(rule.getDirection())) {
- inLabels.add(rule.getLabel());
- } else {
- outLabels.add(rule.getLabel());
- }
- }
- }
-
- if (inLabels.isEmpty() && !outLabels.isEmpty()) {
- traversal.outE(outLabels.toArray(new String[outLabels.size()]));
- } else if (outLabels.isEmpty() && !inLabels.isEmpty()) {
- traversal.inE(inLabels.toArray(new String[inLabels.size()]));
- } else {
- traversal.union(__.outE(outLabels.toArray(new String[outLabels.size()])), __.inE(inLabels.toArray(new String[inLabels.size()])));
- }
- }
-
- @Override
- public QueryBuilder<E> limit(long amount) {
- traversal.limit(amount);
- return this;
- }
-
- /**
- * @{inheritDoc}
- */
- @Override
- public <E2> E2 getQuery() {
- return (E2)this.traversal;
- }
-
- /**
- * @{inheritDoc}
- */
- @Override
- public QueryBuilder<E> getParentQuery() {
-
- return cloneQueryAtStep(parentStepIndex);
- }
-
- @Override
- public QueryBuilder<E> getContainerQuery() {
-
- if (this.parentStepIndex == 0) {
- return removeQueryStepsBetween(0, containerStepIndex);
- } else {
- return cloneQueryAtStep(containerStepIndex);
- }
- }
-
- /**
- * @{inheritDoc}
- */
- @Override
- public void markParentBoundary() {
- parentStepIndex = stepIndex;
- }
-
- @Override
- public void markContainer() {
- containerStepIndex = stepIndex;
- }
-
-
- /**
- * @{inheritDoc}
- */
- @Override
- public Vertex getStart() {
- return this.start;
- }
-
- protected int getParentStepIndex() {
- return parentStepIndex;
- }
-
- protected int getContainerStepIndex() {
- return containerStepIndex;
- }
-
- protected int getStepIndex() {
- return stepIndex;
- }
-
- /**
- * end is exclusive
- *
- * @param start
- * @param end
- * @return
- */
- protected abstract QueryBuilder<E> removeQueryStepsBetween(int start, int end);
-
- protected void executeQuery() {
-
- Admin admin;
- if (start != null) {
- this.completeTraversal = traversal.asAdmin();
- } else {
- admin = source.V().asAdmin();
- TraversalHelper.insertTraversal(admin.getEndStep(), traversal.asAdmin(), admin);
-
- this.completeTraversal = (Admin<Vertex, E>) admin;
-
- }
-
- }
-
- @Override
- public boolean hasNext() {
- if (this.completeTraversal == null) {
- executeQuery();
- }
-
- return this.completeTraversal.hasNext();
- }
-
- @Override
- public E next() {
- if (this.completeTraversal == null) {
- executeQuery();
- }
-
- return this.completeTraversal.next();
- }
-
- @Override
- public List<E> toList() {
- if (this.completeTraversal == null) {
- executeQuery();
- }
- return this.completeTraversal.toList();
- }
-
- protected QueryBuilder<Edge> has(String key, String value) {
- traversal.has(key, value);
-
- return (QueryBuilder<Edge>)this;
- }
+ return this;
+ }
+
+ /**
+ * @{inheritDoc}
+ */
+ @Override
+ public QueryBuilder<E> or(QueryBuilder... builder) {
+ GraphTraversal<Vertex, Vertex>[] traversals = new GraphTraversal[builder.length];
+ for (int i = 0; i < builder.length; i++) {
+ traversals[i] = (GraphTraversal<Vertex, Vertex>) builder[i].getQuery();
+ }
+ this.traversal.or(traversals);
+ stepIndex++;
+
+ return this;
+ }
+
+ @Override
+ public QueryBuilder<E> store(String name) {
+
+ this.traversal.store(name);
+ stepIndex++;
+
+ return this;
+ }
+
+ @Override
+ public QueryBuilder<E> cap(String name) {
+ this.traversal.cap(name);
+ stepIndex++;
+
+ return this;
+ }
+
+ @Override
+ public QueryBuilder<E> unfold() {
+ this.traversal.unfold();
+ stepIndex++;
+
+ return this;
+ }
+
+ @Override
+ public QueryBuilder<E> dedup() {
+
+ this.traversal.dedup();
+ stepIndex++;
+
+ return this;
+ }
+
+ @Override
+ public QueryBuilder<E> emit() {
+
+ this.traversal.emit();
+ stepIndex++;
+
+ return this;
+
+ }
+
+ @Override
+ public QueryBuilder<E> repeat(QueryBuilder<E> builder) {
+
+ this.traversal.repeat((GraphTraversal<Vertex, E>) builder.getQuery());
+ stepIndex++;
+
+ return this;
+ }
+
+ @Override
+ public QueryBuilder<E> until(QueryBuilder<E> builder) {
+ this.traversal.until((GraphTraversal<Vertex, E>) builder.getQuery());
+ stepIndex++;
+
+ return this;
+ }
+
+ @Override
+ public QueryBuilder<E> groupCount() {
+ this.traversal.groupCount();
+ stepIndex++;
+
+ return this;
+ }
+
+ @Override
+ public QueryBuilder<E> both() {
+ this.traversal.both();
+ stepIndex++;
+
+ return this;
+ }
+
+ @Override
+ public QueryBuilder<Tree> tree() {
+
+ this.traversal.tree();
+ stepIndex++;
+
+ return (QueryBuilder<Tree>) this;
+ }
+
+ @Override
+ public QueryBuilder<E> by(String name) {
+ this.traversal.by(name);
+ stepIndex++;
+
+ return this;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public QueryBuilder<E> simplePath() {
+ this.traversal.simplePath();
+ stepIndex++;
+ return this;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public QueryBuilder<Path> path() {
+ this.traversal.path();
+ stepIndex++;
+ return (QueryBuilder<Path>) this;
+ }
+
+ @Override
+ public QueryBuilder<Edge> outE() {
+ this.traversal.outE();
+ stepIndex++;
+ return (QueryBuilder<Edge>) this;
+ }
+
+ @Override
+ public QueryBuilder<Edge> inE() {
+ this.traversal.inE();
+ stepIndex++;
+ return (QueryBuilder<Edge>) this;
+ }
+
+ @Override
+ public QueryBuilder<Vertex> outV() {
+ this.traversal.outV();
+ stepIndex++;
+ return (QueryBuilder<Vertex>) this;
+ }
+
+ @Override
+ public QueryBuilder<Vertex> inV() {
+ this.traversal.inV();
+ stepIndex++;
+ return (QueryBuilder<Vertex>) this;
+ }
+
+ @Override
+ public QueryBuilder<E> as(String name) {
+ this.traversal.as(name);
+
+ stepIndex++;
+ return this;
+ }
+
+ @Override
+ public QueryBuilder<E> not(QueryBuilder<E> builder) {
+ this.traversal.not(builder.getQuery());
+
+ stepIndex++;
+ return this;
+ }
+
+ @Override
+ public QueryBuilder<E> select(String name) {
+ this.traversal.select(name);
+
+ stepIndex++;
+
+ return this;
+ }
+
+ @Override
+ public QueryBuilder<E> select(String... names) {
+ if (names.length == 1) {
+ this.traversal.select(names[0]);
+ } else if (names.length == 2) {
+ this.traversal.select(names[0], names[1]);
+ } else if (names.length > 2) {
+ String[] otherNames = Arrays.copyOfRange(names, 2, names.length);
+ this.traversal.select(names[0], names[1], otherNames);
+ }
+
+ stepIndex++;
+
+ return this;
+ }
+
+ /**
+ * Edge query.
+ *
+ * @param outObj the out type
+ * @param inObj the in type
+ * @throws NoEdgeRuleFoundException
+ * @throws AAIException
+ */
+ private void edgeQueryToVertex(EdgeType type, Introspector outObj, Introspector inObj, List<String> labels)
+ throws AAIException {
+ String outType = outObj.getDbName();
+ String inType = inObj.getDbName();
+
+ if (outObj.isContainer()) {
+ outType = outObj.getChildDBName();
+ }
+ if (inObj.isContainer()) {
+ inType = inObj.getChildDBName();
+ }
+ markParentBoundary();
+ Multimap<String, EdgeRule> rules = ArrayListMultimap.create();
+ EdgeRuleQuery.Builder qB = new EdgeRuleQuery.Builder(outType, inType).edgeType(type);
+
+ if (labels == null) {
+ try {
+ rules.putAll(edgeRules.getRules(qB.build()));
+ } catch (EdgeRuleNotFoundException e) {
+ // is ok per original functioning of this section
+ // TODO add "best try" sort of flag to the EdgeRuleQuery
+ // to indicate if the exception should be thrown or not
+ }
+ } else {
+ for (String label : labels) {
+ try {
+ rules.putAll(edgeRules.getRules(qB.label(label).build()));
+ } catch (EdgeRuleNotFoundException e) {
+ throw new NoEdgeRuleFoundException(e);
+ }
+ }
+ if (rules.isEmpty()) {
+ throw new NoEdgeRuleFoundException(
+ "No edge rules found for " + outType + " and " + inType + " of type " + type.toString());
+ }
+ }
+
+ final List<String> inLabels = new ArrayList<>();
+ final List<String> outLabels = new ArrayList<>();
+
+ for (EdgeRule rule : rules.values()) {
+ if (labels != null && !labels.contains(rule.getLabel())) {
+ return;
+ } else {
+ if (Direction.IN.equals(rule.getDirection())) {
+ inLabels.add(rule.getLabel());
+ } else {
+ outLabels.add(rule.getLabel());
+ }
+ }
+ }
+
+ if (inLabels.isEmpty() && !outLabels.isEmpty()) {
+ traversal.out(outLabels.toArray(new String[outLabels.size()]));
+ } else if (outLabels.isEmpty() && !inLabels.isEmpty()) {
+ traversal.in(inLabels.toArray(new String[inLabels.size()]));
+ } else {
+ traversal.union(__.out(outLabels.toArray(new String[outLabels.size()])),
+ __.in(inLabels.toArray(new String[inLabels.size()])));
+ }
+
+ stepIndex++;
+
+ this.createContainerQuery(inObj);
+
+ }
+
+ /**
+ * Edge query.
+ *
+ * @param outObj the out type
+ * @param inObj the in type
+ * @throws NoEdgeRuleFoundException
+ * @throws AAIException
+ */
+ private void edgeQuery(EdgeType type, Introspector outObj, Introspector inObj, List<String> labels)
+ throws AAIException {
+ String outType = outObj.getDbName();
+ String inType = inObj.getDbName();
+
+ if (outObj.isContainer()) {
+ outType = outObj.getChildDBName();
+ }
+ if (inObj.isContainer()) {
+ inType = inObj.getChildDBName();
+ }
+
+ markParentBoundary();
+ Multimap<String, EdgeRule> rules = ArrayListMultimap.create();
+ EdgeRuleQuery.Builder qB = new EdgeRuleQuery.Builder(outType, inType).edgeType(type);
+
+ try {
+ if (labels == null) {
+ rules.putAll(edgeRules.getRules(qB.build()));
+ } else {
+ for (String label : labels) {
+ rules.putAll(edgeRules.getRules(qB.label(label).build()));
+ }
+ }
+ } catch (EdgeRuleNotFoundException e) {
+ throw new NoEdgeRuleFoundException(e);
+ }
+
+ final List<String> inLabels = new ArrayList<>();
+ final List<String> outLabels = new ArrayList<>();
+
+ for (EdgeRule rule : rules.values()) {
+ if (labels != null && !labels.contains(rule.getLabel())) {
+ return;
+ } else {
+ if (Direction.IN.equals(rule.getDirection())) {
+ inLabels.add(rule.getLabel());
+ } else {
+ outLabels.add(rule.getLabel());
+ }
+ }
+ }
+
+ if (inLabels.isEmpty() && !outLabels.isEmpty()) {
+ traversal.outE(outLabels.toArray(new String[outLabels.size()]));
+ } else if (outLabels.isEmpty() && !inLabels.isEmpty()) {
+ traversal.inE(inLabels.toArray(new String[inLabels.size()]));
+ } else {
+ traversal.union(__.outE(outLabels.toArray(new String[outLabels.size()])),
+ __.inE(inLabels.toArray(new String[inLabels.size()])));
+ }
+ }
+
+ @Override
+ public QueryBuilder<E> limit(long amount) {
+ traversal.limit(amount);
+ return this;
+ }
+
+ /**
+ * @{inheritDoc}
+ */
+ @Override
+ public <E2> E2 getQuery() {
+ return (E2) this.traversal;
+ }
+
+ /**
+ * @{inheritDoc}
+ */
+ @Override
+ public QueryBuilder<E> getParentQuery() {
+
+ return cloneQueryAtStep(parentStepIndex);
+ }
+
+ @Override
+ public QueryBuilder<E> getContainerQuery() {
+
+ if (this.parentStepIndex == 0) {
+ return removeQueryStepsBetween(0, containerStepIndex);
+ } else {
+ return cloneQueryAtStep(containerStepIndex);
+ }
+ }
+
+ /**
+ * @{inheritDoc}
+ */
+ @Override
+ public void markParentBoundary() {
+ parentStepIndex = stepIndex;
+ }
+
+ @Override
+ public void markContainer() {
+ containerStepIndex = stepIndex;
+ }
+
+ /**
+ * @{inheritDoc}
+ */
+ @Override
+ public Vertex getStart() {
+ return this.start;
+ }
+
+ protected int getParentStepIndex() {
+ return parentStepIndex;
+ }
+
+ protected int getContainerStepIndex() {
+ return containerStepIndex;
+ }
+
+ protected int getStepIndex() {
+ return stepIndex;
+ }
+
+ /**
+ * end is exclusive
+ *
+ * @param start
+ * @param end
+ * @return
+ */
+ protected abstract QueryBuilder<E> removeQueryStepsBetween(int start, int end);
+
+ protected void executeQuery() {
+
+ Admin admin;
+ if (start != null) {
+ this.completeTraversal = traversal.asAdmin();
+ } else {
+ admin = source.V().asAdmin();
+ TraversalHelper.insertTraversal(admin.getEndStep(), traversal.asAdmin(), admin);
+
+ this.completeTraversal = (Admin<Vertex, E>) admin;
+
+ }
+
+ }
+
+ @Override
+ public boolean hasNext() {
+ if (this.completeTraversal == null) {
+ executeQuery();
+ }
+
+ return this.completeTraversal.hasNext();
+ }
+
+ @Override
+ public E next() {
+ if (this.completeTraversal == null) {
+ executeQuery();
+ }
+
+ return this.completeTraversal.next();
+ }
+
+ @Override
+ public List<E> toList() {
+ if (this.completeTraversal == null) {
+ executeQuery();
+ }
+ return this.completeTraversal.toList();
+ }
+
+ protected QueryBuilder<Edge> has(String key, String value) {
+ traversal.has(key, value);
+
+ return (QueryBuilder<Edge>) this;
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/query/builder/GremlinQueryBuilder.java b/aai-core/src/main/java/org/onap/aai/query/builder/GremlinQueryBuilder.java
index 1dc2cfe8..98da0766 100644
--- a/aai-core/src/main/java/org/onap/aai/query/builder/GremlinQueryBuilder.java
+++ b/aai-core/src/main/java/org/onap/aai/query/builder/GremlinQueryBuilder.java
@@ -19,12 +19,15 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.query.builder;
import com.google.common.base.Joiner;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
+import java.util.*;
+
import org.apache.tinkerpop.gremlin.process.traversal.Path;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
@@ -33,19 +36,17 @@ import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.onap.aai.db.props.AAIProperties;
+import org.onap.aai.edges.EdgeRule;
+import org.onap.aai.edges.EdgeRuleQuery;
+import org.onap.aai.edges.enums.EdgeType;
+import org.onap.aai.edges.exceptions.EdgeRuleNotFoundException;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.introspection.Introspector;
import org.onap.aai.introspection.Loader;
import org.onap.aai.restcore.search.GremlinGroovyShell;
import org.onap.aai.schema.enums.ObjectMetadata;
-import org.onap.aai.edges.EdgeRule;
-import org.onap.aai.edges.EdgeRuleQuery;
-import org.onap.aai.edges.enums.EdgeType;
-import org.onap.aai.edges.exceptions.EdgeRuleNotFoundException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
-import java.util.*;
-
/**
* The Class GremlinQueryBuilder.
*/
@@ -93,7 +94,7 @@ public abstract class GremlinQueryBuilder<E> extends QueryBuilder<E> {
public QueryBuilder<Vertex> getVerticesByProperty(String key, Object value) {
String term = "";
- if (value != null && !(value instanceof String) ) {
+ if (value != null && !(value instanceof String)) {
term = value.toString();
} else {
term = "'" + value + "'";
@@ -115,18 +116,18 @@ public abstract class GremlinQueryBuilder<E> extends QueryBuilder<E> {
@Override
public QueryBuilder<Vertex> getVerticesByBooleanProperty(String key, Object value) {
-
- if(value!=null && !"".equals(value)) {
- boolean bValue = false;
- if(value instanceof String){
- bValue = Boolean.valueOf(value.toString());
- } else if(value instanceof Boolean){
- bValue = (Boolean) value;
- }
-
- list.add(HAS + key + "', " + bValue + ")");
- stepIndex++;
- }
+
+ if (value != null && !"".equals(value)) {
+ boolean bValue = false;
+ if (value instanceof String) {
+ bValue = Boolean.valueOf(value.toString());
+ } else if (value instanceof Boolean) {
+ bValue = (Boolean) value;
+ }
+
+ list.add(HAS + key + "', " + bValue + ")");
+ stepIndex++;
+ }
return (QueryBuilder<Vertex>) this;
}
@@ -182,7 +183,7 @@ public abstract class GremlinQueryBuilder<E> extends QueryBuilder<E> {
String term = "";
String predicate = "org.janusgraph.core.attribute.Text.textPrefix(#!#argument#!#)";
- if (value != null && !(value instanceof String) ) {
+ if (value != null && !(value instanceof String)) {
term = value.toString();
} else {
term = "'" + value + "'";
@@ -201,7 +202,7 @@ public abstract class GremlinQueryBuilder<E> extends QueryBuilder<E> {
String term = "";
String predicate = "P.neq(#!#argument#!#)";
- if (value != null && !(value instanceof String) ) {
+ if (value != null && !(value instanceof String)) {
term = value.toString();
} else {
term = "'" + value + "'";
@@ -238,7 +239,7 @@ public abstract class GremlinQueryBuilder<E> extends QueryBuilder<E> {
public QueryBuilder<Vertex> getVerticesGreaterThanProperty(String key, Object value) {
String predicate = "P.gte(#!#argument1#!#)";
String term;
- if (value != null && !(value instanceof String) ) {
+ if (value != null && !(value instanceof String)) {
term = value.toString();
} else {
term = "'" + value + "'";
@@ -253,7 +254,7 @@ public abstract class GremlinQueryBuilder<E> extends QueryBuilder<E> {
public QueryBuilder<Vertex> getVerticesLessThanProperty(String key, Object value) {
String predicate = "P.lte(#!#argument1#!#)";
String term;
- if (value != null && !(value instanceof String) ) {
+ if (value != null && !(value instanceof String)) {
term = value.toString();
} else {
term = "'" + value + "'";
@@ -264,15 +265,12 @@ public abstract class GremlinQueryBuilder<E> extends QueryBuilder<E> {
return (QueryBuilder<Vertex>) this;
}
-
-
-
/**
* @{inheritDoc}
*/
@Override
public QueryBuilder<Vertex> getChildVerticesFromParent(String parentKey, String parentValue, String childType) {
- //TODO
+ // TODO
return (QueryBuilder<Vertex>) this;
}
@@ -312,7 +310,8 @@ public abstract class GremlinQueryBuilder<E> extends QueryBuilder<E> {
* @{inheritDoc}
*/
@Override
- public QueryBuilder createEdgeTraversal(EdgeType type, Introspector parent, Introspector child) throws AAIException {
+ public QueryBuilder createEdgeTraversal(EdgeType type, Introspector parent, Introspector child)
+ throws AAIException {
String parentName = parent.getDbName();
String childName = child.getDbName();
if (parent.isContainer()) {
@@ -327,7 +326,8 @@ public abstract class GremlinQueryBuilder<E> extends QueryBuilder<E> {
}
@Override
- public QueryBuilder createPrivateEdgeTraversal(EdgeType type, Introspector parent, Introspector child) throws AAIException{
+ public QueryBuilder createPrivateEdgeTraversal(EdgeType type, Introspector parent, Introspector child)
+ throws AAIException {
String parentName = parent.getDbName();
String childName = child.getDbName();
if (parent.isContainer()) {
@@ -345,7 +345,8 @@ public abstract class GremlinQueryBuilder<E> extends QueryBuilder<E> {
* @{inheritDoc}
*/
@Override
- public QueryBuilder<Vertex> createEdgeTraversalWithLabels(EdgeType type, Introspector out, Introspector in, List<String> labels) throws AAIException {
+ public QueryBuilder<Vertex> createEdgeTraversalWithLabels(EdgeType type, Introspector out, Introspector in,
+ List<String> labels) throws AAIException {
String parentName = out.getDbName();
String childName = in.getDbName();
if (out.isContainer()) {
@@ -358,13 +359,14 @@ public abstract class GremlinQueryBuilder<E> extends QueryBuilder<E> {
return (QueryBuilder<Vertex>) this;
}
-
- public QueryBuilder<Edge> getEdgesBetweenWithLabels(EdgeType type, String outNodeType, String inNodeType, List<String> labels) throws AAIException {
+ public QueryBuilder<Edge> getEdgesBetweenWithLabels(EdgeType type, String outNodeType, String inNodeType,
+ List<String> labels) throws AAIException {
this.edgeQuery(type, outNodeType, inNodeType, labels);
- return (QueryBuilder<Edge>)this;
+ return (QueryBuilder<Edge>) this;
}
- private void edgeQueryToVertex(EdgeType type, String outType, String inType, List<String> labels) throws AAIException {
+ private void edgeQueryToVertex(EdgeType type, String outType, String inType, List<String> labels)
+ throws AAIException {
this.edgeQueryToVertex(type, outType, inType, labels, false);
}
@@ -376,7 +378,8 @@ public abstract class GremlinQueryBuilder<E> extends QueryBuilder<E> {
* @throws NoEdgeRuleFoundException
* @throws AAIException
*/
- private void edgeQueryToVertex(EdgeType type, String outType, String inType, List<String> labels, boolean isPrivateEdge) throws AAIException {
+ private void edgeQueryToVertex(EdgeType type, String outType, String inType, List<String> labels,
+ boolean isPrivateEdge) throws AAIException {
markParentBoundary();
Multimap<String, EdgeRule> rules = ArrayListMultimap.create();
EdgeRuleQuery.Builder qB = new EdgeRuleQuery.Builder(outType, inType).edgeType(type).setPrivate(isPrivateEdge);
@@ -402,26 +405,28 @@ public abstract class GremlinQueryBuilder<E> extends QueryBuilder<E> {
} else {
if (Direction.IN.equals(rule.getDirection())) {
inLabels.add(rule.getLabel());
- if(inType.equals(outType)) {//code to handle when a type edges to itself, to add both in and out
+ if (inType.equals(outType)) {// code to handle when a type edges to itself, to add both in and out
outLabels.add(rule.getLabel());
}
} else {
outLabels.add(rule.getLabel());
- if(inType.equals(outType)) {//code to handle when a type edges to itself, to add both in and out
+ if (inType.equals(outType)) {// code to handle when a type edges to itself, to add both in and out
inLabels.add(rule.getLabel());
}
}
}
}
- if(inLabels.isEmpty() && outLabels.isEmpty()) {
- throw new NoEdgeRuleFoundException("no " + type.toString() + " edge rule between " + outType + " and " + inType );
+ if (inLabels.isEmpty() && outLabels.isEmpty()) {
+ throw new NoEdgeRuleFoundException(
+ "no " + type.toString() + " edge rule between " + outType + " and " + inType);
} else if (inLabels.isEmpty() && !outLabels.isEmpty()) {
list.add(".out('" + String.join("','", outLabels) + "')");
} else if (outLabels.isEmpty() && !inLabels.isEmpty()) {
list.add(".in('" + String.join("','", inLabels) + "')");
} else {
- list.add(".union(__.in('" + String.join("','", inLabels) + "')" + ", __.out('" + String.join("','", outLabels) + "'))");
+ list.add(".union(__.in('" + String.join("','", inLabels) + "')" + ", __.out('"
+ + String.join("','", outLabels) + "'))");
}
stepIndex++;
list.add(HAS + AAIProperties.NODE_TYPE + "', '" + inType + "')");
@@ -468,24 +473,28 @@ public abstract class GremlinQueryBuilder<E> extends QueryBuilder<E> {
}
}
- if(inLabels.isEmpty() && outLabels.isEmpty()) {
- throw new NoEdgeRuleFoundException("no " + type.toString() + " edge rule between " + outType + " and " + inType );
+ if (inLabels.isEmpty() && outLabels.isEmpty()) {
+ throw new NoEdgeRuleFoundException(
+ "no " + type.toString() + " edge rule between " + outType + " and " + inType);
} else if (inLabels.isEmpty() && !outLabels.isEmpty()) {
list.add(".outE('" + String.join("','", outLabels) + "')");
} else if (outLabels.isEmpty() && !inLabels.isEmpty()) {
list.add(".inE('" + String.join("','", inLabels) + "')");
} else {
- list.add(".union(__.inE('" + String.join("','", inLabels) + "')" + ", __.outE('" + String.join("','", outLabels) + "'))");
+ list.add(".union(__.inE('" + String.join("','", inLabels) + "')" + ", __.outE('"
+ + String.join("','", outLabels) + "'))");
}
stepIndex++;
}
+
@Override
public QueryBuilder<E> limit(long amount) {
list.add(".limit(" + amount + ")");
return this;
}
+
/**
* @{inheritDoc}
*/
@@ -540,7 +549,6 @@ public abstract class GremlinQueryBuilder<E> extends QueryBuilder<E> {
}
list.addAll(traversals);
-
return this;
}
@@ -563,7 +571,7 @@ public abstract class GremlinQueryBuilder<E> extends QueryBuilder<E> {
@Override
public QueryBuilder<E> store(String name) {
- this.list.add(".store('"+ name + "')");
+ this.list.add(".store('" + name + "')");
stepIndex++;
return this;
@@ -571,7 +579,7 @@ public abstract class GremlinQueryBuilder<E> extends QueryBuilder<E> {
@Override
public QueryBuilder<E> cap(String name) {
- this.list.add(".cap('"+ name + "')");
+ this.list.add(".cap('" + name + "')");
stepIndex++;
return this;
@@ -603,7 +611,7 @@ public abstract class GremlinQueryBuilder<E> extends QueryBuilder<E> {
@Override
public QueryBuilder<E> repeat(QueryBuilder<E> builder) {
- this.list.add(".repeat(__" + builder.getQuery() + ")");
+ this.list.add(".repeat(__" + builder.getQuery() + ")");
stepIndex++;
return this;
@@ -638,12 +646,12 @@ public abstract class GremlinQueryBuilder<E> extends QueryBuilder<E> {
this.list.add(".tree()");
stepIndex++;
- return (QueryBuilder<Tree>)this;
+ return (QueryBuilder<Tree>) this;
}
@Override
public QueryBuilder<E> by(String name) {
- this.list.add(".by('"+ name + "')");
+ this.list.add(".by('" + name + "')");
stepIndex++;
return this;
@@ -653,7 +661,7 @@ public abstract class GremlinQueryBuilder<E> extends QueryBuilder<E> {
* {@inheritDoc}
*/
@Override
- public QueryBuilder<E> simplePath(){
+ public QueryBuilder<E> simplePath() {
this.list.add(".simplePath()");
stepIndex++;
return this;
@@ -663,10 +671,10 @@ public abstract class GremlinQueryBuilder<E> extends QueryBuilder<E> {
* {@inheritDoc}
*/
@Override
- public QueryBuilder<Path> path(){
+ public QueryBuilder<Path> path() {
this.list.add(".path()");
stepIndex++;
- return (QueryBuilder<Path>)this;
+ return (QueryBuilder<Path>) this;
}
@Override
@@ -674,7 +682,7 @@ public abstract class GremlinQueryBuilder<E> extends QueryBuilder<E> {
this.list.add(".outE()");
stepIndex++;
- return (QueryBuilder<Edge>)this;
+ return (QueryBuilder<Edge>) this;
}
@Override
@@ -682,7 +690,7 @@ public abstract class GremlinQueryBuilder<E> extends QueryBuilder<E> {
this.list.add(".inE()");
stepIndex++;
- return (QueryBuilder<Edge>)this;
+ return (QueryBuilder<Edge>) this;
}
@Override
@@ -690,7 +698,7 @@ public abstract class GremlinQueryBuilder<E> extends QueryBuilder<E> {
this.list.add(".outV()");
stepIndex++;
- return (QueryBuilder<Vertex>)this;
+ return (QueryBuilder<Vertex>) this;
}
@Override
@@ -698,7 +706,7 @@ public abstract class GremlinQueryBuilder<E> extends QueryBuilder<E> {
this.list.add(".inV()");
stepIndex++;
- return (QueryBuilder<Vertex>)this;
+ return (QueryBuilder<Vertex>) this;
}
@Override
@@ -727,19 +735,20 @@ public abstract class GremlinQueryBuilder<E> extends QueryBuilder<E> {
@Override
public QueryBuilder<E> select(String... names) {
- String stepString = ".select('";
- for(int i = 0; i<names.length; i++) {
- stepString = stepString + names[i] +"'";
- if(i!=(names.length-1)) {
- stepString = stepString + ",'";
- }
- }
- stepString = stepString + ")";
- this.list.add(stepString);
+ String stepString = ".select('";
+ for (int i = 0; i < names.length; i++) {
+ stepString = stepString + names[i] + "'";
+ if (i != (names.length - 1)) {
+ stepString = stepString + ",'";
+ }
+ }
+ stepString = stepString + ")";
+ this.list.add(stepString);
stepIndex++;
return this;
}
+
/**
* @{inheritDoc}
*/
@@ -764,7 +773,7 @@ public abstract class GremlinQueryBuilder<E> extends QueryBuilder<E> {
sb.append(piece);
}
- return (T2)sb.toString();
+ return (T2) sb.toString();
}
/**
@@ -810,6 +819,7 @@ public abstract class GremlinQueryBuilder<E> extends QueryBuilder<E> {
}
this.completeTraversal = this.gremlinGroovy.executeTraversal(queryString, params);
}
+
@Override
public boolean hasNext() {
if (this.completeTraversal == null) {
@@ -825,7 +835,7 @@ public abstract class GremlinQueryBuilder<E> extends QueryBuilder<E> {
executeQuery();
}
- return (E)this.completeTraversal.next();
+ return (E) this.completeTraversal.next();
}
@Override
@@ -834,13 +844,13 @@ public abstract class GremlinQueryBuilder<E> extends QueryBuilder<E> {
executeQuery();
}
- return (List<E>)this.completeTraversal.toList();
+ return (List<E>) this.completeTraversal.toList();
}
protected QueryBuilder<Edge> has(String key, String value) {
this.list.add(HAS + key + "','" + value + "')");
- return (QueryBuilder<Edge>)this;
+ return (QueryBuilder<Edge>) this;
}
}
diff --git a/aai-core/src/main/java/org/onap/aai/query/builder/GremlinTraversal.java b/aai-core/src/main/java/org/onap/aai/query/builder/GremlinTraversal.java
index 22103bda..710db480 100644
--- a/aai-core/src/main/java/org/onap/aai/query/builder/GremlinTraversal.java
+++ b/aai-core/src/main/java/org/onap/aai/query/builder/GremlinTraversal.java
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.query.builder;
import java.io.UnsupportedEncodingException;
@@ -39,103 +40,102 @@ import org.onap.aai.parsers.query.TraversalStrategy;
*/
public class GremlinTraversal<E> extends GremlinQueryBuilder<E> {
-
- /**
- * Instantiates a new gremlin traversal.
- *
- * @param loader the loader
- */
- public GremlinTraversal(Loader loader, GraphTraversalSource source) {
- super(loader, source);
- this.factory = new TraversalStrategy(this.loader, this);
- }
-
- /**
- * Instantiates a new gremlin traversal.
- *
- * @param loader the loader
- * @param start the start
- */
- public GremlinTraversal(Loader loader, GraphTraversalSource source, Vertex start) {
- super(loader, source, start);
- this.factory = new TraversalStrategy(this.loader, this);
- }
-
-
- protected GremlinTraversal(List<String> traversal, Loader loader, GraphTraversalSource source, GremlinQueryBuilder<E> gtb) {
- super(loader, source);
- this.list = traversal;
- this.stepIndex = gtb.getStepIndex();
- this.parentStepIndex = gtb.getParentStepIndex();
- this.containerStepIndex = gtb.getContainerStepIndex();
- this.factory = new TraversalStrategy(this.loader, this);
- this.start = gtb.getStart();
- }
-
- /**
- * @{inheritDoc}
- */
- @Override
- public QueryParser createQueryFromURI(URI uri) throws UnsupportedEncodingException, AAIException {
- return factory.buildURIParser(uri);
- }
-
- /**
- * @{inheritDoc}
- */
- @Override
- public QueryParser createQueryFromRelationship(Introspector relationship) throws UnsupportedEncodingException, AAIException {
- return factory.buildRelationshipParser(relationship);
- }
-
-
- /**
- * @{inheritDoc}
- */
- @Override
- public QueryParser createQueryFromURI(URI uri, MultivaluedMap<String, String> queryParams)
- throws UnsupportedEncodingException, AAIException {
- return factory.buildURIParser(uri, queryParams);
- }
-
- /**
- * @{inheritDoc}
- */
- @Override
- public QueryParser createQueryFromObjectName(String objName) {
- return factory.buildObjectNameParser(objName);
- }
-
- /**
- * @{inheritDoc}
- */
- @Override
- public QueryBuilder<E> newInstance(Vertex start) {
- return new GremlinTraversal<>(loader, source, start);
- }
-
- /**
- * @{inheritDoc}
- */
- @Override
- public QueryBuilder<E> newInstance() {
- return new GremlinTraversal<>(loader, source);
- }
-
- @Override
- protected QueryBuilder<E> cloneQueryAtStep(int index) {
-
- int idx = index;
-
- if (idx == 0) {
- idx = stepIndex;
- }
-
- List<String> newList = new ArrayList<>();
- for (int i = 0; i < idx; i++) {
- newList.add(this.list.get(i));
- }
-
- return new GremlinTraversal<>(newList, loader, source, this);
- }
+ /**
+ * Instantiates a new gremlin traversal.
+ *
+ * @param loader the loader
+ */
+ public GremlinTraversal(Loader loader, GraphTraversalSource source) {
+ super(loader, source);
+ this.factory = new TraversalStrategy(this.loader, this);
+ }
+
+ /**
+ * Instantiates a new gremlin traversal.
+ *
+ * @param loader the loader
+ * @param start the start
+ */
+ public GremlinTraversal(Loader loader, GraphTraversalSource source, Vertex start) {
+ super(loader, source, start);
+ this.factory = new TraversalStrategy(this.loader, this);
+ }
+
+ protected GremlinTraversal(List<String> traversal, Loader loader, GraphTraversalSource source,
+ GremlinQueryBuilder<E> gtb) {
+ super(loader, source);
+ this.list = traversal;
+ this.stepIndex = gtb.getStepIndex();
+ this.parentStepIndex = gtb.getParentStepIndex();
+ this.containerStepIndex = gtb.getContainerStepIndex();
+ this.factory = new TraversalStrategy(this.loader, this);
+ this.start = gtb.getStart();
+ }
+
+ /**
+ * @{inheritDoc}
+ */
+ @Override
+ public QueryParser createQueryFromURI(URI uri) throws UnsupportedEncodingException, AAIException {
+ return factory.buildURIParser(uri);
+ }
+
+ /**
+ * @{inheritDoc}
+ */
+ @Override
+ public QueryParser createQueryFromRelationship(Introspector relationship)
+ throws UnsupportedEncodingException, AAIException {
+ return factory.buildRelationshipParser(relationship);
+ }
+
+ /**
+ * @{inheritDoc}
+ */
+ @Override
+ public QueryParser createQueryFromURI(URI uri, MultivaluedMap<String, String> queryParams)
+ throws UnsupportedEncodingException, AAIException {
+ return factory.buildURIParser(uri, queryParams);
+ }
+
+ /**
+ * @{inheritDoc}
+ */
+ @Override
+ public QueryParser createQueryFromObjectName(String objName) {
+ return factory.buildObjectNameParser(objName);
+ }
+
+ /**
+ * @{inheritDoc}
+ */
+ @Override
+ public QueryBuilder<E> newInstance(Vertex start) {
+ return new GremlinTraversal<>(loader, source, start);
+ }
+
+ /**
+ * @{inheritDoc}
+ */
+ @Override
+ public QueryBuilder<E> newInstance() {
+ return new GremlinTraversal<>(loader, source);
+ }
+
+ @Override
+ protected QueryBuilder<E> cloneQueryAtStep(int index) {
+
+ int idx = index;
+
+ if (idx == 0) {
+ idx = stepIndex;
+ }
+
+ List<String> newList = new ArrayList<>();
+ for (int i = 0; i < idx; i++) {
+ newList.add(this.list.get(i));
+ }
+
+ return new GremlinTraversal<>(newList, loader, source, this);
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/query/builder/GremlinUnique.java b/aai-core/src/main/java/org/onap/aai/query/builder/GremlinUnique.java
index da01d2d6..2b117c49 100644
--- a/aai-core/src/main/java/org/onap/aai/query/builder/GremlinUnique.java
+++ b/aai-core/src/main/java/org/onap/aai/query/builder/GremlinUnique.java
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.query.builder;
import java.io.UnsupportedEncodingException;
@@ -28,7 +29,6 @@ import javax.ws.rs.core.MultivaluedMap;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.structure.Vertex;
-
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.introspection.Introspector;
import org.onap.aai.introspection.Loader;
@@ -40,101 +40,103 @@ import org.onap.aai.parsers.query.UniqueStrategy;
* The Class GremlinUnique.
*/
public class GremlinUnique<E> extends GremlinQueryBuilder<E> {
-
- /**
- * Instantiates a new gremlin unique.
- *
- * @param loader the loader
- */
- public GremlinUnique(Loader loader, GraphTraversalSource source) {
- super(loader, source);
- this.factory = new UniqueStrategy(this.loader, this);
- }
-
- /**
- * Instantiates a new gremlin unique.
- *
- * @param loader the loader
- * @param start the start
- */
- public GremlinUnique(Loader loader, GraphTraversalSource source, Vertex start) {
- super(loader, source, start);
- this.factory = new UniqueStrategy(this.loader, this);
- }
-
- protected GremlinUnique(List<String> traversal, Loader loader, GraphTraversalSource source, GremlinQueryBuilder<E> gtb) {
- super(loader, source);
- this.list = traversal;
- this.stepIndex = gtb.getStepIndex();
- this.parentStepIndex = gtb.getParentStepIndex();
- this.containerStepIndex = gtb.getContainerStepIndex();
- this.factory = new TraversalStrategy(this.loader, this);
- this.start = gtb.getStart();
- }
-
- /**
- * @{inheritDoc}
- */
- @Override
- public QueryParser createQueryFromURI(URI uri) throws UnsupportedEncodingException, AAIException {
- return factory.buildURIParser(uri);
- }
-
- /**
- * @{inheritDoc}
- */
- @Override
- public QueryParser createQueryFromRelationship(Introspector relationship) throws UnsupportedEncodingException, AAIException {
- return factory.buildRelationshipParser(relationship);
- }
-
- /**
- * @{inheritDoc}
- */
- @Override
- public QueryParser createQueryFromURI(URI uri, MultivaluedMap<String, String> queryParams)
- throws UnsupportedEncodingException, AAIException {
- return factory.buildURIParser(uri, queryParams);
- }
-
- /**
- * @{inheritDoc}
- */
- @Override
- public QueryParser createQueryFromObjectName(String objName) {
- return factory.buildObjectNameParser(objName);
- }
-
- /**
- * @{inheritDoc}
- */
- @Override
- public QueryBuilder<E> newInstance() {
- return new GremlinUnique<>(loader, source);
- }
-
- /**
- * @{inheritDoc}
- */
- @Override
- public QueryBuilder<E> newInstance(Vertex start) {
- return new GremlinUnique<>(loader, source, start);
- }
-
- @Override
- protected QueryBuilder<E> cloneQueryAtStep(int index) {
-
- int idx = index;
-
- if (idx == 0) {
- idx = stepIndex;
- }
-
- List<String> newList = new ArrayList<>();
- for (int i = 0; i < idx; i++) {
- newList.add(this.list.get(i));
- }
-
- return new GremlinUnique<>(newList, loader, source, this);
- }
+
+ /**
+ * Instantiates a new gremlin unique.
+ *
+ * @param loader the loader
+ */
+ public GremlinUnique(Loader loader, GraphTraversalSource source) {
+ super(loader, source);
+ this.factory = new UniqueStrategy(this.loader, this);
+ }
+
+ /**
+ * Instantiates a new gremlin unique.
+ *
+ * @param loader the loader
+ * @param start the start
+ */
+ public GremlinUnique(Loader loader, GraphTraversalSource source, Vertex start) {
+ super(loader, source, start);
+ this.factory = new UniqueStrategy(this.loader, this);
+ }
+
+ protected GremlinUnique(List<String> traversal, Loader loader, GraphTraversalSource source,
+ GremlinQueryBuilder<E> gtb) {
+ super(loader, source);
+ this.list = traversal;
+ this.stepIndex = gtb.getStepIndex();
+ this.parentStepIndex = gtb.getParentStepIndex();
+ this.containerStepIndex = gtb.getContainerStepIndex();
+ this.factory = new TraversalStrategy(this.loader, this);
+ this.start = gtb.getStart();
+ }
+
+ /**
+ * @{inheritDoc}
+ */
+ @Override
+ public QueryParser createQueryFromURI(URI uri) throws UnsupportedEncodingException, AAIException {
+ return factory.buildURIParser(uri);
+ }
+
+ /**
+ * @{inheritDoc}
+ */
+ @Override
+ public QueryParser createQueryFromRelationship(Introspector relationship)
+ throws UnsupportedEncodingException, AAIException {
+ return factory.buildRelationshipParser(relationship);
+ }
+
+ /**
+ * @{inheritDoc}
+ */
+ @Override
+ public QueryParser createQueryFromURI(URI uri, MultivaluedMap<String, String> queryParams)
+ throws UnsupportedEncodingException, AAIException {
+ return factory.buildURIParser(uri, queryParams);
+ }
+
+ /**
+ * @{inheritDoc}
+ */
+ @Override
+ public QueryParser createQueryFromObjectName(String objName) {
+ return factory.buildObjectNameParser(objName);
+ }
+
+ /**
+ * @{inheritDoc}
+ */
+ @Override
+ public QueryBuilder<E> newInstance() {
+ return new GremlinUnique<>(loader, source);
+ }
+
+ /**
+ * @{inheritDoc}
+ */
+ @Override
+ public QueryBuilder<E> newInstance(Vertex start) {
+ return new GremlinUnique<>(loader, source, start);
+ }
+
+ @Override
+ protected QueryBuilder<E> cloneQueryAtStep(int index) {
+
+ int idx = index;
+
+ if (idx == 0) {
+ idx = stepIndex;
+ }
+
+ List<String> newList = new ArrayList<>();
+ for (int i = 0; i < idx; i++) {
+ newList.add(this.list.get(i));
+ }
+
+ return new GremlinUnique<>(newList, loader, source, this);
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/query/builder/MissingOptionalParameter.java b/aai-core/src/main/java/org/onap/aai/query/builder/MissingOptionalParameter.java
index 8ce71e96..3b03656c 100644
--- a/aai-core/src/main/java/org/onap/aai/query/builder/MissingOptionalParameter.java
+++ b/aai-core/src/main/java/org/onap/aai/query/builder/MissingOptionalParameter.java
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.query.builder;
/*-
@@ -41,13 +42,14 @@ package org.onap.aai.query.builder;
public class MissingOptionalParameter {
- private MissingOptionalParameter() {}
+ private MissingOptionalParameter() {
+ }
- private static class Helper {
- static final MissingOptionalParameter INSTANCE = new MissingOptionalParameter();
- }
+ private static class Helper {
+ static final MissingOptionalParameter INSTANCE = new MissingOptionalParameter();
+ }
- public static MissingOptionalParameter getInstance() {
- return Helper.INSTANCE;
- }
- }
+ public static MissingOptionalParameter getInstance() {
+ return Helper.INSTANCE;
+ }
+}
diff --git a/aai-core/src/main/java/org/onap/aai/query/builder/QueryBuilder.java b/aai-core/src/main/java/org/onap/aai/query/builder/QueryBuilder.java
index 68cfd5fc..a214811c 100644
--- a/aai-core/src/main/java/org/onap/aai/query/builder/QueryBuilder.java
+++ b/aai-core/src/main/java/org/onap/aai/query/builder/QueryBuilder.java
@@ -17,8 +17,17 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.query.builder;
+import java.io.UnsupportedEncodingException;
+import java.net.URI;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import javax.ws.rs.core.MultivaluedMap;
+
import org.apache.tinkerpop.gremlin.process.traversal.Path;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.process.traversal.step.util.Tree;
@@ -26,6 +35,10 @@ import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.onap.aai.config.SpringContextAware;
import org.onap.aai.db.props.AAIProperties;
+import org.onap.aai.edges.EdgeIngestor;
+import org.onap.aai.edges.enums.AAIDirection;
+import org.onap.aai.edges.enums.EdgeProperty;
+import org.onap.aai.edges.enums.EdgeType;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.introspection.Introspector;
import org.onap.aai.introspection.Loader;
@@ -33,102 +46,93 @@ import org.onap.aai.introspection.exceptions.AAIUnknownObjectException;
import org.onap.aai.parsers.query.QueryParser;
import org.onap.aai.parsers.query.QueryParserStrategy;
import org.springframework.context.ApplicationContext;
-import org.onap.aai.edges.EdgeIngestor;
-import org.onap.aai.edges.enums.AAIDirection;
-import org.onap.aai.edges.enums.EdgeProperty;
-import org.onap.aai.edges.enums.EdgeType;
-
-import javax.ws.rs.core.MultivaluedMap;
-import java.io.UnsupportedEncodingException;
-import java.net.URI;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
/**
* The Class QueryBuilder.
*/
public abstract class QueryBuilder<E> implements Iterator<E> {
- protected final GraphTraversalSource source;
- protected QueryParserStrategy factory = null;
- protected Loader loader = null;
- protected EdgeIngestor edgeRules;
- protected boolean optimize = false;
- protected Vertex start = null;
-
- protected int parentStepIndex = 0;
- protected int containerStepIndex = 0;
- protected int stepIndex = 0;
-
- /**
- * Instantiates a new query builder.
- *
- * @param loader the loader
- */
- public QueryBuilder(Loader loader, GraphTraversalSource source) {
- this.loader = loader;
- this.source = source;
- initEdgeIngestor();
- }
-
- /**
- * Instantiates a new query builder.
- *
- * @param loader the loader
- * @param start the start
- */
- public QueryBuilder(Loader loader, GraphTraversalSource source, Vertex start) {
- this.loader = loader;
- this.start = start;
- this.source = source;
- initEdgeIngestor();
- }
-
- public void changeLoader(Loader loader) {
- this.loader = loader;
- }
-
- protected abstract QueryBuilder<E> cloneQueryAtStep(int index);
-
- /**
- * Gets the vertices by indexed property.
- *
- * @param key the key
- * @param value the value
- * @return the vertices by indexed property
- */
- public QueryBuilder<Vertex> getVerticesByIndexedProperty(String key, Object value) {
- return this.getVerticesByProperty(key, value);
- }
-
- /**
- * Gets the vertices by property.
- *
- * @param key the key
- * @param value the value
- * @return the vertices by property
- */
- public abstract QueryBuilder<Vertex> getVerticesByProperty(String key, Object value);
-
- /**
- * filters by all the values for this property
- * @param key
- * @param values
- * @return vertices that match these values
- */
- public QueryBuilder<Vertex> getVerticesByIndexedProperty(String key, List<?> values) {
- return this.getVerticesByProperty(key, values);
- }
-
- /**
- * filters by all the values for this property
- * @param key
- * @param values
- * @return vertices that match these values
- */
- public abstract QueryBuilder<Vertex> getVerticesByProperty(String key, List<?> values);
-
+ protected final GraphTraversalSource source;
+ protected QueryParserStrategy factory = null;
+ protected Loader loader = null;
+ protected EdgeIngestor edgeRules;
+ protected boolean optimize = false;
+ protected Vertex start = null;
+
+ protected int parentStepIndex = 0;
+ protected int containerStepIndex = 0;
+ protected int stepIndex = 0;
+
+ /**
+ * Instantiates a new query builder.
+ *
+ * @param loader the loader
+ */
+ public QueryBuilder(Loader loader, GraphTraversalSource source) {
+ this.loader = loader;
+ this.source = source;
+ initEdgeIngestor();
+ }
+
+ /**
+ * Instantiates a new query builder.
+ *
+ * @param loader the loader
+ * @param start the start
+ */
+ public QueryBuilder(Loader loader, GraphTraversalSource source, Vertex start) {
+ this.loader = loader;
+ this.start = start;
+ this.source = source;
+ initEdgeIngestor();
+ }
+
+ public void changeLoader(Loader loader) {
+ this.loader = loader;
+ }
+
+ protected abstract QueryBuilder<E> cloneQueryAtStep(int index);
+
+ /**
+ * Gets the vertices by indexed property.
+ *
+ * @param key the key
+ * @param value the value
+ * @return the vertices by indexed property
+ */
+ public QueryBuilder<Vertex> getVerticesByIndexedProperty(String key, Object value) {
+ return this.getVerticesByProperty(key, value);
+ }
+
+ /**
+ * Gets the vertices by property.
+ *
+ * @param key the key
+ * @param value the value
+ * @return the vertices by property
+ */
+ public abstract QueryBuilder<Vertex> getVerticesByProperty(String key, Object value);
+
+ /**
+ * filters by all the values for this property
+ *
+ * @param key
+ * @param values
+ * @return vertices that match these values
+ */
+ public QueryBuilder<Vertex> getVerticesByIndexedProperty(String key, List<?> values) {
+ return this.getVerticesByProperty(key, values);
+ }
+
+ /**
+ * filters by all the values for this property
+ *
+ * @param key
+ * @param values
+ * @return vertices that match these values
+ */
+ public abstract QueryBuilder<Vertex> getVerticesByProperty(String key, List<?> values);
+
/**
* Gets the vertices that have this property key.
*
@@ -137,7 +141,7 @@ public abstract class QueryBuilder<E> implements Iterator<E> {
* @return the vertices by property
*/
public abstract QueryBuilder<Vertex> getVerticesByProperty(String key);
-
+
/**
* Gets the vertices that do not have this property key.
*
@@ -147,482 +151,525 @@ public abstract class QueryBuilder<E> implements Iterator<E> {
*/
public abstract QueryBuilder<Vertex> getVerticesExcludeByProperty(String key);
- /**
- * filters by elements that start with the value for this property
- * @param key
- * @param value
- * @return vertices that match these values
- */
- public abstract QueryBuilder<Vertex> getVerticesStartsWithProperty(String key, Object value);
-
- /**
- * Gets the vertices that are excluded by property.
- *
- * @param key the key
- * @param value the value
- * @return the vertices by property
- */
- public abstract QueryBuilder<Vertex> getVerticesExcludeByProperty(String key, Object value);
-
- /**
- * filters by all the values for this property and excludes the vertices
- * @param key
- * @param values
- * @return vertices that match these values
- */
- public QueryBuilder<Vertex> getVerticesExcludeByIndexedProperty(String key, List<?> values) {
- return this.getVerticesExcludeByProperty(key, values);
- }
-
- /**
- * filters by all the values for this property and excludes the vertices
- * @param key
- * @param values
- * @return vertices that match these values
- */
- public abstract QueryBuilder<Vertex> getVerticesExcludeByProperty(String key, List<?> values);
-
- /**
- * filters by all the values greater than for this property
+ /**
+ * filters by elements that start with the value for this property
+ *
+ * @param key
+ * @param value
+ * @return vertices that match these values
+ */
+ public abstract QueryBuilder<Vertex> getVerticesStartsWithProperty(String key, Object value);
+
+ /**
+ * Gets the vertices that are excluded by property.
+ *
+ * @param key the key
+ * @param value the value
+ * @return the vertices by property
+ */
+ public abstract QueryBuilder<Vertex> getVerticesExcludeByProperty(String key, Object value);
+
+ /**
+ * filters by all the values for this property and excludes the vertices
+ *
+ * @param key
+ * @param values
+ * @return vertices that match these values
+ */
+ public QueryBuilder<Vertex> getVerticesExcludeByIndexedProperty(String key, List<?> values) {
+ return this.getVerticesExcludeByProperty(key, values);
+ }
+
+ /**
+ * filters by all the values for this property and excludes the vertices
+ *
* @param key
* @param values
* @return vertices that match these values
*/
- public abstract QueryBuilder<Vertex> getVerticesGreaterThanProperty(String key, Object value) ;
+ public abstract QueryBuilder<Vertex> getVerticesExcludeByProperty(String key, List<?> values);
/**
- * filters by all the values less than for this property
+ * filters by all the values greater than for this property
+ *
* @param key
* @param values
* @return vertices that match these values
*/
-
- public abstract QueryBuilder<Vertex> getVerticesLessThanProperty(String key, Object value) ;
-
- /**
- * Gets the child vertices from parent.
- *
- * @param parentKey the parent key
- * @param parentValue the parent value
- * @param childType the child type
- * @return the child vertices from parent
- */
- public abstract QueryBuilder<Vertex> getChildVerticesFromParent(String parentKey, String parentValue, String childType);
-
- /**
- * Gets the typed vertices by map.
- *
- * @param type the type
- * @param map the map
- * @return the typed vertices by map
- */
- public abstract QueryBuilder<Vertex> getTypedVerticesByMap(String type, Map<String, String> map);
-
- /**
- * Creates the DB query.
- *
- * @param obj the obj
- * @return the query builder
- */
- public QueryBuilder<Vertex> createDBQuery(Introspector obj) {
- this.createKeyQuery(obj);
- this.createContainerQuery(obj);
- return (QueryBuilder<Vertex>) this;
- }
-
- /**
- * Creates the key query.
- *
- * @param obj the obj
- * @return the query builder
- */
- public abstract QueryBuilder<Vertex> createKeyQuery(Introspector obj);
-
- /**
- * Creates the container query.
- *
- * @param obj the obj
- * @return the query builder
- */
- public abstract QueryBuilder<Vertex> createContainerQuery(Introspector obj);
-
- /**
- * Creates the edge traversal.
- *
- * @param parent the parent
- * @param child the child
- * @return the query builder
- */
- public abstract QueryBuilder<Vertex> createEdgeTraversal(EdgeType type, Introspector parent, Introspector child) throws AAIException;
-
- public abstract QueryBuilder<Vertex> getVerticesByBooleanProperty(String key, Object value);
-
- public QueryBuilder<Vertex> getVerticesByBooleanProperty(String key, MissingOptionalParameter value) {
- return (QueryBuilder<Vertex>) this;
- }
- /**
- * Creates the private edge traversal.
- *
- * @param parent the parent
- * @param child the child
- * @return the query builder
- */
- public abstract QueryBuilder<Vertex> createPrivateEdgeTraversal(EdgeType type, Introspector parent, Introspector child) throws AAIException;
-
- /**
- * Creates the edge traversal.
- *
- * @param parent the parent
- * @param child the child
- * @return the query builder
- */
- public QueryBuilder<Vertex> createEdgeTraversal(EdgeType type, Vertex parent, Introspector child) throws AAIException {
- String nodeType = parent.<String>property(AAIProperties.NODE_TYPE).orElse(null);
- this.createEdgeTraversal(type, nodeType, child.getDbName());
- return (QueryBuilder<Vertex>) this;
- }
-
- /**
- *
- * @param type
- * @param outNodeType
- * @param inNodeType
- * @return
- * @throws AAIException
- */
- public QueryBuilder<Vertex> createEdgeTraversal(EdgeType type, String outNodeType, String inNodeType) throws AAIException {
- Introspector out = loader.introspectorFromName(outNodeType);
- Introspector in = loader.introspectorFromName(inNodeType);
-
- return createEdgeTraversal(type, out, in);
- }
-
- /**
- *
- * @param edgeType
- * @param outNodeType
- * @param inNodeType
- * @return
- * @throws AAIException
- */
- public QueryBuilder<Vertex> createEdgeTraversal(String edgeType, String outNodeType, String inNodeType) throws AAIException {
- /*
- * When the optional parameter edgetype is sent it is a string that needs to be converted to Enum
- */
- EdgeType type = EdgeType.valueOf(edgeType);
- Introspector out = loader.introspectorFromName(outNodeType);
- Introspector in = loader.introspectorFromName(inNodeType);
-
- return createEdgeTraversal(type, out, in);
- }
-
- /**
- *
- * @param MissingOptionalParameter
- * @param outNodeType
- * @param inNodeType
- * @return
- * @throws AAIException
- */
- public QueryBuilder<Vertex> createEdgeTraversal(MissingOptionalParameter edgeType, String outNodeType, String inNodeType) throws AAIException {
- /*
- * When no optional parameter edgetype is sent get all edges between the 2 nodetypes
- */
- return this.createEdgeTraversal(outNodeType, inNodeType);
- }
-
- public QueryBuilder<Vertex> createEdgeTraversal(String outNodeType, String inNodeType) throws AAIException {
-
- Introspector out = loader.introspectorFromName(outNodeType);
- Introspector in = loader.introspectorFromName(inNodeType);
-
- QueryBuilder<Vertex> cousinBuilder = null;
- QueryBuilder<Vertex> treeBuilder = null;
- QueryBuilder<Vertex> queryBuilder = null;
-
- try {
- cousinBuilder = this.newInstance().createEdgeTraversal(EdgeType.COUSIN, out, in);
- } catch (AAIException e) {
- }
-
- if(cousinBuilder != null){
- try {
- treeBuilder = this.newInstance().createEdgeTraversal(EdgeType.TREE, out, in);
- } catch (AAIException e) {
- }
- if(treeBuilder != null){
- queryBuilder = this.union(new QueryBuilder[]{cousinBuilder, treeBuilder});
- } else {
- queryBuilder = this.union(new QueryBuilder[]{cousinBuilder});
- }
- } else {
- treeBuilder = this.newInstance().createEdgeTraversal(EdgeType.TREE, out, in);
- queryBuilder = this.union(new QueryBuilder[]{treeBuilder});
- }
-
-
- return queryBuilder;
- }
-
- public QueryBuilder<Vertex> createPrivateEdgeTraversal(EdgeType type, String outNodeType, String inNodeType) throws AAIException {
- Introspector out = loader.introspectorFromName(outNodeType);
- Introspector in = loader.introspectorFromName(inNodeType);
- return createPrivateEdgeTraversal(type, out, in);
- }
-
- /**
- *
- * @param type
- * @param outNodeType
- * @param inNodeType
- * @param labels
- * @return
- * @throws AAIException
- */
- public QueryBuilder<Vertex> createEdgeTraversalWithLabels(EdgeType type, String outNodeType, String inNodeType, List<String> labels) throws AAIException {
- Introspector out = loader.introspectorFromName(outNodeType);
- Introspector in = loader.introspectorFromName(inNodeType);
-
- return createEdgeTraversalWithLabels(type, out, in, labels);
- }
-
- /**
- *
- * @param type
- * @param out
- * @param in
- * @param labels
- * @return
- */
- public abstract QueryBuilder<Vertex> createEdgeTraversalWithLabels(EdgeType type, Introspector out, Introspector in, List<String> labels) throws AAIException;
-
- /**
- *
- * @param type
- * @param outNodeType
- * @param inNodeType
- * @return
- * @throws AAIException
- */
- public QueryBuilder<Edge> getEdgesBetween(EdgeType type, String outNodeType, String inNodeType) throws AAIException {
- this.getEdgesBetweenWithLabels(type, outNodeType, inNodeType, null);
-
- return (QueryBuilder<Edge>)this;
-
- }
- /**
- *
- * @param type
- * @param outNodeType
- * @param inNodeType
- * @param labels
- * @return
- * @throws AAIException
- */
- public abstract QueryBuilder<Edge> getEdgesBetweenWithLabels(EdgeType type, String outNodeType, String inNodeType, List<String> labels) throws AAIException;
-
- /**
- * Creates the query from URI.
- *
- * @param uri the uri
- * @return the query parser
- * @throws UnsupportedEncodingException the unsupported encoding exception
- * @throws AAIException the AAI exception
- */
- public abstract QueryParser createQueryFromURI(URI uri) throws UnsupportedEncodingException, AAIException;
-
- /**
- * Creates the query from URI.
- *
- * @param uri the uri
- * @param queryParams the query params
- * @return the query parser
- * @throws UnsupportedEncodingException the unsupported encoding exception
- * @throws AAIException the AAI exception
- */
- public abstract QueryParser createQueryFromURI(URI uri, MultivaluedMap<String, String> queryParams) throws UnsupportedEncodingException, AAIException;
-
- /**
- * Creates a queryparser from a given object name.
- *
- * @param objName - name of the object type as it appears in the database
- * @return
- */
- public abstract QueryParser createQueryFromObjectName(String objName);
-
- /**
- * Creates the query from relationship.
- *
- * @param relationship the relationship
- * @return the query parser
- * @throws UnsupportedEncodingException the unsupported encoding exception
- * @throws AAIException the AAI exception
- */
- public abstract QueryParser createQueryFromRelationship(Introspector relationship) throws UnsupportedEncodingException, AAIException;
-
- /**
- * Gets the parent query.
- *
- * @return the parent query
- */
- public abstract QueryBuilder<E> getParentQuery();
-
- /**
- * Gets the query.
- *
- * @return the query
- */
- public abstract <E2> E2 getQuery();
-
- /**
- * Form boundary.
- */
- public abstract void markParentBoundary();
-
- public abstract QueryBuilder<E> limit(long amount);
-
- /**
- * New instance.
- *
- * @param start the start
- * @return the query builder
- */
- public abstract QueryBuilder<E> newInstance(Vertex start);
-
- /**
- * New instance.
- *
- * @return the query builder
- */
- public abstract QueryBuilder<E> newInstance();
-
- /**
- * Gets the start.
- *
- * @return the start
- */
- public abstract Vertex getStart();
-
- protected Object correctObjectType(Object obj) {
-
- if (obj != null && obj.getClass().equals(Long.class)) {
- return new Integer(obj.toString());
- }
-
- return obj;
- }
- /**
- * uses all fields in the introspector to create a query
- *
- * @param obj
- * @return
- */
- public abstract QueryBuilder<Vertex> exactMatchQuery(Introspector obj);
-
- /**
- * lets you join any number of QueryBuilders
- * <b>be careful about starting with a union it will not use indexes</b>
- * @param builder
- * @return
- */
- public abstract QueryBuilder<E> union(QueryBuilder<E>... builder);
-
- public abstract QueryBuilder<E> where(QueryBuilder<E>... builder);
-
- public abstract QueryBuilder<E> or(QueryBuilder<E>... builder);
-
- public abstract QueryBuilder<E> store(String name);
- public abstract QueryBuilder<E> cap(String name);
- public abstract QueryBuilder<E> unfold();
- public abstract QueryBuilder<E> dedup();
- public abstract QueryBuilder<E> emit();
- public abstract QueryBuilder<E> repeat(QueryBuilder<E> builder);
- public abstract QueryBuilder<Edge> outE();
- public abstract QueryBuilder<Edge> inE();
- public abstract QueryBuilder<Vertex> inV();
- public abstract QueryBuilder<Vertex> outV();
- public abstract QueryBuilder<E> not(QueryBuilder<E> builder);
- public abstract QueryBuilder<E> as(String name);
- public abstract QueryBuilder<E> select(String name);
- public abstract QueryBuilder<E> select(String... names);
- public abstract QueryBuilder<E> until(QueryBuilder<E> builder);
- public abstract QueryBuilder<E> groupCount();
- public abstract QueryBuilder<E> by(String name);
- public abstract QueryBuilder<E> both();
- public abstract QueryBuilder<Tree> tree();
-
- /**
- * Used to prevent the traversal from repeating its path through the graph.
- * See http://tinkerpop.apache.org/docs/3.0.1-incubating/#simplepath-step for more info.
- *
- * @return a QueryBuilder with the simplePath step appended to its traversal
- */
- public abstract QueryBuilder<E> simplePath();
-
- /**
- *
- * @return QueryBuilder with the path step appended to its traversal
- */
- public abstract QueryBuilder<Path> path();
-
- public abstract void markContainer();
-
- public abstract QueryBuilder<E> getContainerQuery();
-
- public abstract List<E> toList();
-
- /**
- * Used to skip step if there is an optional property missing.
- * @param key
- * @param value
- * @return
- */
- public QueryBuilder<Vertex> getVerticesByProperty(String key, MissingOptionalParameter value) {
- return (QueryBuilder<Vertex>) this;
- }
-
- /**
- * TODO the edge direction is hardcoded here, make it more generic
- * Returns the parent edge of the vertex
- * @return
- */
- public QueryBuilder<Edge> getParentEdge() {
- this.outE().has(EdgeProperty.CONTAINS.toString(), AAIDirection.IN.toString());
- return (QueryBuilder<Edge>)this;
- }
-
- /**
- * TODO the edge direction is hardcoded here, make it more generic
- * Returns the parent vertex of the vertex
- * @return
- */
- public QueryBuilder<Vertex> getParentVertex() {
- this.getParentEdge().inV();
- return (QueryBuilder<Vertex>)this;
- }
-
- protected abstract QueryBuilder<Edge> has(String key, String value);
-
- protected void initEdgeIngestor() {
- //TODO proper spring wiring, but that requires a lot of refactoring so for now we have this
- ApplicationContext ctx = SpringContextAware.getApplicationContext();
- EdgeIngestor ei = ctx.getBean(EdgeIngestor.class);
- setEdgeIngestor(ei);
- }
-
- protected void setEdgeIngestor(EdgeIngestor ei) {
- this.edgeRules = ei;
- }
-
- public QueryBuilder<Vertex> getVerticesByNumberProperty(String key, Object value) {
- return getVerticesByProperty(key, value);
- }
+ public abstract QueryBuilder<Vertex> getVerticesGreaterThanProperty(String key, Object value);
+
+ /**
+ * filters by all the values less than for this property
+ *
+ * @param key
+ * @param values
+ * @return vertices that match these values
+ */
+
+ public abstract QueryBuilder<Vertex> getVerticesLessThanProperty(String key, Object value);
+
+ /**
+ * Gets the child vertices from parent.
+ *
+ * @param parentKey the parent key
+ * @param parentValue the parent value
+ * @param childType the child type
+ * @return the child vertices from parent
+ */
+ public abstract QueryBuilder<Vertex> getChildVerticesFromParent(String parentKey, String parentValue,
+ String childType);
+
+ /**
+ * Gets the typed vertices by map.
+ *
+ * @param type the type
+ * @param map the map
+ * @return the typed vertices by map
+ */
+ public abstract QueryBuilder<Vertex> getTypedVerticesByMap(String type, Map<String, String> map);
+
+ /**
+ * Creates the DB query.
+ *
+ * @param obj the obj
+ * @return the query builder
+ */
+ public QueryBuilder<Vertex> createDBQuery(Introspector obj) {
+ this.createKeyQuery(obj);
+ this.createContainerQuery(obj);
+ return (QueryBuilder<Vertex>) this;
+ }
+
+ /**
+ * Creates the key query.
+ *
+ * @param obj the obj
+ * @return the query builder
+ */
+ public abstract QueryBuilder<Vertex> createKeyQuery(Introspector obj);
+
+ /**
+ * Creates the container query.
+ *
+ * @param obj the obj
+ * @return the query builder
+ */
+ public abstract QueryBuilder<Vertex> createContainerQuery(Introspector obj);
+
+ /**
+ * Creates the edge traversal.
+ *
+ * @param parent the parent
+ * @param child the child
+ * @return the query builder
+ */
+ public abstract QueryBuilder<Vertex> createEdgeTraversal(EdgeType type, Introspector parent, Introspector child)
+ throws AAIException;
+
+ public abstract QueryBuilder<Vertex> getVerticesByBooleanProperty(String key, Object value);
+
+ public QueryBuilder<Vertex> getVerticesByBooleanProperty(String key, MissingOptionalParameter value) {
+ return (QueryBuilder<Vertex>) this;
+ }
+
+ /**
+ * Creates the private edge traversal.
+ *
+ * @param parent the parent
+ * @param child the child
+ * @return the query builder
+ */
+ public abstract QueryBuilder<Vertex> createPrivateEdgeTraversal(EdgeType type, Introspector parent,
+ Introspector child) throws AAIException;
+
+ /**
+ * Creates the edge traversal.
+ *
+ * @param parent the parent
+ * @param child the child
+ * @return the query builder
+ */
+ public QueryBuilder<Vertex> createEdgeTraversal(EdgeType type, Vertex parent, Introspector child)
+ throws AAIException {
+ String nodeType = parent.<String>property(AAIProperties.NODE_TYPE).orElse(null);
+ this.createEdgeTraversal(type, nodeType, child.getDbName());
+ return (QueryBuilder<Vertex>) this;
+ }
+
+ /**
+ *
+ * @param type
+ * @param outNodeType
+ * @param inNodeType
+ * @return
+ * @throws AAIException
+ */
+ public QueryBuilder<Vertex> createEdgeTraversal(EdgeType type, String outNodeType, String inNodeType)
+ throws AAIException {
+ Introspector out = loader.introspectorFromName(outNodeType);
+ Introspector in = loader.introspectorFromName(inNodeType);
+
+ return createEdgeTraversal(type, out, in);
+ }
+
+ /**
+ *
+ * @param edgeType
+ * @param outNodeType
+ * @param inNodeType
+ * @return
+ * @throws AAIException
+ */
+ public QueryBuilder<Vertex> createEdgeTraversal(String edgeType, String outNodeType, String inNodeType)
+ throws AAIException {
+ /*
+ * When the optional parameter edgetype is sent it is a string that needs to be converted to Enum
+ */
+ EdgeType type = EdgeType.valueOf(edgeType);
+ Introspector out = loader.introspectorFromName(outNodeType);
+ Introspector in = loader.introspectorFromName(inNodeType);
+
+ return createEdgeTraversal(type, out, in);
+ }
+
+ /**
+ *
+ * @param MissingOptionalParameter
+ * @param outNodeType
+ * @param inNodeType
+ * @return
+ * @throws AAIException
+ */
+ public QueryBuilder<Vertex> createEdgeTraversal(MissingOptionalParameter edgeType, String outNodeType,
+ String inNodeType) throws AAIException {
+ /*
+ * When no optional parameter edgetype is sent get all edges between the 2 nodetypes
+ */
+ return this.createEdgeTraversal(outNodeType, inNodeType);
+ }
+
+ public QueryBuilder<Vertex> createEdgeTraversal(String outNodeType, String inNodeType) throws AAIException {
+
+ Introspector out = loader.introspectorFromName(outNodeType);
+ Introspector in = loader.introspectorFromName(inNodeType);
+
+ QueryBuilder<Vertex> cousinBuilder = null;
+ QueryBuilder<Vertex> treeBuilder = null;
+ QueryBuilder<Vertex> queryBuilder = null;
+
+ try {
+ cousinBuilder = this.newInstance().createEdgeTraversal(EdgeType.COUSIN, out, in);
+ } catch (AAIException e) {
+ }
+
+ if (cousinBuilder != null) {
+ try {
+ treeBuilder = this.newInstance().createEdgeTraversal(EdgeType.TREE, out, in);
+ } catch (AAIException e) {
+ }
+ if (treeBuilder != null) {
+ queryBuilder = this.union(new QueryBuilder[] {cousinBuilder, treeBuilder});
+ } else {
+ queryBuilder = this.union(new QueryBuilder[] {cousinBuilder});
+ }
+ } else {
+ treeBuilder = this.newInstance().createEdgeTraversal(EdgeType.TREE, out, in);
+ queryBuilder = this.union(new QueryBuilder[] {treeBuilder});
+ }
+
+ return queryBuilder;
+ }
+
+ public QueryBuilder<Vertex> createPrivateEdgeTraversal(EdgeType type, String outNodeType, String inNodeType)
+ throws AAIException {
+ Introspector out = loader.introspectorFromName(outNodeType);
+ Introspector in = loader.introspectorFromName(inNodeType);
+ return createPrivateEdgeTraversal(type, out, in);
+ }
+
+ /**
+ *
+ * @param type
+ * @param outNodeType
+ * @param inNodeType
+ * @param labels
+ * @return
+ * @throws AAIException
+ */
+ public QueryBuilder<Vertex> createEdgeTraversalWithLabels(EdgeType type, String outNodeType, String inNodeType,
+ List<String> labels) throws AAIException {
+ Introspector out = loader.introspectorFromName(outNodeType);
+ Introspector in = loader.introspectorFromName(inNodeType);
+
+ return createEdgeTraversalWithLabels(type, out, in, labels);
+ }
+
+ /**
+ *
+ * @param type
+ * @param out
+ * @param in
+ * @param labels
+ * @return
+ */
+ public abstract QueryBuilder<Vertex> createEdgeTraversalWithLabels(EdgeType type, Introspector out, Introspector in,
+ List<String> labels) throws AAIException;
+
+ /**
+ *
+ * @param type
+ * @param outNodeType
+ * @param inNodeType
+ * @return
+ * @throws AAIException
+ */
+ public QueryBuilder<Edge> getEdgesBetween(EdgeType type, String outNodeType, String inNodeType)
+ throws AAIException {
+ this.getEdgesBetweenWithLabels(type, outNodeType, inNodeType, null);
+
+ return (QueryBuilder<Edge>) this;
+
+ }
+
+ /**
+ *
+ * @param type
+ * @param outNodeType
+ * @param inNodeType
+ * @param labels
+ * @return
+ * @throws AAIException
+ */
+ public abstract QueryBuilder<Edge> getEdgesBetweenWithLabels(EdgeType type, String outNodeType, String inNodeType,
+ List<String> labels) throws AAIException;
+
+ /**
+ * Creates the query from URI.
+ *
+ * @param uri the uri
+ * @return the query parser
+ * @throws UnsupportedEncodingException the unsupported encoding exception
+ * @throws AAIException the AAI exception
+ */
+ public abstract QueryParser createQueryFromURI(URI uri) throws UnsupportedEncodingException, AAIException;
+
+ /**
+ * Creates the query from URI.
+ *
+ * @param uri the uri
+ * @param queryParams the query params
+ * @return the query parser
+ * @throws UnsupportedEncodingException the unsupported encoding exception
+ * @throws AAIException the AAI exception
+ */
+ public abstract QueryParser createQueryFromURI(URI uri, MultivaluedMap<String, String> queryParams)
+ throws UnsupportedEncodingException, AAIException;
+
+ /**
+ * Creates a queryparser from a given object name.
+ *
+ * @param objName - name of the object type as it appears in the database
+ * @return
+ */
+ public abstract QueryParser createQueryFromObjectName(String objName);
+
+ /**
+ * Creates the query from relationship.
+ *
+ * @param relationship the relationship
+ * @return the query parser
+ * @throws UnsupportedEncodingException the unsupported encoding exception
+ * @throws AAIException the AAI exception
+ */
+ public abstract QueryParser createQueryFromRelationship(Introspector relationship)
+ throws UnsupportedEncodingException, AAIException;
+
+ /**
+ * Gets the parent query.
+ *
+ * @return the parent query
+ */
+ public abstract QueryBuilder<E> getParentQuery();
+
+ /**
+ * Gets the query.
+ *
+ * @return the query
+ */
+ public abstract <E2> E2 getQuery();
+
+ /**
+ * Form boundary.
+ */
+ public abstract void markParentBoundary();
+
+ public abstract QueryBuilder<E> limit(long amount);
+
+ /**
+ * New instance.
+ *
+ * @param start the start
+ * @return the query builder
+ */
+ public abstract QueryBuilder<E> newInstance(Vertex start);
+
+ /**
+ * New instance.
+ *
+ * @return the query builder
+ */
+ public abstract QueryBuilder<E> newInstance();
+
+ /**
+ * Gets the start.
+ *
+ * @return the start
+ */
+ public abstract Vertex getStart();
+
+ protected Object correctObjectType(Object obj) {
+
+ if (obj != null && obj.getClass().equals(Long.class)) {
+ return new Integer(obj.toString());
+ }
+
+ return obj;
+ }
+
+ /**
+ * uses all fields in the introspector to create a query
+ *
+ * @param obj
+ * @return
+ */
+ public abstract QueryBuilder<Vertex> exactMatchQuery(Introspector obj);
+
+ /**
+ * lets you join any number of QueryBuilders
+ * <b>be careful about starting with a union it will not use indexes</b>
+ *
+ * @param builder
+ * @return
+ */
+ public abstract QueryBuilder<E> union(QueryBuilder<E>... builder);
+
+ public abstract QueryBuilder<E> where(QueryBuilder<E>... builder);
+
+ public abstract QueryBuilder<E> or(QueryBuilder<E>... builder);
+
+ public abstract QueryBuilder<E> store(String name);
+
+ public abstract QueryBuilder<E> cap(String name);
+
+ public abstract QueryBuilder<E> unfold();
+
+ public abstract QueryBuilder<E> dedup();
+
+ public abstract QueryBuilder<E> emit();
+
+ public abstract QueryBuilder<E> repeat(QueryBuilder<E> builder);
+
+ public abstract QueryBuilder<Edge> outE();
+
+ public abstract QueryBuilder<Edge> inE();
+
+ public abstract QueryBuilder<Vertex> inV();
+
+ public abstract QueryBuilder<Vertex> outV();
+
+ public abstract QueryBuilder<E> not(QueryBuilder<E> builder);
+
+ public abstract QueryBuilder<E> as(String name);
+
+ public abstract QueryBuilder<E> select(String name);
+
+ public abstract QueryBuilder<E> select(String... names);
+
+ public abstract QueryBuilder<E> until(QueryBuilder<E> builder);
+
+ public abstract QueryBuilder<E> groupCount();
+
+ public abstract QueryBuilder<E> by(String name);
+
+ public abstract QueryBuilder<E> both();
+
+ public abstract QueryBuilder<Tree> tree();
+
+ /**
+ * Used to prevent the traversal from repeating its path through the graph.
+ * See http://tinkerpop.apache.org/docs/3.0.1-incubating/#simplepath-step for more info.
+ *
+ * @return a QueryBuilder with the simplePath step appended to its traversal
+ */
+ public abstract QueryBuilder<E> simplePath();
+
+ /**
+ *
+ * @return QueryBuilder with the path step appended to its traversal
+ */
+ public abstract QueryBuilder<Path> path();
+
+ public abstract void markContainer();
+
+ public abstract QueryBuilder<E> getContainerQuery();
+
+ public abstract List<E> toList();
+
+ /**
+ * Used to skip step if there is an optional property missing.
+ *
+ * @param key
+ * @param value
+ * @return
+ */
+ public QueryBuilder<Vertex> getVerticesByProperty(String key, MissingOptionalParameter value) {
+ return (QueryBuilder<Vertex>) this;
+ }
+
+ /**
+ * TODO the edge direction is hardcoded here, make it more generic
+ * Returns the parent edge of the vertex
+ *
+ * @return
+ */
+ public QueryBuilder<Edge> getParentEdge() {
+ this.outE().has(EdgeProperty.CONTAINS.toString(), AAIDirection.IN.toString());
+ return (QueryBuilder<Edge>) this;
+ }
+
+ /**
+ * TODO the edge direction is hardcoded here, make it more generic
+ * Returns the parent vertex of the vertex
+ *
+ * @return
+ */
+ public QueryBuilder<Vertex> getParentVertex() {
+ this.getParentEdge().inV();
+ return (QueryBuilder<Vertex>) this;
+ }
+
+ protected abstract QueryBuilder<Edge> has(String key, String value);
+
+ protected void initEdgeIngestor() {
+ // TODO proper spring wiring, but that requires a lot of refactoring so for now we have this
+ ApplicationContext ctx = SpringContextAware.getApplicationContext();
+ EdgeIngestor ei = ctx.getBean(EdgeIngestor.class);
+ setEdgeIngestor(ei);
+ }
+
+ protected void setEdgeIngestor(EdgeIngestor ei) {
+ this.edgeRules = ei;
+ }
+
+ public QueryBuilder<Vertex> getVerticesByNumberProperty(String key, Object value) {
+ return getVerticesByProperty(key, value);
+ }
public QueryBuilder<Vertex> getVerticesByNumberProperty(String key) {
- return getVerticesByProperty(key);
+ return getVerticesByProperty(key);
}
-
+
public QueryBuilder<Vertex> getVerticesByNumberProperty(String key, MissingOptionalParameter value) {
- return getVerticesByProperty(key, value);
- }
+ return getVerticesByProperty(key, value);
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/query/builder/TraversalQuery.java b/aai-core/src/main/java/org/onap/aai/query/builder/TraversalQuery.java
index 21d8eb50..cf99fd10 100644
--- a/aai-core/src/main/java/org/onap/aai/query/builder/TraversalQuery.java
+++ b/aai-core/src/main/java/org/onap/aai/query/builder/TraversalQuery.java
@@ -17,140 +17,144 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.query.builder;
+import java.io.UnsupportedEncodingException;
+import java.net.URI;
+import java.util.List;
+
+import javax.ws.rs.core.MultivaluedMap;
+
import org.apache.tinkerpop.gremlin.process.traversal.Step;
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.Vertex;
+import org.onap.aai.edges.enums.EdgeType;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.introspection.Introspector;
import org.onap.aai.introspection.Loader;
import org.onap.aai.parsers.query.QueryParser;
import org.onap.aai.parsers.query.TraversalStrategy;
-import org.onap.aai.edges.enums.EdgeType;
-
-import javax.ws.rs.core.MultivaluedMap;
-import java.io.UnsupportedEncodingException;
-import java.net.URI;
-import java.util.List;
/**
* The Class TraversalQuery.
*/
public class TraversalQuery<E> extends GraphTraversalBuilder<E> {
- /**
- * Instantiates a new traversal query.
- *
- * @param loader the loader
- */
- public TraversalQuery(Loader loader, GraphTraversalSource source) {
- super(loader, source);
- this.factory = new TraversalStrategy(this.loader, this);
- }
-
- /**
- * Instantiates a new traversal query.
- *
- * @param loader the loader
- * @param start the start
- */
- public TraversalQuery(Loader loader, GraphTraversalSource source, Vertex start) {
- super(loader, source, start);
- this.factory = new TraversalStrategy(this.loader, this);
- }
-
- protected TraversalQuery(GraphTraversal<Vertex, E> traversal, Loader loader, GraphTraversalSource source, GraphTraversalBuilder<E> gtb) {
- super(loader, source);
- this.traversal = traversal;
- this.stepIndex = gtb.getStepIndex();
- this.parentStepIndex = gtb.getParentStepIndex();
- this.containerStepIndex = gtb.getContainerStepIndex();
- this.factory = new TraversalStrategy(this.loader, this);
- this.start = gtb.getStart();
- }
-
- /**
- * @{inheritDoc}
- */
- @Override
- public QueryParser createQueryFromURI(URI uri) throws UnsupportedEncodingException, AAIException {
- return factory.buildURIParser(uri);
- }
-
- /**
- * @{inheritDoc}
- */
- @Override
- public QueryParser createQueryFromRelationship(Introspector relationship) throws UnsupportedEncodingException, AAIException {
- return factory.buildRelationshipParser(relationship);
- }
-
- /**
- * @{inheritDoc}
- */
- @Override
- public QueryParser createQueryFromURI(URI uri, MultivaluedMap<String, String> queryParams)
- throws UnsupportedEncodingException, AAIException {
- return factory.buildURIParser(uri, queryParams);
- }
-
- /**
- * @{inheritDoc}
- */
- @Override
- public QueryParser createQueryFromObjectName(String objName) {
- return factory.buildObjectNameParser(objName);
- }
-
- /**
- * @{inheritDoc}
- */
- @Override
- public QueryBuilder<E> newInstance(Vertex start) {
- return new TraversalQuery<>(loader, source, start);
- }
-
- /**
- * @{inheritDoc}
- */
- @Override
- public QueryBuilder<E> newInstance() {
- return new TraversalQuery<>(loader, source);
- }
-
- @Override
- protected QueryBuilder<E> cloneQueryAtStep(int index) {
- GraphTraversal.Admin<Vertex, E> cloneAdmin = getCloneAdmin(index);
- return new TraversalQuery<>(cloneAdmin, loader, source, this);
- }
-
- protected GraphTraversal.Admin<Vertex, E> getCloneAdmin(int index) {
- int idx = index;
-
- if (idx == 0) {
- idx = stepIndex;
- }
-
- GraphTraversal<Vertex, E> clone = this.traversal.asAdmin().clone();
- GraphTraversal.Admin<Vertex, E> cloneAdmin = clone.asAdmin();
- List<Step> steps = cloneAdmin.getSteps();
-
- for (int i = steps.size()-1; i >= idx; i--) {
- cloneAdmin.removeStep(i);
- }
- return cloneAdmin;
- }
-
- @Override
- protected QueryBuilder<E> removeQueryStepsBetween(int start, int end) {
- GraphTraversal<Vertex, E> clone = this.traversal.asAdmin().clone();
- GraphTraversal.Admin<Vertex, E> cloneAdmin = clone.asAdmin();
-
- for (int i = end-2; i >= start; i--) {
- cloneAdmin.removeStep(i);
- }
- return new TraversalQuery<>(cloneAdmin, loader, source, this);
- }
+ /**
+ * Instantiates a new traversal query.
+ *
+ * @param loader the loader
+ */
+ public TraversalQuery(Loader loader, GraphTraversalSource source) {
+ super(loader, source);
+ this.factory = new TraversalStrategy(this.loader, this);
+ }
+
+ /**
+ * Instantiates a new traversal query.
+ *
+ * @param loader the loader
+ * @param start the start
+ */
+ public TraversalQuery(Loader loader, GraphTraversalSource source, Vertex start) {
+ super(loader, source, start);
+ this.factory = new TraversalStrategy(this.loader, this);
+ }
+
+ protected TraversalQuery(GraphTraversal<Vertex, E> traversal, Loader loader, GraphTraversalSource source,
+ GraphTraversalBuilder<E> gtb) {
+ super(loader, source);
+ this.traversal = traversal;
+ this.stepIndex = gtb.getStepIndex();
+ this.parentStepIndex = gtb.getParentStepIndex();
+ this.containerStepIndex = gtb.getContainerStepIndex();
+ this.factory = new TraversalStrategy(this.loader, this);
+ this.start = gtb.getStart();
+ }
+
+ /**
+ * @{inheritDoc}
+ */
+ @Override
+ public QueryParser createQueryFromURI(URI uri) throws UnsupportedEncodingException, AAIException {
+ return factory.buildURIParser(uri);
+ }
+
+ /**
+ * @{inheritDoc}
+ */
+ @Override
+ public QueryParser createQueryFromRelationship(Introspector relationship)
+ throws UnsupportedEncodingException, AAIException {
+ return factory.buildRelationshipParser(relationship);
+ }
+
+ /**
+ * @{inheritDoc}
+ */
+ @Override
+ public QueryParser createQueryFromURI(URI uri, MultivaluedMap<String, String> queryParams)
+ throws UnsupportedEncodingException, AAIException {
+ return factory.buildURIParser(uri, queryParams);
+ }
+
+ /**
+ * @{inheritDoc}
+ */
+ @Override
+ public QueryParser createQueryFromObjectName(String objName) {
+ return factory.buildObjectNameParser(objName);
+ }
+
+ /**
+ * @{inheritDoc}
+ */
+ @Override
+ public QueryBuilder<E> newInstance(Vertex start) {
+ return new TraversalQuery<>(loader, source, start);
+ }
+
+ /**
+ * @{inheritDoc}
+ */
+ @Override
+ public QueryBuilder<E> newInstance() {
+ return new TraversalQuery<>(loader, source);
+ }
+
+ @Override
+ protected QueryBuilder<E> cloneQueryAtStep(int index) {
+ GraphTraversal.Admin<Vertex, E> cloneAdmin = getCloneAdmin(index);
+ return new TraversalQuery<>(cloneAdmin, loader, source, this);
+ }
+
+ protected GraphTraversal.Admin<Vertex, E> getCloneAdmin(int index) {
+ int idx = index;
+
+ if (idx == 0) {
+ idx = stepIndex;
+ }
+
+ GraphTraversal<Vertex, E> clone = this.traversal.asAdmin().clone();
+ GraphTraversal.Admin<Vertex, E> cloneAdmin = clone.asAdmin();
+ List<Step> steps = cloneAdmin.getSteps();
+
+ for (int i = steps.size() - 1; i >= idx; i--) {
+ cloneAdmin.removeStep(i);
+ }
+ return cloneAdmin;
+ }
+
+ @Override
+ protected QueryBuilder<E> removeQueryStepsBetween(int start, int end) {
+ GraphTraversal<Vertex, E> clone = this.traversal.asAdmin().clone();
+ GraphTraversal.Admin<Vertex, E> cloneAdmin = clone.asAdmin();
+
+ for (int i = end - 2; i >= start; i--) {
+ cloneAdmin.removeStep(i);
+ }
+ return new TraversalQuery<>(cloneAdmin, loader, source, this);
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/query/builder/TraversalURIOptimizedQuery.java b/aai-core/src/main/java/org/onap/aai/query/builder/TraversalURIOptimizedQuery.java
index 6a247c2a..91d2d084 100644
--- a/aai-core/src/main/java/org/onap/aai/query/builder/TraversalURIOptimizedQuery.java
+++ b/aai-core/src/main/java/org/onap/aai/query/builder/TraversalURIOptimizedQuery.java
@@ -17,8 +17,15 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.query.builder;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.stream.Collectors;
+
import org.apache.tinkerpop.gremlin.process.traversal.Step;
import org.apache.tinkerpop.gremlin.process.traversal.Traversal;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
@@ -30,151 +37,149 @@ import org.onap.aai.introspection.Introspector;
import org.onap.aai.introspection.Loader;
import org.onap.aai.schema.enums.ObjectMetadata;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
-import java.util.stream.Collectors;
-
public class TraversalURIOptimizedQuery<E> extends TraversalQuery {
- protected Map<Integer, String> stepToAaiUri = new HashMap<>();
-
- public TraversalURIOptimizedQuery(Loader loader, GraphTraversalSource source) {
- super(loader, source);
- optimize = true;
- }
-
- public TraversalURIOptimizedQuery(Loader loader, GraphTraversalSource source, Vertex start) {
- super(loader, source, start);
- optimize = true;
- }
-
- protected TraversalURIOptimizedQuery(GraphTraversal traversal, Loader loader, GraphTraversalSource source, GraphTraversalBuilder gtb) {
- super(traversal, loader, source, gtb);
- optimize = true;
- }
-
- protected TraversalURIOptimizedQuery(GraphTraversal traversal, Loader loader, GraphTraversalSource source, GraphTraversalBuilder gtb, Map<Integer, String> stepToAaiUri) {
- super(traversal, loader, source, gtb);
- optimize = gtb.optimize;
- this.stepToAaiUri = stepToAaiUri;
- }
+ protected Map<Integer, String> stepToAaiUri = new HashMap<>();
- @Override
- protected void executeQuery() {
+ public TraversalURIOptimizedQuery(Loader loader, GraphTraversalSource source) {
+ super(loader, source);
+ optimize = true;
+ }
- this.completeTraversal = this.traversal.asAdmin().clone();
+ public TraversalURIOptimizedQuery(Loader loader, GraphTraversalSource source, Vertex start) {
+ super(loader, source, start);
+ optimize = true;
+ }
- if (this.optimize) {
- this.completeTraversal = this.pivotTraversal(this.completeTraversal);
- }
+ protected TraversalURIOptimizedQuery(GraphTraversal traversal, Loader loader, GraphTraversalSource source,
+ GraphTraversalBuilder gtb) {
+ super(traversal, loader, source, gtb);
+ optimize = true;
+ }
- if (start == null) {
- Traversal.Admin admin = source.V().asAdmin();
- TraversalHelper.insertTraversal(admin.getEndStep(), completeTraversal, admin);
+ protected TraversalURIOptimizedQuery(GraphTraversal traversal, Loader loader, GraphTraversalSource source,
+ GraphTraversalBuilder gtb, Map<Integer, String> stepToAaiUri) {
+ super(traversal, loader, source, gtb);
+ optimize = gtb.optimize;
+ this.stepToAaiUri = stepToAaiUri;
+ }
- this.completeTraversal = (Traversal.Admin<Vertex, E>) admin;
+ @Override
+ protected void executeQuery() {
- }
+ this.completeTraversal = this.traversal.asAdmin().clone();
- }
+ if (this.optimize) {
+ this.completeTraversal = this.pivotTraversal(this.completeTraversal);
+ }
- private Traversal.Admin<Vertex,E> pivotTraversal(Traversal.Admin<Vertex, E> traversalAdmin) {
+ if (start == null) {
+ Traversal.Admin admin = source.V().asAdmin();
+ TraversalHelper.insertTraversal(admin.getEndStep(), completeTraversal, admin);
- List<Step> steps = traversalAdmin.getSteps();
+ this.completeTraversal = (Traversal.Admin<Vertex, E>) admin;
- Traversal.Admin<Vertex, E> traversalAdminStart = traversalAdmin.clone();
+ }
- //if we do not have an index or other conditions do no optimization
- if (stepToAaiUri.isEmpty()) {
- return traversalAdmin;
- }
+ }
- int lastURIStepKey = getLastURIStepKey();
+ private Traversal.Admin<Vertex, E> pivotTraversal(Traversal.Admin<Vertex, E> traversalAdmin) {
- //clean up traversal steps
- for (int i = 0; i < steps.size(); i++) {
- traversalAdminStart.removeStep(0);
- }
+ List<Step> steps = traversalAdmin.getSteps();
- ((GraphTraversal<Vertex, E>)traversalAdminStart).has(AAIProperties.AAI_URI, stepToAaiUri.get(lastURIStepKey));
- for (int i = lastURIStepKey; i < steps.size(); i++) {
- traversalAdminStart.addStep(steps.get(i));
- }
+ Traversal.Admin<Vertex, E> traversalAdminStart = traversalAdmin.clone();
- return traversalAdminStart;
- }
+ // if we do not have an index or other conditions do no optimization
+ if (stepToAaiUri.isEmpty()) {
+ return traversalAdmin;
+ }
- @Override
- public QueryBuilder<Vertex> createKeyQuery(Introspector obj) {
- super.createKeyQuery(obj);
+ int lastURIStepKey = getLastURIStepKey();
- if (shouldAddStepUri(obj)) {
- Optional<String> uri = getStepUriFromIntrospector(obj);
- if (uri.isPresent()) {
- if (stepToAaiUri.isEmpty()) {
- stepToAaiUri.put(stepIndex + 1, uri.get());
- } else {
- stepToAaiUri.put(stepIndex, uri.get());
- }
- }
- } else {
- optimize = false;
- stepToAaiUri = new HashMap<>();
- }
- return (QueryBuilder<Vertex>) this;
- }
+ // clean up traversal steps
+ for (int i = 0; i < steps.size(); i++) {
+ traversalAdminStart.removeStep(0);
+ }
- private boolean shouldAddStepUri(Introspector obj) {
- boolean shouldOptimize = optimize;
+ ((GraphTraversal<Vertex, E>) traversalAdminStart).has(AAIProperties.AAI_URI, stepToAaiUri.get(lastURIStepKey));
+ for (int i = lastURIStepKey; i < steps.size(); i++) {
+ traversalAdminStart.addStep(steps.get(i));
+ }
- if (shouldOptimize && start != null) {
- shouldOptimize = false;
- }
+ return traversalAdminStart;
+ }
- if (shouldOptimize && stepToAaiUri.isEmpty() && !obj.isTopLevel()) {
- shouldOptimize = false;
- }
+ @Override
+ public QueryBuilder<Vertex> createKeyQuery(Introspector obj) {
+ super.createKeyQuery(obj);
- if (shouldOptimize && obj.getMetadata(ObjectMetadata.ABSTRACT) != null) {
- shouldOptimize = false;
- }
-
- return shouldOptimize;
+ if (shouldAddStepUri(obj)) {
+ Optional<String> uri = getStepUriFromIntrospector(obj);
+ if (uri.isPresent()) {
+ if (stepToAaiUri.isEmpty()) {
+ stepToAaiUri.put(stepIndex + 1, uri.get());
+ } else {
+ stepToAaiUri.put(stepIndex, uri.get());
+ }
+ }
+ } else {
+ optimize = false;
+ stepToAaiUri = new HashMap<>();
+ }
+ return (QueryBuilder<Vertex>) this;
+ }
- }
+ private boolean shouldAddStepUri(Introspector obj) {
+ boolean shouldOptimize = optimize;
- private Optional<String> getStepUriFromIntrospector(Introspector obj) {
- String uri = "";
- try {
- uri = obj.getURI();
- } catch (Exception e) {
- }
+ if (shouldOptimize && start != null) {
+ shouldOptimize = false;
+ }
- if ("".equals(uri)) {
- return Optional.empty();
- }
+ if (shouldOptimize && stepToAaiUri.isEmpty() && !obj.isTopLevel()) {
+ shouldOptimize = false;
+ }
+
+ if (shouldOptimize && obj.getMetadata(ObjectMetadata.ABSTRACT) != null) {
+ shouldOptimize = false;
+ }
+
+ return shouldOptimize;
+
+ }
+
+ private Optional<String> getStepUriFromIntrospector(Introspector obj) {
+ String uri = "";
+ try {
+ uri = obj.getURI();
+ } catch (Exception e) {
+ }
- if (!stepToAaiUri.isEmpty()) {
- uri = stepToAaiUri.get(getLastURIStepKey()) + uri;
- }
+ if ("".equals(uri)) {
+ return Optional.empty();
+ }
- return Optional.of(uri);
- }
+ if (!stepToAaiUri.isEmpty()) {
+ uri = stepToAaiUri.get(getLastURIStepKey()) + uri;
+ }
- private int getLastURIStepKey() {
- return stepToAaiUri.keySet().stream().mapToInt(Integer::intValue).max().getAsInt();
- }
+ return Optional.of(uri);
+ }
- private Map<Integer, String> getStepToAaiUriWithoutStepGreaterThan(final int index) {
- return stepToAaiUri.entrySet().stream().filter(kv -> kv.getKey() <= index).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
- }
+ private int getLastURIStepKey() {
+ return stepToAaiUri.keySet().stream().mapToInt(Integer::intValue).max().getAsInt();
+ }
+
+ private Map<Integer, String> getStepToAaiUriWithoutStepGreaterThan(final int index) {
+ return stepToAaiUri.entrySet().stream().filter(kv -> kv.getKey() <= index)
+ .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
+ }
- @Override
- protected QueryBuilder<E> cloneQueryAtStep(int index) {
- GraphTraversal.Admin<Vertex, E> cloneAdmin = getCloneAdmin(index);
- return new TraversalURIOptimizedQuery<>(cloneAdmin, loader, source, this, getStepToAaiUriWithoutStepGreaterThan(index));
- }
+ @Override
+ protected QueryBuilder<E> cloneQueryAtStep(int index) {
+ GraphTraversal.Admin<Vertex, E> cloneAdmin = getCloneAdmin(index);
+ return new TraversalURIOptimizedQuery<>(cloneAdmin, loader, source, this,
+ getStepToAaiUriWithoutStepGreaterThan(index));
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/rest/RestHandlerService.java b/aai-core/src/main/java/org/onap/aai/rest/RestHandlerService.java
index 69525e29..aeb58c4b 100644
--- a/aai-core/src/main/java/org/onap/aai/rest/RestHandlerService.java
+++ b/aai-core/src/main/java/org/onap/aai/rest/RestHandlerService.java
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.rest;
import java.util.concurrent.Executors;
@@ -25,11 +26,12 @@ import java.util.concurrent.ThreadPoolExecutor;
public class RestHandlerService {
private static RestHandlerService single_instance = null;
public ThreadPoolExecutor executor;
+
// private constructor restricted to this class itself
- private RestHandlerService()
- {
+ private RestHandlerService() {
executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(50);
}
+
/**
* Gets the single instance of RestHandlerService.
*
diff --git a/aai-core/src/main/java/org/onap/aai/rest/RestTokens.java b/aai-core/src/main/java/org/onap/aai/rest/RestTokens.java
index d1c4d863..bd471b05 100644
--- a/aai-core/src/main/java/org/onap/aai/rest/RestTokens.java
+++ b/aai-core/src/main/java/org/onap/aai/rest/RestTokens.java
@@ -17,19 +17,20 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.rest;
public enum RestTokens {
- COUSIN("related-to");
- private final String name;
+ COUSIN("related-to");
+ private final String name;
- private RestTokens(String name) {
- this.name = name;
- }
+ private RestTokens(String name) {
+ this.name = name;
+ }
- @Override
- public String toString() {
- return name;
- }
+ @Override
+ public String toString() {
+ return name;
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/rest/db/DBRequest.java b/aai-core/src/main/java/org/onap/aai/rest/db/DBRequest.java
index c378ae74..1f94fbe2 100644
--- a/aai-core/src/main/java/org/onap/aai/rest/db/DBRequest.java
+++ b/aai-core/src/main/java/org/onap/aai/rest/db/DBRequest.java
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.rest.db;
import java.net.URI;
@@ -35,216 +36,216 @@ import org.onap.aai.restcore.HttpMethod;
*/
public class DBRequest {
- private final QueryParser parser;
-
- private final Introspector introspector;
-
- private final HttpHeaders headers;
-
- private final String transactionId;
-
- private final UriInfo info;
-
- private final HttpMethod method;
-
- private final URI uri;
-
- private final Optional<String> rawRequestContent;
-
- private final Optional<MarshallerProperties> marshallerProperties;
-
-
- /**
- * Instantiates a new DB request.
- *
- * @param method the method
- * @param uri the uri
- * @param parser the parser
- * @param obj the obj
- * @param headers the headers
- * @param info the info
- * @param transactionId the transaction id
- */
- private DBRequest(Builder builder) {
- this.method = builder.getMethod();
- this.parser = builder.getParser();
- this.introspector = builder.getIntrospector();
- this.headers = builder.getHeaders();
- this.transactionId = builder.getTransactionId();
- this.info = builder.getInfo();
- this.uri = builder.getUri();
- this.marshallerProperties = builder.getMarshallerProperties();
- this.rawRequestContent = builder.getRawRequestContent();
- }
-
- /**
- * Gets the headers.
- *
- * @return the headers
- */
- public HttpHeaders getHeaders() {
- return headers;
- }
-
-
- /**
- * Gets the transaction id.
- *
- * @return the transaction id
- */
- public String getTransactionId() {
- return transactionId;
- }
-
- /**
- * Gets the info.
- *
- * @return the info
- */
- public UriInfo getInfo() {
- return info;
- }
-
- /**
- * Gets the parser.
- *
- * @return the parser
- */
- public QueryParser getParser() {
- return parser;
- }
-
- /**
- * Gets the introspector.
- *
- * @return the introspector
- */
- public Introspector getIntrospector() {
- return introspector;
- }
-
- /**
- * Gets the method.
- *
- * @return the method
- */
- public HttpMethod getMethod() {
- return method;
- }
-
- /**
- * Gets the uri.
- *
- * @return the uri
- */
- public URI getUri() {
- return uri;
- }
-
- /**
- * Gets the raw content.
- *
- * @return the raw content
- */
- public Optional<String> getRawRequestContent() {
- return rawRequestContent;
- }
-
- public Optional<MarshallerProperties> getMarshallerProperties() {
- return marshallerProperties;
- }
-
-
-
- public static class Builder {
-
- private QueryParser parser = null;
-
- private Introspector introspector = null;
-
- private HttpHeaders headers = null;
-
- private String transactionId = null;
-
- private UriInfo info = null;
-
- private HttpMethod method = null;
-
- private URI uri = null;
-
- private Optional<MarshallerProperties> marshallerProperties = Optional.empty();
-
- private Optional<String> rawRequestContent = Optional.empty();
- /**
- * Instantiates a new DB request.
- *
- * @param method the method
- * @param uri the uri
- * @param parser the parser
- * @param obj the obj
- * @param headers the headers
- * @param info the info
- * @param transactionId the transaction id
- */
- public Builder(HttpMethod method, URI uri, QueryParser parser, Introspector obj, HttpHeaders headers, UriInfo info, String transactionId) {
- this.method = method;
- this.parser = parser;
- this.introspector = obj;
- this.headers = headers;
- this.transactionId = transactionId;
- this.info = info;
- this.uri = uri;
-
- }
-
- public QueryParser getParser() {
- return parser;
- }
-
- public Introspector getIntrospector() {
- return introspector;
- }
-
- public HttpHeaders getHeaders() {
- return headers;
- }
-
- public String getTransactionId() {
- return transactionId;
- }
-
- public UriInfo getInfo() {
- return info;
- }
-
- public HttpMethod getMethod() {
- return method;
- }
-
- public URI getUri() {
- return uri;
- }
-
- public Builder customMarshaller(MarshallerProperties properties) {
- this.marshallerProperties = Optional.of(properties);
- return this;
- }
-
- public Builder rawRequestContent(String content) {
- this.rawRequestContent = Optional.of(content);
- return this;
- }
- protected Optional<MarshallerProperties> getMarshallerProperties() {
- return marshallerProperties;
- }
- protected Optional<String> getRawRequestContent() {
- return rawRequestContent;
- }
- public DBRequest build() {
-
- return new DBRequest(this);
- }
-
-
- }
+ private final QueryParser parser;
+
+ private final Introspector introspector;
+
+ private final HttpHeaders headers;
+
+ private final String transactionId;
+
+ private final UriInfo info;
+
+ private final HttpMethod method;
+
+ private final URI uri;
+
+ private final Optional<String> rawRequestContent;
+
+ private final Optional<MarshallerProperties> marshallerProperties;
+
+ /**
+ * Instantiates a new DB request.
+ *
+ * @param method the method
+ * @param uri the uri
+ * @param parser the parser
+ * @param obj the obj
+ * @param headers the headers
+ * @param info the info
+ * @param transactionId the transaction id
+ */
+ private DBRequest(Builder builder) {
+ this.method = builder.getMethod();
+ this.parser = builder.getParser();
+ this.introspector = builder.getIntrospector();
+ this.headers = builder.getHeaders();
+ this.transactionId = builder.getTransactionId();
+ this.info = builder.getInfo();
+ this.uri = builder.getUri();
+ this.marshallerProperties = builder.getMarshallerProperties();
+ this.rawRequestContent = builder.getRawRequestContent();
+ }
+
+ /**
+ * Gets the headers.
+ *
+ * @return the headers
+ */
+ public HttpHeaders getHeaders() {
+ return headers;
+ }
+
+ /**
+ * Gets the transaction id.
+ *
+ * @return the transaction id
+ */
+ public String getTransactionId() {
+ return transactionId;
+ }
+
+ /**
+ * Gets the info.
+ *
+ * @return the info
+ */
+ public UriInfo getInfo() {
+ return info;
+ }
+
+ /**
+ * Gets the parser.
+ *
+ * @return the parser
+ */
+ public QueryParser getParser() {
+ return parser;
+ }
+
+ /**
+ * Gets the introspector.
+ *
+ * @return the introspector
+ */
+ public Introspector getIntrospector() {
+ return introspector;
+ }
+
+ /**
+ * Gets the method.
+ *
+ * @return the method
+ */
+ public HttpMethod getMethod() {
+ return method;
+ }
+
+ /**
+ * Gets the uri.
+ *
+ * @return the uri
+ */
+ public URI getUri() {
+ return uri;
+ }
+
+ /**
+ * Gets the raw content.
+ *
+ * @return the raw content
+ */
+ public Optional<String> getRawRequestContent() {
+ return rawRequestContent;
+ }
+
+ public Optional<MarshallerProperties> getMarshallerProperties() {
+ return marshallerProperties;
+ }
+
+ public static class Builder {
+
+ private QueryParser parser = null;
+
+ private Introspector introspector = null;
+
+ private HttpHeaders headers = null;
+
+ private String transactionId = null;
+
+ private UriInfo info = null;
+
+ private HttpMethod method = null;
+
+ private URI uri = null;
+
+ private Optional<MarshallerProperties> marshallerProperties = Optional.empty();
+
+ private Optional<String> rawRequestContent = Optional.empty();
+
+ /**
+ * Instantiates a new DB request.
+ *
+ * @param method the method
+ * @param uri the uri
+ * @param parser the parser
+ * @param obj the obj
+ * @param headers the headers
+ * @param info the info
+ * @param transactionId the transaction id
+ */
+ public Builder(HttpMethod method, URI uri, QueryParser parser, Introspector obj, HttpHeaders headers,
+ UriInfo info, String transactionId) {
+ this.method = method;
+ this.parser = parser;
+ this.introspector = obj;
+ this.headers = headers;
+ this.transactionId = transactionId;
+ this.info = info;
+ this.uri = uri;
+
+ }
+
+ public QueryParser getParser() {
+ return parser;
+ }
+
+ public Introspector getIntrospector() {
+ return introspector;
+ }
+
+ public HttpHeaders getHeaders() {
+ return headers;
+ }
+
+ public String getTransactionId() {
+ return transactionId;
+ }
+
+ public UriInfo getInfo() {
+ return info;
+ }
+
+ public HttpMethod getMethod() {
+ return method;
+ }
+
+ public URI getUri() {
+ return uri;
+ }
+
+ public Builder customMarshaller(MarshallerProperties properties) {
+ this.marshallerProperties = Optional.of(properties);
+ return this;
+ }
+
+ public Builder rawRequestContent(String content) {
+ this.rawRequestContent = Optional.of(content);
+ return this;
+ }
+
+ protected Optional<MarshallerProperties> getMarshallerProperties() {
+ return marshallerProperties;
+ }
+
+ protected Optional<String> getRawRequestContent() {
+ return rawRequestContent;
+ }
+
+ public DBRequest build() {
+
+ return new DBRequest(this);
+ }
+
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/rest/db/HttpEntry.java b/aai-core/src/main/java/org/onap/aai/rest/db/HttpEntry.java
index 6f551de7..8556c111 100644
--- a/aai-core/src/main/java/org/onap/aai/rest/db/HttpEntry.java
+++ b/aai-core/src/main/java/org/onap/aai/rest/db/HttpEntry.java
@@ -17,8 +17,15 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.rest.db;
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.github.fge.jsonpatch.JsonPatchException;
+import com.github.fge.jsonpatch.mergepatch.JsonMergePatch;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
@@ -41,12 +48,6 @@ import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriBuilder;
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
-import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.github.fge.jsonpatch.JsonPatchException;
-import com.github.fge.jsonpatch.mergepatch.JsonMergePatch;
import org.apache.commons.lang.StringUtils;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.Vertex;
@@ -69,7 +70,6 @@ import org.onap.aai.logging.LoggingContext;
import org.onap.aai.nodes.NodeIngestor;
import org.onap.aai.parsers.query.QueryParser;
import org.onap.aai.parsers.uri.URIToExtensionInformation;
-
import org.onap.aai.parsers.uri.URIToObject;
import org.onap.aai.rest.ueb.UEBNotification;
import org.onap.aai.restcore.HttpMethod;
@@ -93,1127 +93,1169 @@ import org.springframework.beans.factory.annotation.Value;
*/
public class HttpEntry {
- private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(HttpEntry.class);
- private static final String TARGET_ENTITY = "DB";
-
- private ModelType introspectorFactoryType;
-
- private QueryStyle queryStyle;
-
- private SchemaVersion version;
-
- private Loader loader;
-
- private TransactionalGraphEngine dbEngine;
-
- private boolean processSingle = true;
-
- private int paginationBucket = -1;
- private int paginationIndex = -1;
- private int totalVertices = 0;
- private int totalPaginationBuckets = 0;
-
- @Autowired
- private NodeIngestor nodeIngestor;
-
- @Autowired
- private LoaderFactory loaderFactory;
-
- @Autowired
- private SchemaVersions schemaVersions;
-
- @Value("${schema.uri.base.path}")
- private String basePath;
-
- private UEBNotification notification;
-
- /**
- * Instantiates a new http entry.
- *
- * @param modelType the model type
- * @param queryStyle the query style
- */
- public HttpEntry(ModelType modelType, QueryStyle queryStyle) {
- this.introspectorFactoryType = modelType;
- this.queryStyle = queryStyle;
- }
-
- public HttpEntry setHttpEntryProperties(SchemaVersion version, DBConnectionType connectionType) {
- this.version = version;
- this.loader = loaderFactory.createLoaderForVersion(introspectorFactoryType, version);
- this.dbEngine = new JanusGraphDBEngine(
- queryStyle,
- connectionType,
- loader);
-
- getDbEngine().startTransaction();
- this.notification = new UEBNotification(loader, loaderFactory, schemaVersions);
- return this;
- }
-
-
- public HttpEntry setHttpEntryProperties(SchemaVersion version, DBConnectionType connectionType, UEBNotification notification) {
- this.version = version;
- this.loader = loaderFactory.createLoaderForVersion(introspectorFactoryType, version);
- this.dbEngine = new JanusGraphDBEngine(
- queryStyle,
- connectionType,
- loader);
-
- this.notification = notification;
- //start transaction on creation
- getDbEngine().startTransaction();
- return this;
- }
-
-
- /**
- * Gets the introspector factory type.
- *
- * @return the introspector factory type
- */
- public ModelType getIntrospectorFactoryType() {
- return introspectorFactoryType;
- }
-
- /**
- * Gets the query style.
- *
- * @return the query style
- */
- public QueryStyle getQueryStyle() {
- return queryStyle;
- }
-
- /**
- * Gets the version.
- *
- * @return the version
- */
- public SchemaVersion getVersion() {
- return version;
- }
-
- /**
- * Gets the loader.
- *
- * @return the loader
- */
- public Loader getLoader() {
- return loader;
- }
-
- /**
- * Gets the db engine.
- *
- * @return the db engine
- */
- public TransactionalGraphEngine getDbEngine() {
- return dbEngine;
- }
-
- public Pair<Boolean, List<Pair<URI, Response>>> process(List<DBRequest> requests, String sourceOfTruth) throws AAIException {
- return this.process(requests, sourceOfTruth, true);
- }
-
-
- /**
- * Checks the pagination bucket and pagination index variables to determine whether or not the user
- * requested paginated results
- *
- * @return a boolean true/false of whether the user requested paginated results
- */
- public boolean isPaginated() {
- return this.paginationBucket > -1 && this.paginationIndex > -1;
- }
-
- /**
- * Returns the pagination size
- * @return integer of the size of results to be returned when paginated
- */
- public int getPaginationBucket() {
- return this.paginationBucket;
- }
-
- /**
- * Setter for the pagination bucket variable which stores in this object the size of results to return
- * @param pb
- */
- public void setPaginationBucket(int pb) {
- this.paginationBucket = pb;
- }
-
- /**
- * Getter to return the pagination index requested by the user when requesting paginated results
- * @return
- */
- public int getPaginationIndex() {
- return this.paginationIndex;
- }
-
- /**
- * Sets the pagination index that was passed in by the user, to determine which index or results to retrieve when
- * paginated
- * @param pi
- */
- public void setPaginationIndex(int pi) {
- if (pi == 0) {
- pi = 1;
- }
- this.paginationIndex = pi;
- }
-
- /**
- * Sets the total vertices variables and calculates the amount of pages based on size and total vertices
- * @param totalVertices
- * @param paginationBucketSize
- */
- public void setTotalsForPaging(int totalVertices, int paginationBucketSize) {
- this.totalVertices = totalVertices;
- //set total number of buckets equal to full pages
- this.totalPaginationBuckets = totalVertices / paginationBucketSize;
- //conditionally add a page for the remainder
- if (totalVertices % paginationBucketSize > 0) {
- this.totalPaginationBuckets++;
- }
- }
-
- /**
- * @return the total amount of pages
- */
- public int getTotalPaginationBuckets() {
- return this.totalPaginationBuckets;
- }
-
- /**
- *
- * @return the total number of vertices when paginated
- */
- public int getTotalVertices() {
- return this.totalVertices;
- }
-
- /**
- * Process.
- * @param requests the requests
- * @param sourceOfTruth the source of truth
- *
- * @return the pair
- * @throws AAIException the AAI exception
- */
- public Pair<Boolean, List<Pair<URI, Response>>> process(List<DBRequest> requests, String sourceOfTruth, boolean enableResourceVersion) throws AAIException {
-
- DBSerializer serializer = new DBSerializer(version, dbEngine, introspectorFactoryType, sourceOfTruth);
- String methodName = "process";
- Response response;
- Introspector obj = null;
- QueryParser query = null;
- URI uri = null;
- String transactionId = null;
- int depth = AAIProperties.MAXIMUM_DEPTH;
- Format format = null;
- List<Pair<URI, Response>> responses = new ArrayList<>();
- MultivaluedMap<String, String> params = null;
- HttpMethod method = null;
- String uriTemp = "";
- Boolean success = true;
- QueryEngine queryEngine = dbEngine.getQueryEngine();
- int maxRetries = 10;
- int retry = 0;
-
- LoggingContext.save();
- for (DBRequest request : requests) {
- response = null;
- Status status = Status.NOT_FOUND;
- method = request.getMethod();
- try {
- for (retry = 0; retry < maxRetries; ++retry) {
- try {
-
- LoggingContext.targetEntity(TARGET_ENTITY);
- LoggingContext.targetServiceName(methodName + " " + method);
-
- obj = request.getIntrospector();
- query = request.getParser();
- transactionId = request.getTransactionId();
- uriTemp = request.getUri().getRawPath().replaceFirst("^v\\d+/", "");
- uri = UriBuilder.fromPath(uriTemp).build();
- LoggingContext.startTime();
- List<Vertex> vertTemp;
- List<Vertex> vertices;
- if (this.isPaginated()) {
- vertTemp = query.getQueryBuilder().toList();
- this.setTotalsForPaging(vertTemp.size(), this.paginationBucket);
- vertices = vertTemp.subList(((this.paginationIndex - 1) * this.paginationBucket), Math.min((this.paginationBucket * this.paginationIndex), vertTemp.size()));
- } else {
- vertices = query.getQueryBuilder().toList();
- }
- boolean isNewVertex = false;
- String outputMediaType = getMediaType(request.getHeaders().getAcceptableMediaTypes());
- String result = null;
- params = request.getInfo().getQueryParameters(false);
- depth = setDepth(obj, params.getFirst("depth"));
- if (params.containsKey("format")) {
- format = Format.getFormat(params.getFirst("format"));
- }
- String cleanUp = params.getFirst("cleanup");
- String requestContext = "";
- List<String> requestContextList = request.getHeaders().getRequestHeader("aai-request-context");
- if (requestContextList != null) {
- requestContext = requestContextList.get(0);
- }
-
- if (cleanUp == null) {
- cleanUp = "false";
- }
- if (vertices.size() > 1 && processSingle && !(method.equals(HttpMethod.GET) || method.equals(HttpMethod.GET_RELATIONSHIP))) {
- if (method.equals(HttpMethod.DELETE)) {
- LoggingContext.restoreIfPossible();
- throw new AAIException("AAI_6138");
- } else {
- LoggingContext.restoreIfPossible();
- throw new AAIException("AAI_6137");
- }
- }
- if (method.equals(HttpMethod.PUT)) {
- String resourceVersion = (String) obj.getValue("resource-version");
- if (vertices.isEmpty()) {
- if (enableResourceVersion) {
- serializer.verifyResourceVersion("create", query.getResultType(), "", resourceVersion, obj.getURI());
- }
- isNewVertex = true;
- } else {
- if (enableResourceVersion) {
- serializer.verifyResourceVersion("update", query.getResultType(), vertices.get(0).<String>property("resource-version").orElse(null), resourceVersion, obj.getURI());
- }
- isNewVertex = false;
- }
- } else {
- if (vertices.isEmpty()) {
- String msg = createNotFoundMessage(query.getResultType(), request.getUri());
- throw new AAIException("AAI_6114", msg);
- } else {
- isNewVertex = false;
- }
- }
- Vertex v = null;
- if (!isNewVertex) {
- v = vertices.get(0);
- }
- HashMap<String, Introspector> relatedObjects = new HashMap<>();
- String nodeOnly = params.getFirst("nodes-only");
- boolean isNodeOnly = nodeOnly != null;
- switch (method) {
- case GET:
-
- if (format == null) {
- obj = this.getObjectFromDb(vertices, serializer, query, obj, request.getUri(), depth, isNodeOnly, cleanUp);
-
-
- LoggingContext.elapsedTime((long) serializer.getDBTimeMsecs(), TimeUnit.MILLISECONDS);
- LOGGER.info("Completed");
- LoggingContext.restoreIfPossible();
-
- if (obj != null) {
- status = Status.OK;
- MarshallerProperties properties;
- if (!request.getMarshallerProperties().isPresent()) {
- properties = new MarshallerProperties.Builder(org.onap.aai.restcore.MediaType.getEnum(outputMediaType)).build();
- } else {
- properties = request.getMarshallerProperties().get();
- }
- result = obj.marshal(properties);
- }
- } else {
- FormatFactory ff = new FormatFactory(loader, serializer, schemaVersions, basePath + "/");
- Formatter formatter = ff.get(format, params);
- result = formatter.output(vertices.stream().map(vertex -> (Object) vertex).collect(Collectors.toList())).toString();
- status = Status.OK;
- }
-
- break;
- case GET_RELATIONSHIP:
- if (format == null) {
- obj = this.getRelationshipObjectFromDb(vertices, serializer, query, request.getInfo().getRequestUri());
-
- LoggingContext.elapsedTime((long) serializer.getDBTimeMsecs(), TimeUnit.MILLISECONDS);
- LOGGER.info("Completed");
- LoggingContext.restoreIfPossible();
-
- if (obj != null) {
- status = Status.OK;
- MarshallerProperties properties;
- if (!request.getMarshallerProperties().isPresent()) {
- properties = new MarshallerProperties.Builder(org.onap.aai.restcore.MediaType.getEnum(outputMediaType)).build();
- } else {
- properties = request.getMarshallerProperties().get();
- }
- result = obj.marshal(properties);
- } else {
- String msg = createRelationshipNotFoundMessage(query.getResultType(), request.getUri());
- throw new AAIException("AAI_6149", msg);
- }
- } else {
- FormatFactory ff = new FormatFactory(loader, serializer, schemaVersions, basePath + "/");
- Formatter formatter = ff.get(format, params);
- result = formatter.output(vertices.stream().map(vertex -> (Object) vertex).collect(Collectors.toList())).toString();
- status = Status.OK;
- }
- break;
- case PUT:
- response = this.invokeExtension(dbEngine, this.dbEngine.tx(), method, request, sourceOfTruth, version, loader, obj, uri, true);
- if (isNewVertex) {
- v = serializer.createNewVertex(obj);
- }
- serializer.serializeToDb(obj, v, query, uri.getRawPath(), requestContext);
- this.invokeExtension(dbEngine, this.dbEngine.tx(), HttpMethod.PUT, request, sourceOfTruth, version, loader, obj, uri, false);
- status = Status.OK;
- if (isNewVertex) {
- status = Status.CREATED;
- }
- obj = serializer.getLatestVersionView(v);
- if (query.isDependent()) {
- relatedObjects = this.getRelatedObjects(serializer, queryEngine, v, obj, this.loader);
- }
- LoggingContext.elapsedTime((long) serializer.getDBTimeMsecs() +
- (long) queryEngine.getDBTimeMsecs(), TimeUnit.MILLISECONDS);
- LOGGER.info("Completed ");
- LoggingContext.restoreIfPossible();
- notification.createNotificationEvent(transactionId, sourceOfTruth, status, uri, obj, relatedObjects, basePath);
-
- break;
- case PUT_EDGE:
- serializer.touchStandardVertexProperties(v, false);
- this.invokeExtension(dbEngine, this.dbEngine.tx(), method, request, sourceOfTruth, version, loader, obj, uri, true);
- serializer.createEdge(obj, v);
-
- LoggingContext.elapsedTime((long) serializer.getDBTimeMsecs(), TimeUnit.MILLISECONDS);
- LOGGER.info("Completed");
- LoggingContext.restoreIfPossible();
- status = Status.OK;
- notification.createNotificationEvent(transactionId, sourceOfTruth, status, new URI(uri.toString().replace("/relationship-list/relationship", "")), serializer.getLatestVersionView(v), relatedObjects, basePath);
- break;
- case MERGE_PATCH:
- Introspector existingObj = loader.introspectorFromName(obj.getDbName());
- existingObj = this.getObjectFromDb(vertices, serializer, query, existingObj, request.getUri(), 0, false, cleanUp);
- String existingJson = existingObj.marshal(false);
- String newJson;
-
- if (request.getRawRequestContent().isPresent()) {
- newJson = request.getRawRequestContent().get();
- } else {
- newJson = "";
- }
- Object relationshipList = request.getIntrospector().getValue("relationship-list");
- ObjectMapper mapper = new ObjectMapper();
- try {
- JsonNode existingNode = mapper.readTree(existingJson);
- JsonNode newNode = mapper.readTree(newJson);
- JsonMergePatch patch = JsonMergePatch.fromJson(newNode);
- JsonNode completed = patch.apply(existingNode);
- String patched = mapper.writeValueAsString(completed);
- Introspector patchedObj = loader.unmarshal(existingObj.getName(), patched);
- if (relationshipList == null) {
- //if the caller didn't touch the relationship-list, we shouldn't either
- patchedObj.setValue("relationship-list", null);
- }
- serializer.serializeToDb(patchedObj, v, query, uri.getRawPath(), requestContext);
- status = Status.OK;
- patchedObj = serializer.getLatestVersionView(v);
- if (query.isDependent()) {
- relatedObjects = this.getRelatedObjects(serializer, queryEngine, v, patchedObj, this.loader);
- }
- LoggingContext.elapsedTime((long) serializer.getDBTimeMsecs() +
- (long) queryEngine.getDBTimeMsecs(), TimeUnit.MILLISECONDS);
- LOGGER.info("Completed");
- LoggingContext.restoreIfPossible();
- notification.createNotificationEvent(transactionId, sourceOfTruth, status, uri, patchedObj, relatedObjects, basePath);
- } catch (IOException | JsonPatchException e) {
-
- LOGGER.info("Caught exception: " + e.getMessage());
- LoggingContext.restoreIfPossible();
- throw new AAIException("AAI_3000", "could not perform patch operation");
- }
- break;
- case DELETE:
- String resourceVersion = params.getFirst("resource-version");
- obj = serializer.getLatestVersionView(v);
- if (query.isDependent()) {
- relatedObjects = this.getRelatedObjects(serializer, queryEngine, v, obj, this.loader);
- }
- /*
- * Find all Delete-other-vertex vertices and create structure for notify
- * findDeleatble also returns the startVertex v and we dont want to create
- * duplicate notification events for the same
- * So remove the startvertex first
- */
-
- List<Vertex> deletableVertices = dbEngine.getQueryEngine().findDeletable(v);
- Long vId = (Long) v.id();
-
- /*
- * I am assuming vertexId cant be null
- */
- deletableVertices.removeIf(s -> vId.equals(s.id()));
- boolean isDelVerticesPresent = !deletableVertices.isEmpty();
- Map<Vertex, Introspector> deleteObjects = new HashMap<>();
- Map<String, URI> uriMap = new HashMap<>();
- Map<String, HashMap<String, Introspector>> deleteRelatedObjects = new HashMap<>();
-
- if (isDelVerticesPresent) {
- deleteObjects = this.buildIntrospectorObjects(serializer, deletableVertices);
-
- uriMap = this.buildURIMap(serializer, deleteObjects);
- deleteRelatedObjects = this.buildRelatedObjects(serializer, queryEngine, deleteObjects);
- }
-
- this.invokeExtension(dbEngine, this.dbEngine.tx(), method, request, sourceOfTruth, version, loader, obj, uri, true);
- serializer.delete(v, deletableVertices, resourceVersion, enableResourceVersion);
- this.invokeExtension(dbEngine, this.dbEngine.tx(), method, request, sourceOfTruth, version, loader, obj, uri, false);
-
- LoggingContext.elapsedTime((long) serializer.getDBTimeMsecs() +
- (long) queryEngine.getDBTimeMsecs(), TimeUnit.MILLISECONDS);
- LOGGER.info("Completed");
- LoggingContext.restoreIfPossible();
- status = Status.NO_CONTENT;
- notification.createNotificationEvent(transactionId, sourceOfTruth, status, uri, obj, relatedObjects, basePath);
-
- /*
- * Notify delete-other-v candidates
- */
-
- if (isDelVerticesPresent) {
- this.buildNotificationEvent(sourceOfTruth, status, transactionId, notification, deleteObjects,
- uriMap, deleteRelatedObjects, basePath);
- }
-
- break;
- case DELETE_EDGE:
- serializer.touchStandardVertexProperties(v, false);
- serializer.deleteEdge(obj, v);
-
- LoggingContext.elapsedTime((long) serializer.getDBTimeMsecs(), TimeUnit.MILLISECONDS);
- LOGGER.info("Completed");
- LoggingContext.restoreIfPossible();
- status = Status.NO_CONTENT;
- notification.createNotificationEvent(transactionId, sourceOfTruth, Status.OK, new URI(uri.toString().replace("/relationship-list/relationship", "")), serializer.getLatestVersionView(v), relatedObjects, basePath);
- break;
- default:
- break;
- }
-
-
- /* temporarily adding vertex id to the headers
- * to be able to use for testing the vertex id endpoint functionality
- * since we presently have no other way of generating those id urls
- */
- if (response == null && v != null && (
- method.equals(HttpMethod.PUT)
- || method.equals(HttpMethod.GET)
- || method.equals(HttpMethod.MERGE_PATCH)
- || method.equals(HttpMethod.GET_RELATIONSHIP))
-
- ) {
- String myvertid = v.id().toString();
- if (this.isPaginated()) {
- response = Response.status(status)
- .header("vertex-id", myvertid)
- .header("total-results", this.getTotalVertices())
- .header("total-pages", this.getTotalPaginationBuckets())
- .entity(result)
- .type(outputMediaType).build();
- } else {
- response = Response.status(status)
- .header("vertex-id", myvertid)
- .entity(result)
- .type(outputMediaType).build();
- }
- } else if (response == null) {
- response = Response.status(status)
- .type(outputMediaType).build();
- } else {
- //response already set to something
- }
- Pair<URI, Response> pairedResp = Pair.with(request.getUri(), response);
- responses.add(pairedResp);
- //break out of retry loop
- break;
- } catch (JanusGraphException e) {
- this.dbEngine.rollback();
-
- LOGGER.info("Caught exception: " + e.getMessage());
- LoggingContext.restoreIfPossible();
- AAIException ex = new AAIException("AAI_6142", e);
- ErrorLogHelper.logException(ex);
- Thread.sleep((retry + 1) * 20L);
- this.dbEngine.startTransaction();
- queryEngine = dbEngine.getQueryEngine();
- serializer = new DBSerializer(version, dbEngine, introspectorFactoryType, sourceOfTruth);
- }
- if (retry == maxRetries) {
- throw new AAIException("AAI_6134");
- }
- }
- } catch (AAIException e) {
- success = false;
- ArrayList<String> templateVars = new ArrayList<>();
- templateVars.add(request.getMethod().toString()); //GET, PUT, etc
- templateVars.add(request.getUri().getPath());
- templateVars.addAll(e.getTemplateVars());
- ErrorLogHelper.logException(e);
- response = Response
- .status(e.getErrorObject().getHTTPResponseCode())
- .entity(ErrorLogHelper.getRESTAPIErrorResponse(request.getHeaders().getAcceptableMediaTypes(), e, templateVars))
- .build();
- Pair<URI, Response> pairedResp = Pair.with(request.getUri(), response);
- responses.add(pairedResp);
- continue;
- } catch (Exception e) {
- success = false;
- e.printStackTrace();
- AAIException ex = new AAIException("AAI_4000", e);
- ArrayList<String> templateVars = new ArrayList<String>();
- templateVars.add(request.getMethod().toString()); //GET, PUT, etc
- templateVars.add(request.getUri().getPath().toString());
- ErrorLogHelper.logException(ex);
- response = Response
- .status(ex.getErrorObject().getHTTPResponseCode())
- .entity(ErrorLogHelper.getRESTAPIErrorResponse(request.getHeaders().getAcceptableMediaTypes(), ex, templateVars))
- .build();
- Pair<URI, Response> pairedResp = Pair.with(request.getUri(), response);
- responses.add(pairedResp);
- continue;
- }
- }
- notification.triggerEvents();
- return Pair.with(success, responses);
- }
-
-
- /**
- * Gets the media type.
- *
- * @param mediaTypeList the media type list
- * @return the media type
- */
- private String getMediaType(List<MediaType> mediaTypeList) {
- String mediaType = MediaType.APPLICATION_JSON; // json is the default
- for (MediaType mt : mediaTypeList) {
- if (MediaType.APPLICATION_XML_TYPE.isCompatible(mt)) {
- mediaType = MediaType.APPLICATION_XML;
- }
- }
- return mediaType;
- }
-
- /**
- * Gets the object from db.
- *
- * @param serializer the serializer
- * @param query the query
- * @param obj the obj
- * @param uri the uri
- * @param depth the depth
- * @param cleanUp the clean up
- * @return the object from db
- * @throws AAIException the AAI exception
- * @throws IllegalAccessException the illegal access exception
- * @throws IllegalArgumentException the illegal argument exception
- * @throws InvocationTargetException the invocation target exception
- * @throws SecurityException the security exception
- * @throws InstantiationException the instantiation exception
- * @throws NoSuchMethodException the no such method exception
- * @throws UnsupportedEncodingException the unsupported encoding exception
- * @throws MalformedURLException the malformed URL exception
- * @throws AAIUnknownObjectException
- * @throws URISyntaxException
- */
- private Introspector getObjectFromDb(List<Vertex> results, DBSerializer serializer, QueryParser query, Introspector obj, URI uri, int depth, boolean nodeOnly, String cleanUp) throws AAIException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException, InstantiationException, NoSuchMethodException, UnsupportedEncodingException, AAIUnknownObjectException, URISyntaxException {
-
- //nothing found
- if (results.isEmpty()) {
- String msg = createNotFoundMessage(query.getResultType(), uri);
- throw new AAIException("AAI_6114", msg);
- }
-
- return serializer.dbToObject(results, obj, depth, nodeOnly, cleanUp);
-
- }
-
- /**
- * Gets the object from db.
- *
- * @param serializer the serializer
- * @param query the query
- * @param obj the obj
- * @param uri the uri
- * @param depth the depth
- * @param cleanUp the clean up
- * @return the object from db
- * @throws AAIException the AAI exception
- * @throws IllegalAccessException the illegal access exception
- * @throws IllegalArgumentException the illegal argument exception
- * @throws InvocationTargetException the invocation target exception
- * @throws SecurityException the security exception
- * @throws InstantiationException the instantiation exception
- * @throws NoSuchMethodException the no such method exception
- * @throws UnsupportedEncodingException the unsupported encoding exception
- * @throws MalformedURLException the malformed URL exception
- * @throws AAIUnknownObjectException
- * @throws URISyntaxException
- */
- private Introspector getRelationshipObjectFromDb(List<Vertex> results, DBSerializer serializer, QueryParser query, URI uri) throws AAIException, IllegalArgumentException, SecurityException, UnsupportedEncodingException, AAIUnknownObjectException {
-
- //nothing found
- if (results.isEmpty()) {
- String msg = createNotFoundMessage(query.getResultType(), uri);
- throw new AAIException("AAI_6114", msg);
- }
-
- if (results.size() > 1) {
- throw new AAIException("AAI_6148", uri.getPath());
- }
-
- Vertex v = results.get(0);
- return serializer.dbToRelationshipObject(v);
- }
-
- /**
- * Invoke extension.
- *
- * @param dbEngine the db engine
- * @param g the g
- * @param httpMethod the http method
- * @param fromAppId the from app id
- * @param apiVersion the api version
- * @param loader the loader
- * @param obj the obj
- * @param uri the uri
- * @param isPreprocess the is preprocess
- * @return the response
- * @throws IllegalArgumentException the illegal argument exception
- * @throws UnsupportedEncodingException the unsupported encoding exception
- * @throws AAIException the AAI exception
- */
- private Response invokeExtension(TransactionalGraphEngine dbEngine, Graph g, HttpMethod httpMethod, DBRequest request, String fromAppId, SchemaVersion apiVersion, Loader loader, Introspector obj, URI uri, boolean isPreprocess) throws IllegalArgumentException, UnsupportedEncodingException, AAIException {
- AAIExtensionMap aaiExtMap = new AAIExtensionMap();
- //ModelInjestor injestor = ModelInjestor.getInstance();
- Response response = null;
- URIToExtensionInformation extensionInformation = new URIToExtensionInformation(loader, uri);
- aaiExtMap.setHttpEntry(this);
- aaiExtMap.setDbRequest(request);
- aaiExtMap.setTransId(request.getTransactionId());
- aaiExtMap.setFromAppId(fromAppId);
- aaiExtMap.setGraph(g);
- aaiExtMap.setApiVersion(apiVersion.toString());
- aaiExtMap.setObjectFromRequest(obj);
- aaiExtMap.setObjectFromRequestType(obj.getJavaClassName());
- aaiExtMap.setObjectFromResponse(obj);
- aaiExtMap.setObjectFromResponseType(obj.getJavaClassName());
- aaiExtMap.setJaxbContext(nodeIngestor.getContextForVersion(apiVersion));
- aaiExtMap.setUri(uri.getRawPath());
- aaiExtMap.setTransactionalGraphEngine(dbEngine);
- aaiExtMap.setLoader(loader);
- aaiExtMap.setNamespace(extensionInformation.getNamespace());
-
- ExtensionController ext = new ExtensionController();
- ext.runExtension(aaiExtMap.getApiVersion(),
- extensionInformation.getNamespace(),
- extensionInformation.getTopObject(),
- extensionInformation.getMethodName(httpMethod, isPreprocess),
- aaiExtMap,
- isPreprocess);
-
- if (aaiExtMap.getPrecheckAddedList().size() > 0) {
- response = notifyOnSkeletonCreation(aaiExtMap, obj, request.getHeaders());
- }
-
- return response;
- }
-
- /**
- * Notify on skeleton creation.
- *
- * @param aaiExtMap the aai ext map
- * @param input the input
- * @param headers the headers
- * @return the response
- */
- //Legacy support
- private Response notifyOnSkeletonCreation(AAIExtensionMap aaiExtMap, Introspector input, HttpHeaders headers) {
- Response response = null;
- HashMap<AAIException, ArrayList<String>> exceptionList = new HashMap<AAIException, ArrayList<String>>();
-
- StringBuilder keyString = new StringBuilder();
-
- Set<String> resourceKeys = input.getKeys();
- for (String key : resourceKeys) {
- keyString.append(key).append("=").append(input.getValue(key).toString()).append(" ");
- }
-
- for (AAIResponseMessage msg : aaiExtMap.getPrecheckResponseMessages().getAAIResponseMessage()) {
- ArrayList<String> templateVars = new ArrayList<>();
-
- templateVars.add("PUT " + input.getDbName());
- templateVars.add(keyString.toString());
- List<String> keys = new ArrayList<>();
- templateVars.add(msg.getAaiResponseMessageResourceType());
- for (AAIResponseMessageDatum dat : msg.getAaiResponseMessageData().getAAIResponseMessageDatum()) {
- keys.add(dat.getAaiResponseMessageDatumKey() + "=" + dat.getAaiResponseMessageDatumValue());
- }
- templateVars.add(StringUtils.join(keys, ", "));
- exceptionList.put(new AAIException("AAI_0004", msg.getAaiResponseMessageResourceType()),
- templateVars);
- }
- response = Response
- .status(Status.ACCEPTED).entity(ErrorLogHelper
- .getRESTAPIInfoResponse(headers.getAcceptableMediaTypes(), exceptionList))
- .build();
-
- return response;
- }
-
- /**
- * Creates the not found message.
- *
- * @param resultType the result type
- * @param uri the uri
- * @return the string
- */
- private String createNotFoundMessage(String resultType, URI uri) {
-
- String msg = "No Node of type " + resultType + " found at: " + uri.getPath();
-
- return msg;
- }
-
- /**
- * Creates the not found message.
- *
- * @param resultType the result type
- * @param uri the uri
- * @return the string
- */
- private String createRelationshipNotFoundMessage(String resultType, URI uri) {
-
- String msg = "No relationship found of type " + resultType + " at the given URI: " + uri.getPath() + "/relationship-list";
-
- return msg;
- }
-
- /**
- * Sets the depth.
- *
- * @param depthParam the depth param
- * @return the int
- * @throws AAIException the AAI exception
- */
- protected int setDepth(Introspector obj, String depthParam) throws AAIException {
- int depth = AAIProperties.MAXIMUM_DEPTH;
-
- String getAllRandomStr = AAIConfig.get("aai.rest.getall.depthparam", "");
- if (depthParam != null && getAllRandomStr != null && !getAllRandomStr.isEmpty()
- && getAllRandomStr.equals(depthParam)) {
- return depth;
- }
-
- if (depthParam == null) {
- if (this.version.compareTo(schemaVersions.getDepthVersion()) >= 0) {
- depth = 0;
- } else {
- depth = AAIProperties.MAXIMUM_DEPTH;
- }
- } else {
- if (!depthParam.isEmpty() && !"all".equals(depthParam)) {
- try {
- depth = Integer.parseInt(depthParam);
- } catch (Exception e) {
- throw new AAIException("AAI_4016");
- }
-
- }
- }
- String maxDepth = obj.getMetadata(ObjectMetadata.MAXIMUM_DEPTH);
-
- int maximumDepth = AAIProperties.MAXIMUM_DEPTH;
-
- if (maxDepth != null) {
- try {
- maximumDepth = Integer.parseInt(maxDepth);
- } catch (Exception ex) {
- throw new AAIException("AAI_4018");
- }
- }
-
- if (depth > maximumDepth) {
- throw new AAIException("AAI_3303");
- }
-
- return depth;
- }
-
- /**
- * Checks if is modification method.
- *
- * @param method the method
- * @return true, if is modification method
- */
- private boolean isModificationMethod(HttpMethod method) {
- boolean result = false;
-
- if (method.equals(HttpMethod.PUT) || method.equals(HttpMethod.PUT_EDGE) || method.equals(HttpMethod.DELETE_EDGE) || method.equals(HttpMethod.MERGE_PATCH)) {
- result = true;
- }
-
- return result;
-
- }
-
- /**
- * Given an uri, introspector object and loader object
- * it will check if the obj is top level object if it is,
- * it will return immediately returning the uri passed in
- * If it isn't, it will go through, get the uriTemplate
- * from the introspector object and get the count of "/"s
- * and remove that part of the uri using substring
- * and keep doing that until the current object is top level
- * Also added the max depth just so worst case scenario
- * Then keep adding aai-uri to the list include the aai-uri passed in
- * Convert that list into an array and return it
- * <p>
- *
- * Example:
- *
- * <blockquote>
- * aai-uri -> /cloud-infrastructure/cloud-regions/cloud-region/cloud-owner/cloud-region-id/tenants/tenant/tenant1/vservers/vserver/v1
- *
- * Given the uriTemplate vserver -> /vservers/vserver/{vserver-id}
- * it converts to /vservers/vserver
- *
- * lastIndexOf /vservers/vserver in /cloud-infrastructure/cloud-regions/cloud-region/cloud-owner/cloud-region-id/tenants/tenant/tenant1/vservers/vserver/v1
- * ^
- * |
- * |
- * lastIndexOf
- * Use substring to get the string from 0 to that lastIndexOf
- * aai-uri -> /cloud-infrastructure/cloud-regions/cloud-region/cloud-owner/cloud-region-id/tenants/tenant/tenant1
- *
- * From this new aai-uri, generate a introspector from the URITOObject class
- * and keep doing this until you
- *
- * </blockquote>
- *
- * @param aaiUri - aai-uri of the vertex representating the unique id of a given vertex
- * @param obj - introspector object of the given starting vertex
- * @param loader - Type of loader which will always be MoxyLoader to support model driven
- * @return an array of strings which can be used to get the vertexes of parent and grand parents from a given vertex
- * @throws UnsupportedEncodingException
- * @throws AAIException
- */
- String[] convertIntrospectorToUriList(String aaiUri, Introspector obj, Loader loader) throws UnsupportedEncodingException, AAIException {
-
- List<String> uriList = new ArrayList<>();
- String template = StringUtils.EMPTY;
- String truncatedUri = aaiUri;
- int depth = AAIProperties.MAXIMUM_DEPTH;
- uriList.add(truncatedUri);
-
- while (depth >= 0 && !obj.isTopLevel()) {
- template = obj.getMetadata(ObjectMetadata.URI_TEMPLATE);
-
- if (template == null) {
- LOGGER.warn("Unable to find the uriTemplate for the object {}", obj.getDbName());
- return null;
- }
-
- int templateCount = StringUtils.countMatches(template, "/");
- int truncatedUriCount = StringUtils.countMatches(truncatedUri, "/");
-
- if (templateCount > truncatedUriCount) {
- LOGGER.warn("Template uri {} contains more slashes than truncatedUri {}", template, truncatedUri);
- return null;
- }
-
- int cutIndex = StringUtils.ordinalIndexOf(truncatedUri, "/", truncatedUriCount - templateCount + 1);
- truncatedUri = StringUtils.substring(truncatedUri, 0, cutIndex);
- uriList.add(truncatedUri);
- obj = new URIToObject(loader, UriBuilder.fromPath(truncatedUri).build()).getEntity();
- depth--;
- }
-
- return uriList.toArray(new String[uriList.size()]);
- }
-
- /**
- *
- * @param serializer
- * @param queryEngine
- * @param v
- * @param obj
- * @param loader
- * @return
- * @throws IllegalAccessException
- * @throws IllegalArgumentException
- * @throws InvocationTargetException
- * @throws SecurityException
- * @throws InstantiationException
- * @throws NoSuchMethodException
- * @throws UnsupportedEncodingException
- * @throws AAIException
- * @throws URISyntaxException
- */
- private HashMap<String, Introspector> getRelatedObjects(DBSerializer serializer, QueryEngine queryEngine, Vertex v, Introspector obj, Loader loader) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException, InstantiationException, NoSuchMethodException, UnsupportedEncodingException, AAIException, URISyntaxException {
-
- HashMap<String, Introspector> relatedVertices = new HashMap<>();
- VertexProperty aaiUriProperty = v.property(AAIProperties.AAI_URI);
-
- if (!aaiUriProperty.isPresent()) {
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug("For the given vertex {}, it seems aai-uri is not present so not getting related objects", v.id().toString());
- } else {
- LOGGER.info("It seems aai-uri is not present in vertex, so not getting related objects, for more info enable debug log");
- }
- return relatedVertices;
- }
-
- String aaiUri = aaiUriProperty.value().toString();
-
- if (!obj.isTopLevel()) {
- String[] uriList = convertIntrospectorToUriList(aaiUri, obj, loader);
- List<Vertex> vertexChain = null;
- // If the uriList is null then there is something wrong with converting the uri
- // into a list of aai-uris so falling back to the old mechanism for finding parents
- if (uriList == null) {
- LOGGER.info("Falling back to the old mechanism due to unable to convert aai-uri to list of uris but this is not optimal");
- vertexChain = queryEngine.findParents(v);
- } else {
- vertexChain = queryEngine.findParents(uriList);
- }
- for (Vertex vertex : vertexChain) {
- try {
- final Introspector vertexObj = serializer.getVertexProperties(vertex);
- relatedVertices.put(vertexObj.getObjectId(), vertexObj);
- } catch (AAIUnknownObjectException e) {
- LOGGER.warn("Unable to get vertex properties, partial list of related vertices returned");
- }
- }
- } else {
- try {
- final Introspector vertexObj = serializer.getVertexProperties(v);
- relatedVertices.put(vertexObj.getObjectId(), vertexObj);
- } catch (AAIUnknownObjectException e) {
- LOGGER.warn("Unable to get vertex properties, partial list of related vertices returned");
- }
- }
-
- return relatedVertices;
- }
-
- private Map<Vertex, Introspector> buildIntrospectorObjects(DBSerializer serializer, Iterable<Vertex> vertices) {
- Map<Vertex, Introspector> deleteObjectMap = new HashMap<>();
- for (Vertex vertex : vertices) {
- try {
- // deleteObjectMap.computeIfAbsent(vertex, s ->
- // serializer.getLatestVersionView(vertex));
- Introspector deleteObj = serializer.getLatestVersionView(vertex);
- deleteObjectMap.put(vertex, deleteObj);
- } catch (UnsupportedEncodingException | AAIException e) {
- LOGGER.warn("Unable to get Introspctor Objects, Just continue");
- continue;
- }
-
- }
-
- return deleteObjectMap;
-
- }
-
- private Map<String, URI> buildURIMap(DBSerializer serializer, Map<Vertex, Introspector> introSpector) {
- Map<String, URI> uriMap = new HashMap<>();
- for (Map.Entry<Vertex, Introspector> entry : introSpector.entrySet()) {
- URI uri;
- try {
- uri = serializer.getURIForVertex(entry.getKey());
- if (null != entry.getValue()) {
- uriMap.put(entry.getValue().getObjectId(), uri);
- }
- } catch (UnsupportedEncodingException e) {
- LOGGER.warn("Unable to get URIs, Just continue");
- continue;
- }
-
- }
-
- return uriMap;
-
- }
-
- private Map<String, HashMap<String, Introspector>> buildRelatedObjects(DBSerializer serializer,
- QueryEngine queryEngine, Map<Vertex, Introspector> introSpector) {
-
- Map<String, HashMap<String, Introspector>> relatedObjectsMap = new HashMap<>();
- for (Map.Entry<Vertex, Introspector> entry : introSpector.entrySet()) {
- try {
- HashMap<String, Introspector> relatedObjects = this.getRelatedObjects(serializer, queryEngine,
- entry.getKey(), entry.getValue(), this.loader);
- if (null != entry.getValue()) {
- relatedObjectsMap.put(entry.getValue().getObjectId(), relatedObjects);
- }
- } catch (IllegalAccessException | IllegalArgumentException
- | InvocationTargetException | SecurityException | InstantiationException | NoSuchMethodException
- | UnsupportedEncodingException | AAIException | URISyntaxException e) {
- LOGGER.warn("Unable to get realted Objects, Just continue");
- continue;
- }
-
- }
-
- return relatedObjectsMap;
-
- }
-
- private void buildNotificationEvent(String sourceOfTruth, Status status, String transactionId,
- UEBNotification notification, Map<Vertex, Introspector> deleteObjects, Map<String, URI> uriMap,
- Map<String, HashMap<String, Introspector>> deleteRelatedObjects, String basePath) {
- for (Map.Entry<Vertex, Introspector> entry : deleteObjects.entrySet()) {
- try {
- String vertexObjectId = "";
-
- if (null != entry.getValue()) {
- vertexObjectId = entry.getValue().getObjectId();
-
- if (uriMap.containsKey(vertexObjectId) && deleteRelatedObjects.containsKey(vertexObjectId)) {
- notification.createNotificationEvent(transactionId, sourceOfTruth, status,
- uriMap.get(vertexObjectId), entry.getValue(), deleteRelatedObjects.get(vertexObjectId), basePath);
- }
- }
- } catch (UnsupportedEncodingException | AAIException e) {
-
- LOGGER.warn("Error in sending notification");
- }
- }
- }
-
- public void setPaginationParameters(String resultIndex, String resultSize) {
- if (resultIndex != null && resultIndex != "-1" && resultSize != null && resultSize != "-1") {
- this.setPaginationIndex(Integer.parseInt(resultIndex));
- this.setPaginationBucket(Integer.parseInt(resultSize));
- }
- }
-
- public List<Object> getPaginatedVertexList(List<Object> vertexList) throws AAIException {
- List<Object> vertices;
- if (this.isPaginated()) {
- this.setTotalsForPaging(vertexList.size(), this.getPaginationBucket());
- int startIndex = (this.getPaginationIndex() - 1) * this.getPaginationBucket();
- int endIndex = Math.min((this.getPaginationBucket() * this.getPaginationIndex()), vertexList.size());
- if (startIndex > endIndex) {
- throw new AAIException("AAI_6150", " ResultIndex is not appropriate for the result set, Needs to be <= " + endIndex);
- }
- vertices = vertexList.subList(startIndex, endIndex);
- } else {
- vertices = vertexList;
- }
- return vertices;
- }
+ private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(HttpEntry.class);
+ private static final String TARGET_ENTITY = "DB";
+
+ private ModelType introspectorFactoryType;
+
+ private QueryStyle queryStyle;
+
+ private SchemaVersion version;
+
+ private Loader loader;
+
+ private TransactionalGraphEngine dbEngine;
+
+ private boolean processSingle = true;
+
+ private int paginationBucket = -1;
+ private int paginationIndex = -1;
+ private int totalVertices = 0;
+ private int totalPaginationBuckets = 0;
+
+ @Autowired
+ private NodeIngestor nodeIngestor;
+
+ @Autowired
+ private LoaderFactory loaderFactory;
+
+ @Autowired
+ private SchemaVersions schemaVersions;
+
+ @Value("${schema.uri.base.path}")
+ private String basePath;
+
+ private UEBNotification notification;
+
+ /**
+ * Instantiates a new http entry.
+ *
+ * @param modelType the model type
+ * @param queryStyle the query style
+ */
+ public HttpEntry(ModelType modelType, QueryStyle queryStyle) {
+ this.introspectorFactoryType = modelType;
+ this.queryStyle = queryStyle;
+ }
+
+ public HttpEntry setHttpEntryProperties(SchemaVersion version, DBConnectionType connectionType) {
+ this.version = version;
+ this.loader = loaderFactory.createLoaderForVersion(introspectorFactoryType, version);
+ this.dbEngine = new JanusGraphDBEngine(queryStyle, connectionType, loader);
+
+ getDbEngine().startTransaction();
+ this.notification = new UEBNotification(loader, loaderFactory, schemaVersions);
+ return this;
+ }
+
+ public HttpEntry setHttpEntryProperties(SchemaVersion version, DBConnectionType connectionType,
+ UEBNotification notification) {
+ this.version = version;
+ this.loader = loaderFactory.createLoaderForVersion(introspectorFactoryType, version);
+ this.dbEngine = new JanusGraphDBEngine(queryStyle, connectionType, loader);
+
+ this.notification = notification;
+ // start transaction on creation
+ getDbEngine().startTransaction();
+ return this;
+ }
+
+ /**
+ * Gets the introspector factory type.
+ *
+ * @return the introspector factory type
+ */
+ public ModelType getIntrospectorFactoryType() {
+ return introspectorFactoryType;
+ }
+
+ /**
+ * Gets the query style.
+ *
+ * @return the query style
+ */
+ public QueryStyle getQueryStyle() {
+ return queryStyle;
+ }
+
+ /**
+ * Gets the version.
+ *
+ * @return the version
+ */
+ public SchemaVersion getVersion() {
+ return version;
+ }
+
+ /**
+ * Gets the loader.
+ *
+ * @return the loader
+ */
+ public Loader getLoader() {
+ return loader;
+ }
+
+ /**
+ * Gets the db engine.
+ *
+ * @return the db engine
+ */
+ public TransactionalGraphEngine getDbEngine() {
+ return dbEngine;
+ }
+
+ public Pair<Boolean, List<Pair<URI, Response>>> process(List<DBRequest> requests, String sourceOfTruth)
+ throws AAIException {
+ return this.process(requests, sourceOfTruth, true);
+ }
+
+ /**
+ * Checks the pagination bucket and pagination index variables to determine whether or not the user
+ * requested paginated results
+ *
+ * @return a boolean true/false of whether the user requested paginated results
+ */
+ public boolean isPaginated() {
+ return this.paginationBucket > -1 && this.paginationIndex > -1;
+ }
+
+ /**
+ * Returns the pagination size
+ *
+ * @return integer of the size of results to be returned when paginated
+ */
+ public int getPaginationBucket() {
+ return this.paginationBucket;
+ }
+
+ /**
+ * Setter for the pagination bucket variable which stores in this object the size of results to return
+ *
+ * @param pb
+ */
+ public void setPaginationBucket(int pb) {
+ this.paginationBucket = pb;
+ }
+
+ /**
+ * Getter to return the pagination index requested by the user when requesting paginated results
+ *
+ * @return
+ */
+ public int getPaginationIndex() {
+ return this.paginationIndex;
+ }
+
+ /**
+ * Sets the pagination index that was passed in by the user, to determine which index or results to retrieve when
+ * paginated
+ *
+ * @param pi
+ */
+ public void setPaginationIndex(int pi) {
+ if (pi == 0) {
+ pi = 1;
+ }
+ this.paginationIndex = pi;
+ }
+
+ /**
+ * Sets the total vertices variables and calculates the amount of pages based on size and total vertices
+ *
+ * @param totalVertices
+ * @param paginationBucketSize
+ */
+ public void setTotalsForPaging(int totalVertices, int paginationBucketSize) {
+ this.totalVertices = totalVertices;
+ // set total number of buckets equal to full pages
+ this.totalPaginationBuckets = totalVertices / paginationBucketSize;
+ // conditionally add a page for the remainder
+ if (totalVertices % paginationBucketSize > 0) {
+ this.totalPaginationBuckets++;
+ }
+ }
+
+ /**
+ * @return the total amount of pages
+ */
+ public int getTotalPaginationBuckets() {
+ return this.totalPaginationBuckets;
+ }
+
+ /**
+ *
+ * @return the total number of vertices when paginated
+ */
+ public int getTotalVertices() {
+ return this.totalVertices;
+ }
+
+ /**
+ * Process.
+ *
+ * @param requests the requests
+ * @param sourceOfTruth the source of truth
+ *
+ * @return the pair
+ * @throws AAIException the AAI exception
+ */
+ public Pair<Boolean, List<Pair<URI, Response>>> process(List<DBRequest> requests, String sourceOfTruth,
+ boolean enableResourceVersion) throws AAIException {
+
+ DBSerializer serializer = new DBSerializer(version, dbEngine, introspectorFactoryType, sourceOfTruth);
+ String methodName = "process";
+ Response response;
+ Introspector obj = null;
+ QueryParser query = null;
+ URI uri = null;
+ String transactionId = null;
+ int depth = AAIProperties.MAXIMUM_DEPTH;
+ Format format = null;
+ List<Pair<URI, Response>> responses = new ArrayList<>();
+ MultivaluedMap<String, String> params = null;
+ HttpMethod method = null;
+ String uriTemp = "";
+ Boolean success = true;
+ QueryEngine queryEngine = dbEngine.getQueryEngine();
+ int maxRetries = 10;
+ int retry = 0;
+
+ LoggingContext.save();
+ for (DBRequest request : requests) {
+ response = null;
+ Status status = Status.NOT_FOUND;
+ method = request.getMethod();
+ try {
+ for (retry = 0; retry < maxRetries; ++retry) {
+ try {
+
+ LoggingContext.targetEntity(TARGET_ENTITY);
+ LoggingContext.targetServiceName(methodName + " " + method);
+
+ obj = request.getIntrospector();
+ query = request.getParser();
+ transactionId = request.getTransactionId();
+ uriTemp = request.getUri().getRawPath().replaceFirst("^v\\d+/", "");
+ uri = UriBuilder.fromPath(uriTemp).build();
+ LoggingContext.startTime();
+ List<Vertex> vertTemp;
+ List<Vertex> vertices;
+ if (this.isPaginated()) {
+ vertTemp = query.getQueryBuilder().toList();
+ this.setTotalsForPaging(vertTemp.size(), this.paginationBucket);
+ vertices = vertTemp.subList(((this.paginationIndex - 1) * this.paginationBucket),
+ Math.min((this.paginationBucket * this.paginationIndex), vertTemp.size()));
+ } else {
+ vertices = query.getQueryBuilder().toList();
+ }
+ boolean isNewVertex = false;
+ String outputMediaType = getMediaType(request.getHeaders().getAcceptableMediaTypes());
+ String result = null;
+ params = request.getInfo().getQueryParameters(false);
+ depth = setDepth(obj, params.getFirst("depth"));
+ if (params.containsKey("format")) {
+ format = Format.getFormat(params.getFirst("format"));
+ }
+ String cleanUp = params.getFirst("cleanup");
+ String requestContext = "";
+ List<String> requestContextList = request.getHeaders().getRequestHeader("aai-request-context");
+ if (requestContextList != null) {
+ requestContext = requestContextList.get(0);
+ }
+
+ if (cleanUp == null) {
+ cleanUp = "false";
+ }
+ if (vertices.size() > 1 && processSingle
+ && !(method.equals(HttpMethod.GET) || method.equals(HttpMethod.GET_RELATIONSHIP))) {
+ if (method.equals(HttpMethod.DELETE)) {
+ LoggingContext.restoreIfPossible();
+ throw new AAIException("AAI_6138");
+ } else {
+ LoggingContext.restoreIfPossible();
+ throw new AAIException("AAI_6137");
+ }
+ }
+ if (method.equals(HttpMethod.PUT)) {
+ String resourceVersion = (String) obj.getValue("resource-version");
+ if (vertices.isEmpty()) {
+ if (enableResourceVersion) {
+ serializer.verifyResourceVersion("create", query.getResultType(), "",
+ resourceVersion, obj.getURI());
+ }
+ isNewVertex = true;
+ } else {
+ if (enableResourceVersion) {
+ serializer.verifyResourceVersion("update", query.getResultType(),
+ vertices.get(0).<String>property("resource-version").orElse(null),
+ resourceVersion, obj.getURI());
+ }
+ isNewVertex = false;
+ }
+ } else {
+ if (vertices.isEmpty()) {
+ String msg = createNotFoundMessage(query.getResultType(), request.getUri());
+ throw new AAIException("AAI_6114", msg);
+ } else {
+ isNewVertex = false;
+ }
+ }
+ Vertex v = null;
+ if (!isNewVertex) {
+ v = vertices.get(0);
+ }
+ HashMap<String, Introspector> relatedObjects = new HashMap<>();
+ String nodeOnly = params.getFirst("nodes-only");
+ boolean isNodeOnly = nodeOnly != null;
+ switch (method) {
+ case GET:
+
+ if (format == null) {
+ obj = this.getObjectFromDb(vertices, serializer, query, obj, request.getUri(),
+ depth, isNodeOnly, cleanUp);
+
+ LoggingContext.elapsedTime((long) serializer.getDBTimeMsecs(),
+ TimeUnit.MILLISECONDS);
+ LOGGER.info("Completed");
+ LoggingContext.restoreIfPossible();
+
+ if (obj != null) {
+ status = Status.OK;
+ MarshallerProperties properties;
+ if (!request.getMarshallerProperties().isPresent()) {
+ properties = new MarshallerProperties.Builder(
+ org.onap.aai.restcore.MediaType.getEnum(outputMediaType)).build();
+ } else {
+ properties = request.getMarshallerProperties().get();
+ }
+ result = obj.marshal(properties);
+ }
+ } else {
+ FormatFactory ff =
+ new FormatFactory(loader, serializer, schemaVersions, basePath + "/");
+ Formatter formatter = ff.get(format, params);
+ result = formatter.output(vertices.stream().map(vertex -> (Object) vertex)
+ .collect(Collectors.toList())).toString();
+ status = Status.OK;
+ }
+
+ break;
+ case GET_RELATIONSHIP:
+ if (format == null) {
+ obj = this.getRelationshipObjectFromDb(vertices, serializer, query,
+ request.getInfo().getRequestUri());
+
+ LoggingContext.elapsedTime((long) serializer.getDBTimeMsecs(),
+ TimeUnit.MILLISECONDS);
+ LOGGER.info("Completed");
+ LoggingContext.restoreIfPossible();
+
+ if (obj != null) {
+ status = Status.OK;
+ MarshallerProperties properties;
+ if (!request.getMarshallerProperties().isPresent()) {
+ properties = new MarshallerProperties.Builder(
+ org.onap.aai.restcore.MediaType.getEnum(outputMediaType)).build();
+ } else {
+ properties = request.getMarshallerProperties().get();
+ }
+ result = obj.marshal(properties);
+ } else {
+ String msg = createRelationshipNotFoundMessage(query.getResultType(),
+ request.getUri());
+ throw new AAIException("AAI_6149", msg);
+ }
+ } else {
+ FormatFactory ff =
+ new FormatFactory(loader, serializer, schemaVersions, basePath + "/");
+ Formatter formatter = ff.get(format, params);
+ result = formatter.output(vertices.stream().map(vertex -> (Object) vertex)
+ .collect(Collectors.toList())).toString();
+ status = Status.OK;
+ }
+ break;
+ case PUT:
+ response = this.invokeExtension(dbEngine, this.dbEngine.tx(), method, request,
+ sourceOfTruth, version, loader, obj, uri, true);
+ if (isNewVertex) {
+ v = serializer.createNewVertex(obj);
+ }
+ serializer.serializeToDb(obj, v, query, uri.getRawPath(), requestContext);
+ this.invokeExtension(dbEngine, this.dbEngine.tx(), HttpMethod.PUT, request,
+ sourceOfTruth, version, loader, obj, uri, false);
+ status = Status.OK;
+ if (isNewVertex) {
+ status = Status.CREATED;
+ }
+ obj = serializer.getLatestVersionView(v);
+ if (query.isDependent()) {
+ relatedObjects =
+ this.getRelatedObjects(serializer, queryEngine, v, obj, this.loader);
+ }
+ LoggingContext.elapsedTime(
+ (long) serializer.getDBTimeMsecs() + (long) queryEngine.getDBTimeMsecs(),
+ TimeUnit.MILLISECONDS);
+ LOGGER.info("Completed ");
+ LoggingContext.restoreIfPossible();
+ notification.createNotificationEvent(transactionId, sourceOfTruth, status, uri, obj,
+ relatedObjects, basePath);
+
+ break;
+ case PUT_EDGE:
+ serializer.touchStandardVertexProperties(v, false);
+ this.invokeExtension(dbEngine, this.dbEngine.tx(), method, request, sourceOfTruth,
+ version, loader, obj, uri, true);
+ serializer.createEdge(obj, v);
+
+ LoggingContext.elapsedTime((long) serializer.getDBTimeMsecs(), TimeUnit.MILLISECONDS);
+ LOGGER.info("Completed");
+ LoggingContext.restoreIfPossible();
+ status = Status.OK;
+ notification.createNotificationEvent(transactionId, sourceOfTruth, status,
+ new URI(uri.toString().replace("/relationship-list/relationship", "")),
+ serializer.getLatestVersionView(v), relatedObjects, basePath);
+ break;
+ case MERGE_PATCH:
+ Introspector existingObj = loader.introspectorFromName(obj.getDbName());
+ existingObj = this.getObjectFromDb(vertices, serializer, query, existingObj,
+ request.getUri(), 0, false, cleanUp);
+ String existingJson = existingObj.marshal(false);
+ String newJson;
+
+ if (request.getRawRequestContent().isPresent()) {
+ newJson = request.getRawRequestContent().get();
+ } else {
+ newJson = "";
+ }
+ Object relationshipList = request.getIntrospector().getValue("relationship-list");
+ ObjectMapper mapper = new ObjectMapper();
+ try {
+ JsonNode existingNode = mapper.readTree(existingJson);
+ JsonNode newNode = mapper.readTree(newJson);
+ JsonMergePatch patch = JsonMergePatch.fromJson(newNode);
+ JsonNode completed = patch.apply(existingNode);
+ String patched = mapper.writeValueAsString(completed);
+ Introspector patchedObj = loader.unmarshal(existingObj.getName(), patched);
+ if (relationshipList == null) {
+ // if the caller didn't touch the relationship-list, we shouldn't either
+ patchedObj.setValue("relationship-list", null);
+ }
+ serializer.serializeToDb(patchedObj, v, query, uri.getRawPath(), requestContext);
+ status = Status.OK;
+ patchedObj = serializer.getLatestVersionView(v);
+ if (query.isDependent()) {
+ relatedObjects = this.getRelatedObjects(serializer, queryEngine, v, patchedObj,
+ this.loader);
+ }
+ LoggingContext.elapsedTime(
+ (long) serializer.getDBTimeMsecs() + (long) queryEngine.getDBTimeMsecs(),
+ TimeUnit.MILLISECONDS);
+ LOGGER.info("Completed");
+ LoggingContext.restoreIfPossible();
+ notification.createNotificationEvent(transactionId, sourceOfTruth, status, uri,
+ patchedObj, relatedObjects, basePath);
+ } catch (IOException | JsonPatchException e) {
+
+ LOGGER.info("Caught exception: " + e.getMessage());
+ LoggingContext.restoreIfPossible();
+ throw new AAIException("AAI_3000", "could not perform patch operation");
+ }
+ break;
+ case DELETE:
+ String resourceVersion = params.getFirst("resource-version");
+ obj = serializer.getLatestVersionView(v);
+ if (query.isDependent()) {
+ relatedObjects =
+ this.getRelatedObjects(serializer, queryEngine, v, obj, this.loader);
+ }
+ /*
+ * Find all Delete-other-vertex vertices and create structure for notify
+ * findDeleatble also returns the startVertex v and we dont want to create
+ * duplicate notification events for the same
+ * So remove the startvertex first
+ */
+
+ List<Vertex> deletableVertices = dbEngine.getQueryEngine().findDeletable(v);
+ Long vId = (Long) v.id();
+
+ /*
+ * I am assuming vertexId cant be null
+ */
+ deletableVertices.removeIf(s -> vId.equals(s.id()));
+ boolean isDelVerticesPresent = !deletableVertices.isEmpty();
+ Map<Vertex, Introspector> deleteObjects = new HashMap<>();
+ Map<String, URI> uriMap = new HashMap<>();
+ Map<String, HashMap<String, Introspector>> deleteRelatedObjects = new HashMap<>();
+
+ if (isDelVerticesPresent) {
+ deleteObjects = this.buildIntrospectorObjects(serializer, deletableVertices);
+
+ uriMap = this.buildURIMap(serializer, deleteObjects);
+ deleteRelatedObjects =
+ this.buildRelatedObjects(serializer, queryEngine, deleteObjects);
+ }
+
+ this.invokeExtension(dbEngine, this.dbEngine.tx(), method, request, sourceOfTruth,
+ version, loader, obj, uri, true);
+ serializer.delete(v, deletableVertices, resourceVersion, enableResourceVersion);
+ this.invokeExtension(dbEngine, this.dbEngine.tx(), method, request, sourceOfTruth,
+ version, loader, obj, uri, false);
+
+ LoggingContext.elapsedTime(
+ (long) serializer.getDBTimeMsecs() + (long) queryEngine.getDBTimeMsecs(),
+ TimeUnit.MILLISECONDS);
+ LOGGER.info("Completed");
+ LoggingContext.restoreIfPossible();
+ status = Status.NO_CONTENT;
+ notification.createNotificationEvent(transactionId, sourceOfTruth, status, uri, obj,
+ relatedObjects, basePath);
+
+ /*
+ * Notify delete-other-v candidates
+ */
+
+ if (isDelVerticesPresent) {
+ this.buildNotificationEvent(sourceOfTruth, status, transactionId, notification,
+ deleteObjects, uriMap, deleteRelatedObjects, basePath);
+ }
+
+ break;
+ case DELETE_EDGE:
+ serializer.touchStandardVertexProperties(v, false);
+ serializer.deleteEdge(obj, v);
+
+ LoggingContext.elapsedTime((long) serializer.getDBTimeMsecs(), TimeUnit.MILLISECONDS);
+ LOGGER.info("Completed");
+ LoggingContext.restoreIfPossible();
+ status = Status.NO_CONTENT;
+ notification.createNotificationEvent(transactionId, sourceOfTruth, Status.OK,
+ new URI(uri.toString().replace("/relationship-list/relationship", "")),
+ serializer.getLatestVersionView(v), relatedObjects, basePath);
+ break;
+ default:
+ break;
+ }
+
+ /*
+ * temporarily adding vertex id to the headers
+ * to be able to use for testing the vertex id endpoint functionality
+ * since we presently have no other way of generating those id urls
+ */
+ if (response == null && v != null
+ && (method.equals(HttpMethod.PUT) || method.equals(HttpMethod.GET)
+ || method.equals(HttpMethod.MERGE_PATCH)
+ || method.equals(HttpMethod.GET_RELATIONSHIP))
+
+ ) {
+ String myvertid = v.id().toString();
+ if (this.isPaginated()) {
+ response = Response.status(status).header("vertex-id", myvertid)
+ .header("total-results", this.getTotalVertices())
+ .header("total-pages", this.getTotalPaginationBuckets()).entity(result)
+ .type(outputMediaType).build();
+ } else {
+ response = Response.status(status).header("vertex-id", myvertid).entity(result)
+ .type(outputMediaType).build();
+ }
+ } else if (response == null) {
+ response = Response.status(status).type(outputMediaType).build();
+ } else {
+ // response already set to something
+ }
+ Pair<URI, Response> pairedResp = Pair.with(request.getUri(), response);
+ responses.add(pairedResp);
+ // break out of retry loop
+ break;
+ } catch (JanusGraphException e) {
+ this.dbEngine.rollback();
+
+ LOGGER.info("Caught exception: " + e.getMessage());
+ LoggingContext.restoreIfPossible();
+ AAIException ex = new AAIException("AAI_6142", e);
+ ErrorLogHelper.logException(ex);
+ Thread.sleep((retry + 1) * 20L);
+ this.dbEngine.startTransaction();
+ queryEngine = dbEngine.getQueryEngine();
+ serializer = new DBSerializer(version, dbEngine, introspectorFactoryType, sourceOfTruth);
+ }
+ if (retry == maxRetries) {
+ throw new AAIException("AAI_6134");
+ }
+ }
+ } catch (AAIException e) {
+ success = false;
+ ArrayList<String> templateVars = new ArrayList<>();
+ templateVars.add(request.getMethod().toString()); // GET, PUT, etc
+ templateVars.add(request.getUri().getPath());
+ templateVars.addAll(e.getTemplateVars());
+ ErrorLogHelper.logException(e);
+ response = Response.status(e.getErrorObject().getHTTPResponseCode()).entity(ErrorLogHelper
+ .getRESTAPIErrorResponse(request.getHeaders().getAcceptableMediaTypes(), e, templateVars))
+ .build();
+ Pair<URI, Response> pairedResp = Pair.with(request.getUri(), response);
+ responses.add(pairedResp);
+ continue;
+ } catch (Exception e) {
+ success = false;
+ e.printStackTrace();
+ AAIException ex = new AAIException("AAI_4000", e);
+ ArrayList<String> templateVars = new ArrayList<String>();
+ templateVars.add(request.getMethod().toString()); // GET, PUT, etc
+ templateVars.add(request.getUri().getPath().toString());
+ ErrorLogHelper.logException(ex);
+ response = Response.status(ex.getErrorObject().getHTTPResponseCode()).entity(ErrorLogHelper
+ .getRESTAPIErrorResponse(request.getHeaders().getAcceptableMediaTypes(), ex, templateVars))
+ .build();
+ Pair<URI, Response> pairedResp = Pair.with(request.getUri(), response);
+ responses.add(pairedResp);
+ continue;
+ }
+ }
+ notification.triggerEvents();
+ return Pair.with(success, responses);
+ }
+
+ /**
+ * Gets the media type.
+ *
+ * @param mediaTypeList the media type list
+ * @return the media type
+ */
+ private String getMediaType(List<MediaType> mediaTypeList) {
+ String mediaType = MediaType.APPLICATION_JSON; // json is the default
+ for (MediaType mt : mediaTypeList) {
+ if (MediaType.APPLICATION_XML_TYPE.isCompatible(mt)) {
+ mediaType = MediaType.APPLICATION_XML;
+ }
+ }
+ return mediaType;
+ }
+
+ /**
+ * Gets the object from db.
+ *
+ * @param serializer the serializer
+ * @param query the query
+ * @param obj the obj
+ * @param uri the uri
+ * @param depth the depth
+ * @param cleanUp the clean up
+ * @return the object from db
+ * @throws AAIException the AAI exception
+ * @throws IllegalAccessException the illegal access exception
+ * @throws IllegalArgumentException the illegal argument exception
+ * @throws InvocationTargetException the invocation target exception
+ * @throws SecurityException the security exception
+ * @throws InstantiationException the instantiation exception
+ * @throws NoSuchMethodException the no such method exception
+ * @throws UnsupportedEncodingException the unsupported encoding exception
+ * @throws MalformedURLException the malformed URL exception
+ * @throws AAIUnknownObjectException
+ * @throws URISyntaxException
+ */
+ private Introspector getObjectFromDb(List<Vertex> results, DBSerializer serializer, QueryParser query,
+ Introspector obj, URI uri, int depth, boolean nodeOnly, String cleanUp)
+ throws AAIException, IllegalAccessException, IllegalArgumentException, InvocationTargetException,
+ SecurityException, InstantiationException, NoSuchMethodException, UnsupportedEncodingException,
+ AAIUnknownObjectException, URISyntaxException {
+
+ // nothing found
+ if (results.isEmpty()) {
+ String msg = createNotFoundMessage(query.getResultType(), uri);
+ throw new AAIException("AAI_6114", msg);
+ }
+
+ return serializer.dbToObject(results, obj, depth, nodeOnly, cleanUp);
+
+ }
+
+ /**
+ * Gets the object from db.
+ *
+ * @param serializer the serializer
+ * @param query the query
+ * @param obj the obj
+ * @param uri the uri
+ * @param depth the depth
+ * @param cleanUp the clean up
+ * @return the object from db
+ * @throws AAIException the AAI exception
+ * @throws IllegalAccessException the illegal access exception
+ * @throws IllegalArgumentException the illegal argument exception
+ * @throws InvocationTargetException the invocation target exception
+ * @throws SecurityException the security exception
+ * @throws InstantiationException the instantiation exception
+ * @throws NoSuchMethodException the no such method exception
+ * @throws UnsupportedEncodingException the unsupported encoding exception
+ * @throws MalformedURLException the malformed URL exception
+ * @throws AAIUnknownObjectException
+ * @throws URISyntaxException
+ */
+ private Introspector getRelationshipObjectFromDb(List<Vertex> results, DBSerializer serializer, QueryParser query,
+ URI uri) throws AAIException, IllegalArgumentException, SecurityException, UnsupportedEncodingException,
+ AAIUnknownObjectException {
+
+ // nothing found
+ if (results.isEmpty()) {
+ String msg = createNotFoundMessage(query.getResultType(), uri);
+ throw new AAIException("AAI_6114", msg);
+ }
+
+ if (results.size() > 1) {
+ throw new AAIException("AAI_6148", uri.getPath());
+ }
+
+ Vertex v = results.get(0);
+ return serializer.dbToRelationshipObject(v);
+ }
+
+ /**
+ * Invoke extension.
+ *
+ * @param dbEngine the db engine
+ * @param g the g
+ * @param httpMethod the http method
+ * @param fromAppId the from app id
+ * @param apiVersion the api version
+ * @param loader the loader
+ * @param obj the obj
+ * @param uri the uri
+ * @param isPreprocess the is preprocess
+ * @return the response
+ * @throws IllegalArgumentException the illegal argument exception
+ * @throws UnsupportedEncodingException the unsupported encoding exception
+ * @throws AAIException the AAI exception
+ */
+ private Response invokeExtension(TransactionalGraphEngine dbEngine, Graph g, HttpMethod httpMethod,
+ DBRequest request, String fromAppId, SchemaVersion apiVersion, Loader loader, Introspector obj, URI uri,
+ boolean isPreprocess) throws IllegalArgumentException, UnsupportedEncodingException, AAIException {
+ AAIExtensionMap aaiExtMap = new AAIExtensionMap();
+ // ModelInjestor injestor = ModelInjestor.getInstance();
+ Response response = null;
+ URIToExtensionInformation extensionInformation = new URIToExtensionInformation(loader, uri);
+ aaiExtMap.setHttpEntry(this);
+ aaiExtMap.setDbRequest(request);
+ aaiExtMap.setTransId(request.getTransactionId());
+ aaiExtMap.setFromAppId(fromAppId);
+ aaiExtMap.setGraph(g);
+ aaiExtMap.setApiVersion(apiVersion.toString());
+ aaiExtMap.setObjectFromRequest(obj);
+ aaiExtMap.setObjectFromRequestType(obj.getJavaClassName());
+ aaiExtMap.setObjectFromResponse(obj);
+ aaiExtMap.setObjectFromResponseType(obj.getJavaClassName());
+ aaiExtMap.setJaxbContext(nodeIngestor.getContextForVersion(apiVersion));
+ aaiExtMap.setUri(uri.getRawPath());
+ aaiExtMap.setTransactionalGraphEngine(dbEngine);
+ aaiExtMap.setLoader(loader);
+ aaiExtMap.setNamespace(extensionInformation.getNamespace());
+
+ ExtensionController ext = new ExtensionController();
+ ext.runExtension(aaiExtMap.getApiVersion(), extensionInformation.getNamespace(),
+ extensionInformation.getTopObject(), extensionInformation.getMethodName(httpMethod, isPreprocess),
+ aaiExtMap, isPreprocess);
+
+ if (aaiExtMap.getPrecheckAddedList().size() > 0) {
+ response = notifyOnSkeletonCreation(aaiExtMap, obj, request.getHeaders());
+ }
+
+ return response;
+ }
+
+ /**
+ * Notify on skeleton creation.
+ *
+ * @param aaiExtMap the aai ext map
+ * @param input the input
+ * @param headers the headers
+ * @return the response
+ */
+ // Legacy support
+ private Response notifyOnSkeletonCreation(AAIExtensionMap aaiExtMap, Introspector input, HttpHeaders headers) {
+ Response response = null;
+ HashMap<AAIException, ArrayList<String>> exceptionList = new HashMap<AAIException, ArrayList<String>>();
+
+ StringBuilder keyString = new StringBuilder();
+
+ Set<String> resourceKeys = input.getKeys();
+ for (String key : resourceKeys) {
+ keyString.append(key).append("=").append(input.getValue(key).toString()).append(" ");
+ }
+
+ for (AAIResponseMessage msg : aaiExtMap.getPrecheckResponseMessages().getAAIResponseMessage()) {
+ ArrayList<String> templateVars = new ArrayList<>();
+
+ templateVars.add("PUT " + input.getDbName());
+ templateVars.add(keyString.toString());
+ List<String> keys = new ArrayList<>();
+ templateVars.add(msg.getAaiResponseMessageResourceType());
+ for (AAIResponseMessageDatum dat : msg.getAaiResponseMessageData().getAAIResponseMessageDatum()) {
+ keys.add(dat.getAaiResponseMessageDatumKey() + "=" + dat.getAaiResponseMessageDatumValue());
+ }
+ templateVars.add(StringUtils.join(keys, ", "));
+ exceptionList.put(new AAIException("AAI_0004", msg.getAaiResponseMessageResourceType()), templateVars);
+ }
+ response = Response.status(Status.ACCEPTED)
+ .entity(ErrorLogHelper.getRESTAPIInfoResponse(headers.getAcceptableMediaTypes(), exceptionList))
+ .build();
+
+ return response;
+ }
+
+ /**
+ * Creates the not found message.
+ *
+ * @param resultType the result type
+ * @param uri the uri
+ * @return the string
+ */
+ private String createNotFoundMessage(String resultType, URI uri) {
+
+ String msg = "No Node of type " + resultType + " found at: " + uri.getPath();
+
+ return msg;
+ }
+
+ /**
+ * Creates the not found message.
+ *
+ * @param resultType the result type
+ * @param uri the uri
+ * @return the string
+ */
+ private String createRelationshipNotFoundMessage(String resultType, URI uri) {
+
+ String msg = "No relationship found of type " + resultType + " at the given URI: " + uri.getPath()
+ + "/relationship-list";
+
+ return msg;
+ }
+
+ /**
+ * Sets the depth.
+ *
+ * @param depthParam the depth param
+ * @return the int
+ * @throws AAIException the AAI exception
+ */
+ protected int setDepth(Introspector obj, String depthParam) throws AAIException {
+ int depth = AAIProperties.MAXIMUM_DEPTH;
+
+ String getAllRandomStr = AAIConfig.get("aai.rest.getall.depthparam", "");
+ if (depthParam != null && getAllRandomStr != null && !getAllRandomStr.isEmpty()
+ && getAllRandomStr.equals(depthParam)) {
+ return depth;
+ }
+
+ if (depthParam == null) {
+ if (this.version.compareTo(schemaVersions.getDepthVersion()) >= 0) {
+ depth = 0;
+ } else {
+ depth = AAIProperties.MAXIMUM_DEPTH;
+ }
+ } else {
+ if (!depthParam.isEmpty() && !"all".equals(depthParam)) {
+ try {
+ depth = Integer.parseInt(depthParam);
+ } catch (Exception e) {
+ throw new AAIException("AAI_4016");
+ }
+
+ }
+ }
+ String maxDepth = obj.getMetadata(ObjectMetadata.MAXIMUM_DEPTH);
+
+ int maximumDepth = AAIProperties.MAXIMUM_DEPTH;
+
+ if (maxDepth != null) {
+ try {
+ maximumDepth = Integer.parseInt(maxDepth);
+ } catch (Exception ex) {
+ throw new AAIException("AAI_4018");
+ }
+ }
+
+ if (depth > maximumDepth) {
+ throw new AAIException("AAI_3303");
+ }
+
+ return depth;
+ }
+
+ /**
+ * Checks if is modification method.
+ *
+ * @param method the method
+ * @return true, if is modification method
+ */
+ private boolean isModificationMethod(HttpMethod method) {
+ boolean result = false;
+
+ if (method.equals(HttpMethod.PUT) || method.equals(HttpMethod.PUT_EDGE) || method.equals(HttpMethod.DELETE_EDGE)
+ || method.equals(HttpMethod.MERGE_PATCH)) {
+ result = true;
+ }
+
+ return result;
+
+ }
+
+ /**
+ * Given an uri, introspector object and loader object
+ * it will check if the obj is top level object if it is,
+ * it will return immediately returning the uri passed in
+ * If it isn't, it will go through, get the uriTemplate
+ * from the introspector object and get the count of "/"s
+ * and remove that part of the uri using substring
+ * and keep doing that until the current object is top level
+ * Also added the max depth just so worst case scenario
+ * Then keep adding aai-uri to the list include the aai-uri passed in
+ * Convert that list into an array and return it
+ * <p>
+ *
+ * Example:
+ *
+ * <blockquote>
+ * aai-uri ->
+ * /cloud-infrastructure/cloud-regions/cloud-region/cloud-owner/cloud-region-id/tenants/tenant/tenant1/vservers/vserver/v1
+ *
+ * Given the uriTemplate vserver -> /vservers/vserver/{vserver-id}
+ * it converts to /vservers/vserver
+ *
+ * lastIndexOf /vservers/vserver in
+ * /cloud-infrastructure/cloud-regions/cloud-region/cloud-owner/cloud-region-id/tenants/tenant/tenant1/vservers/vserver/v1
+ * ^
+ * |
+ * |
+ * lastIndexOf
+ * Use substring to get the string from 0 to that lastIndexOf
+ * aai-uri -> /cloud-infrastructure/cloud-regions/cloud-region/cloud-owner/cloud-region-id/tenants/tenant/tenant1
+ *
+ * From this new aai-uri, generate a introspector from the URITOObject class
+ * and keep doing this until you
+ *
+ * </blockquote>
+ *
+ * @param aaiUri - aai-uri of the vertex representating the unique id of a given vertex
+ * @param obj - introspector object of the given starting vertex
+ * @param loader - Type of loader which will always be MoxyLoader to support model driven
+ * @return an array of strings which can be used to get the vertexes of parent and grand parents from a given vertex
+ * @throws UnsupportedEncodingException
+ * @throws AAIException
+ */
+ String[] convertIntrospectorToUriList(String aaiUri, Introspector obj, Loader loader)
+ throws UnsupportedEncodingException, AAIException {
+
+ List<String> uriList = new ArrayList<>();
+ String template = StringUtils.EMPTY;
+ String truncatedUri = aaiUri;
+ int depth = AAIProperties.MAXIMUM_DEPTH;
+ uriList.add(truncatedUri);
+
+ while (depth >= 0 && !obj.isTopLevel()) {
+ template = obj.getMetadata(ObjectMetadata.URI_TEMPLATE);
+
+ if (template == null) {
+ LOGGER.warn("Unable to find the uriTemplate for the object {}", obj.getDbName());
+ return null;
+ }
+
+ int templateCount = StringUtils.countMatches(template, "/");
+ int truncatedUriCount = StringUtils.countMatches(truncatedUri, "/");
+
+ if (templateCount > truncatedUriCount) {
+ LOGGER.warn("Template uri {} contains more slashes than truncatedUri {}", template, truncatedUri);
+ return null;
+ }
+
+ int cutIndex = StringUtils.ordinalIndexOf(truncatedUri, "/", truncatedUriCount - templateCount + 1);
+ truncatedUri = StringUtils.substring(truncatedUri, 0, cutIndex);
+ uriList.add(truncatedUri);
+ obj = new URIToObject(loader, UriBuilder.fromPath(truncatedUri).build()).getEntity();
+ depth--;
+ }
+
+ return uriList.toArray(new String[uriList.size()]);
+ }
+
+ /**
+ *
+ * @param serializer
+ * @param queryEngine
+ * @param v
+ * @param obj
+ * @param loader
+ * @return
+ * @throws IllegalAccessException
+ * @throws IllegalArgumentException
+ * @throws InvocationTargetException
+ * @throws SecurityException
+ * @throws InstantiationException
+ * @throws NoSuchMethodException
+ * @throws UnsupportedEncodingException
+ * @throws AAIException
+ * @throws URISyntaxException
+ */
+ private HashMap<String, Introspector> getRelatedObjects(DBSerializer serializer, QueryEngine queryEngine, Vertex v,
+ Introspector obj, Loader loader) throws IllegalAccessException, IllegalArgumentException,
+ InvocationTargetException, SecurityException, InstantiationException, NoSuchMethodException,
+ UnsupportedEncodingException, AAIException, URISyntaxException {
+
+ HashMap<String, Introspector> relatedVertices = new HashMap<>();
+ VertexProperty aaiUriProperty = v.property(AAIProperties.AAI_URI);
+
+ if (!aaiUriProperty.isPresent()) {
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug("For the given vertex {}, it seems aai-uri is not present so not getting related objects",
+ v.id().toString());
+ } else {
+ LOGGER.info(
+ "It seems aai-uri is not present in vertex, so not getting related objects, for more info enable debug log");
+ }
+ return relatedVertices;
+ }
+
+ String aaiUri = aaiUriProperty.value().toString();
+
+ if (!obj.isTopLevel()) {
+ String[] uriList = convertIntrospectorToUriList(aaiUri, obj, loader);
+ List<Vertex> vertexChain = null;
+ // If the uriList is null then there is something wrong with converting the uri
+ // into a list of aai-uris so falling back to the old mechanism for finding parents
+ if (uriList == null) {
+ LOGGER.info(
+ "Falling back to the old mechanism due to unable to convert aai-uri to list of uris but this is not optimal");
+ vertexChain = queryEngine.findParents(v);
+ } else {
+ vertexChain = queryEngine.findParents(uriList);
+ }
+ for (Vertex vertex : vertexChain) {
+ try {
+ final Introspector vertexObj = serializer.getVertexProperties(vertex);
+ relatedVertices.put(vertexObj.getObjectId(), vertexObj);
+ } catch (AAIUnknownObjectException e) {
+ LOGGER.warn("Unable to get vertex properties, partial list of related vertices returned");
+ }
+ }
+ } else {
+ try {
+ final Introspector vertexObj = serializer.getVertexProperties(v);
+ relatedVertices.put(vertexObj.getObjectId(), vertexObj);
+ } catch (AAIUnknownObjectException e) {
+ LOGGER.warn("Unable to get vertex properties, partial list of related vertices returned");
+ }
+ }
+
+ return relatedVertices;
+ }
+
+ private Map<Vertex, Introspector> buildIntrospectorObjects(DBSerializer serializer, Iterable<Vertex> vertices) {
+ Map<Vertex, Introspector> deleteObjectMap = new HashMap<>();
+ for (Vertex vertex : vertices) {
+ try {
+ // deleteObjectMap.computeIfAbsent(vertex, s ->
+ // serializer.getLatestVersionView(vertex));
+ Introspector deleteObj = serializer.getLatestVersionView(vertex);
+ deleteObjectMap.put(vertex, deleteObj);
+ } catch (UnsupportedEncodingException | AAIException e) {
+ LOGGER.warn("Unable to get Introspctor Objects, Just continue");
+ continue;
+ }
+
+ }
+
+ return deleteObjectMap;
+
+ }
+
+ private Map<String, URI> buildURIMap(DBSerializer serializer, Map<Vertex, Introspector> introSpector) {
+ Map<String, URI> uriMap = new HashMap<>();
+ for (Map.Entry<Vertex, Introspector> entry : introSpector.entrySet()) {
+ URI uri;
+ try {
+ uri = serializer.getURIForVertex(entry.getKey());
+ if (null != entry.getValue()) {
+ uriMap.put(entry.getValue().getObjectId(), uri);
+ }
+ } catch (UnsupportedEncodingException e) {
+ LOGGER.warn("Unable to get URIs, Just continue");
+ continue;
+ }
+
+ }
+
+ return uriMap;
+
+ }
+
+ private Map<String, HashMap<String, Introspector>> buildRelatedObjects(DBSerializer serializer,
+ QueryEngine queryEngine, Map<Vertex, Introspector> introSpector) {
+
+ Map<String, HashMap<String, Introspector>> relatedObjectsMap = new HashMap<>();
+ for (Map.Entry<Vertex, Introspector> entry : introSpector.entrySet()) {
+ try {
+ HashMap<String, Introspector> relatedObjects =
+ this.getRelatedObjects(serializer, queryEngine, entry.getKey(), entry.getValue(), this.loader);
+ if (null != entry.getValue()) {
+ relatedObjectsMap.put(entry.getValue().getObjectId(), relatedObjects);
+ }
+ } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | SecurityException
+ | InstantiationException | NoSuchMethodException | UnsupportedEncodingException | AAIException
+ | URISyntaxException e) {
+ LOGGER.warn("Unable to get realted Objects, Just continue");
+ continue;
+ }
+
+ }
+
+ return relatedObjectsMap;
+
+ }
+
+ private void buildNotificationEvent(String sourceOfTruth, Status status, String transactionId,
+ UEBNotification notification, Map<Vertex, Introspector> deleteObjects, Map<String, URI> uriMap,
+ Map<String, HashMap<String, Introspector>> deleteRelatedObjects, String basePath) {
+ for (Map.Entry<Vertex, Introspector> entry : deleteObjects.entrySet()) {
+ try {
+ String vertexObjectId = "";
+
+ if (null != entry.getValue()) {
+ vertexObjectId = entry.getValue().getObjectId();
+
+ if (uriMap.containsKey(vertexObjectId) && deleteRelatedObjects.containsKey(vertexObjectId)) {
+ notification.createNotificationEvent(transactionId, sourceOfTruth, status,
+ uriMap.get(vertexObjectId), entry.getValue(), deleteRelatedObjects.get(vertexObjectId),
+ basePath);
+ }
+ }
+ } catch (UnsupportedEncodingException | AAIException e) {
+
+ LOGGER.warn("Error in sending notification");
+ }
+ }
+ }
+
+ public void setPaginationParameters(String resultIndex, String resultSize) {
+ if (resultIndex != null && resultIndex != "-1" && resultSize != null && resultSize != "-1") {
+ this.setPaginationIndex(Integer.parseInt(resultIndex));
+ this.setPaginationBucket(Integer.parseInt(resultSize));
+ }
+ }
+
+ public List<Object> getPaginatedVertexList(List<Object> vertexList) throws AAIException {
+ List<Object> vertices;
+ if (this.isPaginated()) {
+ this.setTotalsForPaging(vertexList.size(), this.getPaginationBucket());
+ int startIndex = (this.getPaginationIndex() - 1) * this.getPaginationBucket();
+ int endIndex = Math.min((this.getPaginationBucket() * this.getPaginationIndex()), vertexList.size());
+ if (startIndex > endIndex) {
+ throw new AAIException("AAI_6150",
+ " ResultIndex is not appropriate for the result set, Needs to be <= " + endIndex);
+ }
+ vertices = vertexList.subList(startIndex, endIndex);
+ } else {
+ vertices = vertexList;
+ }
+ return vertices;
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/rest/ueb/NotificationEvent.java b/aai-core/src/main/java/org/onap/aai/rest/ueb/NotificationEvent.java
index 5dafebd6..61beb8d0 100644
--- a/aai-core/src/main/java/org/onap/aai/rest/ueb/NotificationEvent.java
+++ b/aai-core/src/main/java/org/onap/aai/rest/ueb/NotificationEvent.java
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.rest.ueb;
import org.onap.aai.exceptions.AAIException;
@@ -30,68 +31,67 @@ import org.onap.aai.util.StoreNotificationEvent;
*/
public class NotificationEvent {
- private final Loader loader;
-
- private final Introspector eventHeader;
-
- private final Introspector obj;
- private final String transactionId;
- private final String sourceOfTruth;
- /**
- * Instantiates a new notification event.
- *
- * @param eventHeader the event header
- * @param obj the obj
- */
- public NotificationEvent (Loader loader, Introspector eventHeader, Introspector obj, String transactionId, String sourceOfTruth) {
- this.loader = loader;
- this.eventHeader = eventHeader;
- this.obj = obj;
- this.transactionId = transactionId;
- this.sourceOfTruth = sourceOfTruth;
- }
-
- /**
- * Trigger.
- *
- * @throws AAIException the AAI exception
- */
- public void trigger() throws AAIException {
-
- StoreNotificationEvent sne = new StoreNotificationEvent(transactionId, sourceOfTruth);
-
- sne.storeEvent(loader, eventHeader, obj);
+ private final Loader loader;
+
+ private final Introspector eventHeader;
+
+ private final Introspector obj;
+ private final String transactionId;
+ private final String sourceOfTruth;
+
+ /**
+ * Instantiates a new notification event.
+ *
+ * @param eventHeader the event header
+ * @param obj the obj
+ */
+ public NotificationEvent(Loader loader, Introspector eventHeader, Introspector obj, String transactionId,
+ String sourceOfTruth) {
+ this.loader = loader;
+ this.eventHeader = eventHeader;
+ this.obj = obj;
+ this.transactionId = transactionId;
+ this.sourceOfTruth = sourceOfTruth;
+ }
+
+ /**
+ * Trigger.
+ *
+ * @throws AAIException the AAI exception
+ */
+ public void trigger() throws AAIException {
+
+ StoreNotificationEvent sne = new StoreNotificationEvent(transactionId, sourceOfTruth);
+
+ sne.storeEvent(loader, eventHeader, obj);
+
+ }
+
+ /**
+ * Gets the notification version.
+ *
+ * @return the notification version
+ */
+ public SchemaVersion getNotificationVersion() {
+ return loader.getVersion();
+ }
+
+ /**
+ * Gets the event header.
+ *
+ * @return the event header
+ */
+ public Introspector getEventHeader() {
+ return eventHeader;
+ }
+
+ /**
+ * Gets the obj.
+ *
+ * @return the obj
+ */
+ public Introspector getObj() {
+ return obj;
+ }
- }
-
- /**
- * Gets the notification version.
- *
- * @return the notification version
- */
- public SchemaVersion getNotificationVersion() {
- return loader.getVersion();
- }
-
- /**
- * Gets the event header.
- *
- * @return the event header
- */
- public Introspector getEventHeader() {
- return eventHeader;
- }
-
- /**
- * Gets the obj.
- *
- * @return the obj
- */
- public Introspector getObj() {
- return obj;
- }
-
-
-
-
}
diff --git a/aai-core/src/main/java/org/onap/aai/rest/ueb/UEBNotification.java b/aai-core/src/main/java/org/onap/aai/rest/ueb/UEBNotification.java
index f5f1e14a..b189c050 100644
--- a/aai-core/src/main/java/org/onap/aai/rest/ueb/UEBNotification.java
+++ b/aai-core/src/main/java/org/onap/aai/rest/ueb/UEBNotification.java
@@ -17,8 +17,12 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.rest.ueb;
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
+
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.util.ArrayList;
@@ -32,161 +36,159 @@ import org.onap.aai.exceptions.AAIException;
import org.onap.aai.introspection.Introspector;
import org.onap.aai.introspection.Loader;
import org.onap.aai.introspection.LoaderFactory;
-import org.onap.aai.setup.SchemaVersion;
-import org.onap.aai.setup.SchemaVersions;
import org.onap.aai.introspection.exceptions.AAIUnknownObjectException;
import org.onap.aai.introspection.exceptions.AAIUnmarshallingException;
import org.onap.aai.logging.LogFormatTools;
import org.onap.aai.parsers.uri.URIToObject;
-
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
+import org.onap.aai.setup.SchemaVersion;
+import org.onap.aai.setup.SchemaVersions;
/**
* The Class UEBNotification.
*/
public class UEBNotification {
- private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(UEBNotification.class);
-
- private Loader currentVersionLoader = null;
- protected List<NotificationEvent> events = null;
- private SchemaVersion notificationVersion = null;
- /**
- * Instantiates a new UEB notification.
- *
- * @param loader the loader
- */
- public UEBNotification(Loader loader, LoaderFactory loaderFactory, SchemaVersions schemaVersions) {
- events = new ArrayList<>();
- SchemaVersion defaultVersion = schemaVersions.getDefaultVersion();
- currentVersionLoader = loaderFactory.createLoaderForVersion(loader.getModelType(), defaultVersion);
- notificationVersion = defaultVersion;
- }
-
-
- /**
- * Creates the notification event.
- *
- * @param transactionId the X-TransactionId
- * @param sourceOfTruth
- * @param status the status
- * @param uri the uri
- * @param obj the obj
- * @param basePath base URI path
- * @throws AAIException the AAI exception
- * @throws IllegalArgumentException the illegal argument exception
- * @throws UnsupportedEncodingException the unsupported encoding exception
- */
- public void createNotificationEvent(String transactionId, String sourceOfTruth, Status status, URI uri, Introspector obj, HashMap<String, Introspector> relatedObjects, String basePath) throws AAIException, UnsupportedEncodingException {
-
- String action = "UPDATE";
-
- if (status.equals(Status.CREATED)) {
- action = "CREATE";
- } else if (status.equals(Status.OK)) {
- action = "UPDATE";
- } else if (status.equals(Status.NO_CONTENT)) {
- action = "DELETE";
- }
-
- try {
- Introspector eventHeader = currentVersionLoader.introspectorFromName("notification-event-header");
- URIToObject parser = new URIToObject(currentVersionLoader, uri, relatedObjects);
-
- String entityLink = "";
- if ((basePath != null) && (!basePath.isEmpty())) {
- if (!(basePath.startsWith("/"))) {
- basePath = "/" + basePath;
- }
- if (!(basePath.endsWith("/"))) {
- basePath = basePath + "/";
- }
- } else {
- // default
- basePath = "/aai/";
- if(LOGGER.isDebugEnabled()){
- LOGGER.debug("Please check the schema.uri.base.path as it didn't seem to be set");
- }
- }
-
- if (uri.toString().startsWith("/")) {
- entityLink = basePath + notificationVersion + uri;
- } else {
- entityLink = basePath + notificationVersion + "/" + uri;
- }
-
-
- eventHeader.setValue("entity-link", entityLink);
- eventHeader.setValue("action", action);
- eventHeader.setValue("entity-type", obj.getDbName());
- eventHeader.setValue("top-entity-type", parser.getTopEntityName());
- eventHeader.setValue("source-name", sourceOfTruth);
- eventHeader.setValue("version", notificationVersion.toString());
- eventHeader.setValue("id", transactionId);
-
- List<Object> parentList = parser.getParentList();
- parentList.clear();
-
- if (!parser.getTopEntity().equals(parser.getEntity())) {
- Introspector child = obj;
- if (!parser.getLoader().getVersion().equals(obj.getVersion())) {
- String json = obj.marshal(false);
- child = parser.getLoader().unmarshal(parser.getEntity().getName(), json);
- }
-
- //wrap the child object in its parents
- parentList.add(child.getUnderlyingObject());
- }
-
- final Introspector eventObject;
-
- //convert to most resent version
- if (!parser.getLoader().getVersion().equals(currentVersionLoader.getVersion())) {
- String json = "";
- if (parser.getTopEntity().equals(parser.getEntity())) {
- //convert the parent object passed in
- json = obj.marshal(false);
- eventObject = currentVersionLoader.unmarshal(obj.getName(), json);
- } else {
- //convert the object created in the parser
- json = parser.getTopEntity().marshal(false);
- eventObject = currentVersionLoader.unmarshal(parser.getTopEntity().getName(), json);
- }
- } else {
- if (parser.getTopEntity().equals(parser.getEntity())) {
- //take the top level parent object passed in
- eventObject = obj;
- } else {
- //take the wrapped child objects (ogres are like onions)
- eventObject = parser.getTopEntity();
- }
- }
- final NotificationEvent event = new NotificationEvent(currentVersionLoader, eventHeader, eventObject, transactionId, sourceOfTruth);
- events.add(event);
- } catch (AAIUnknownObjectException e) {
- throw new RuntimeException("Fatal error - notification-event-header object not found!");
- } catch (AAIUnmarshallingException e) {
- LOGGER.error("Unmarshalling error occurred while generating UEBNotification " + LogFormatTools.getStackTop(e));
- }
- }
-
- /**
- * Trigger events.
- *
- * @throws AAIException the AAI exception
- */
- public void triggerEvents() throws AAIException {
- for (NotificationEvent event : events) {
- event.trigger();
- }
- events.clear();
- }
-
- public List<NotificationEvent> getEvents() {
- return this.events;
- }
-
-
+ private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(UEBNotification.class);
+
+ private Loader currentVersionLoader = null;
+ protected List<NotificationEvent> events = null;
+ private SchemaVersion notificationVersion = null;
+
+ /**
+ * Instantiates a new UEB notification.
+ *
+ * @param loader the loader
+ */
+ public UEBNotification(Loader loader, LoaderFactory loaderFactory, SchemaVersions schemaVersions) {
+ events = new ArrayList<>();
+ SchemaVersion defaultVersion = schemaVersions.getDefaultVersion();
+ currentVersionLoader = loaderFactory.createLoaderForVersion(loader.getModelType(), defaultVersion);
+ notificationVersion = defaultVersion;
+ }
+
+ /**
+ * Creates the notification event.
+ *
+ * @param transactionId the X-TransactionId
+ * @param sourceOfTruth
+ * @param status the status
+ * @param uri the uri
+ * @param obj the obj
+ * @param basePath base URI path
+ * @throws AAIException the AAI exception
+ * @throws IllegalArgumentException the illegal argument exception
+ * @throws UnsupportedEncodingException the unsupported encoding exception
+ */
+ public void createNotificationEvent(String transactionId, String sourceOfTruth, Status status, URI uri,
+ Introspector obj, HashMap<String, Introspector> relatedObjects, String basePath)
+ throws AAIException, UnsupportedEncodingException {
+
+ String action = "UPDATE";
+
+ if (status.equals(Status.CREATED)) {
+ action = "CREATE";
+ } else if (status.equals(Status.OK)) {
+ action = "UPDATE";
+ } else if (status.equals(Status.NO_CONTENT)) {
+ action = "DELETE";
+ }
+
+ try {
+ Introspector eventHeader = currentVersionLoader.introspectorFromName("notification-event-header");
+ URIToObject parser = new URIToObject(currentVersionLoader, uri, relatedObjects);
+
+ String entityLink = "";
+ if ((basePath != null) && (!basePath.isEmpty())) {
+ if (!(basePath.startsWith("/"))) {
+ basePath = "/" + basePath;
+ }
+ if (!(basePath.endsWith("/"))) {
+ basePath = basePath + "/";
+ }
+ } else {
+ // default
+ basePath = "/aai/";
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug("Please check the schema.uri.base.path as it didn't seem to be set");
+ }
+ }
+
+ if (uri.toString().startsWith("/")) {
+ entityLink = basePath + notificationVersion + uri;
+ } else {
+ entityLink = basePath + notificationVersion + "/" + uri;
+ }
+
+ eventHeader.setValue("entity-link", entityLink);
+ eventHeader.setValue("action", action);
+ eventHeader.setValue("entity-type", obj.getDbName());
+ eventHeader.setValue("top-entity-type", parser.getTopEntityName());
+ eventHeader.setValue("source-name", sourceOfTruth);
+ eventHeader.setValue("version", notificationVersion.toString());
+ eventHeader.setValue("id", transactionId);
+
+ List<Object> parentList = parser.getParentList();
+ parentList.clear();
+
+ if (!parser.getTopEntity().equals(parser.getEntity())) {
+ Introspector child = obj;
+ if (!parser.getLoader().getVersion().equals(obj.getVersion())) {
+ String json = obj.marshal(false);
+ child = parser.getLoader().unmarshal(parser.getEntity().getName(), json);
+ }
+
+ // wrap the child object in its parents
+ parentList.add(child.getUnderlyingObject());
+ }
+
+ final Introspector eventObject;
+
+ // convert to most resent version
+ if (!parser.getLoader().getVersion().equals(currentVersionLoader.getVersion())) {
+ String json = "";
+ if (parser.getTopEntity().equals(parser.getEntity())) {
+ // convert the parent object passed in
+ json = obj.marshal(false);
+ eventObject = currentVersionLoader.unmarshal(obj.getName(), json);
+ } else {
+ // convert the object created in the parser
+ json = parser.getTopEntity().marshal(false);
+ eventObject = currentVersionLoader.unmarshal(parser.getTopEntity().getName(), json);
+ }
+ } else {
+ if (parser.getTopEntity().equals(parser.getEntity())) {
+ // take the top level parent object passed in
+ eventObject = obj;
+ } else {
+ // take the wrapped child objects (ogres are like onions)
+ eventObject = parser.getTopEntity();
+ }
+ }
+ final NotificationEvent event =
+ new NotificationEvent(currentVersionLoader, eventHeader, eventObject, transactionId, sourceOfTruth);
+ events.add(event);
+ } catch (AAIUnknownObjectException e) {
+ throw new RuntimeException("Fatal error - notification-event-header object not found!");
+ } catch (AAIUnmarshallingException e) {
+ LOGGER.error(
+ "Unmarshalling error occurred while generating UEBNotification " + LogFormatTools.getStackTop(e));
+ }
+ }
+
+ /**
+ * Trigger events.
+ *
+ * @throws AAIException the AAI exception
+ */
+ public void triggerEvents() throws AAIException {
+ for (NotificationEvent event : events) {
+ event.trigger();
+ }
+ events.clear();
+ }
+
+ public List<NotificationEvent> getEvents() {
+ return this.events;
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/restcore/CustomJacksonJaxBJsonProvider.java b/aai-core/src/main/java/org/onap/aai/restcore/CustomJacksonJaxBJsonProvider.java
index 44bcb8a5..1e9bb05b 100644
--- a/aai-core/src/main/java/org/onap/aai/restcore/CustomJacksonJaxBJsonProvider.java
+++ b/aai-core/src/main/java/org/onap/aai/restcore/CustomJacksonJaxBJsonProvider.java
@@ -17,9 +17,8 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-package org.onap.aai.restcore;
-import javax.ws.rs.ext.Provider;
+package org.onap.aai.restcore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
@@ -28,43 +27,45 @@ import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider;
import com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule;
+import javax.ws.rs.ext.Provider;
+
/**
* The Class CustomJacksonJaxBJsonProvider.
*/
@Provider
public class CustomJacksonJaxBJsonProvider extends JacksonJaxbJsonProvider {
- private static ObjectMapper commonMapper = null;
+ private static ObjectMapper commonMapper = null;
+
+ /**
+ * Instantiates a new custom jackson jax B json provider.
+ */
+ public CustomJacksonJaxBJsonProvider() {
+ if (commonMapper == null) {
+ ObjectMapper mapper = new ObjectMapper();
+
+ mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
- /**
- * Instantiates a new custom jackson jax B json provider.
- */
- public CustomJacksonJaxBJsonProvider() {
- if (commonMapper == null) {
- ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
+ mapper.configure(SerializationFeature.INDENT_OUTPUT, false);
+ mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
- mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
-
- mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
- mapper.configure(SerializationFeature.INDENT_OUTPUT, false);
- mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, false);
- mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, false);
+ mapper.registerModule(new JaxbAnnotationModule());
- mapper.registerModule(new JaxbAnnotationModule());
+ commonMapper = mapper;
+ }
+ super.setMapper(commonMapper);
+ }
- commonMapper = mapper;
- }
- super.setMapper(commonMapper);
- }
-
- /**
- * Gets the mapper.
- *
- * @return the mapper
- */
- public ObjectMapper getMapper() {
- return commonMapper;
- }
+ /**
+ * Gets the mapper.
+ *
+ * @return the mapper
+ */
+ public ObjectMapper getMapper() {
+ return commonMapper;
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/restcore/HttpMethod.java b/aai-core/src/main/java/org/onap/aai/restcore/HttpMethod.java
index 54215d6a..c6b59472 100644
--- a/aai-core/src/main/java/org/onap/aai/restcore/HttpMethod.java
+++ b/aai-core/src/main/java/org/onap/aai/restcore/HttpMethod.java
@@ -17,17 +17,12 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.restcore;
/**
* The Enum HttpMethod.
*/
public enum HttpMethod {
- PUT,
- MERGE_PATCH,
- DELETE,
- PUT_EDGE,
- DELETE_EDGE,
- GET,
- GET_RELATIONSHIP;
+ PUT, MERGE_PATCH, DELETE, PUT_EDGE, DELETE_EDGE, GET, GET_RELATIONSHIP;
}
diff --git a/aai-core/src/main/java/org/onap/aai/restcore/JettyObfuscationConversionCommandLineUtil.java b/aai-core/src/main/java/org/onap/aai/restcore/JettyObfuscationConversionCommandLineUtil.java
index b4d04246..3e995d64 100644
--- a/aai-core/src/main/java/org/onap/aai/restcore/JettyObfuscationConversionCommandLineUtil.java
+++ b/aai-core/src/main/java/org/onap/aai/restcore/JettyObfuscationConversionCommandLineUtil.java
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.restcore;
import org.apache.commons.cli.BasicParser;
@@ -47,50 +48,50 @@ import org.eclipse.jetty.util.security.Password;
* the-secret-to-hide-the-secret problem.
*/
public class JettyObfuscationConversionCommandLineUtil {
-
- /**
- * The main method.
- *
- * @param args the arguments
- */
- public static void main(String[] args){
- Options options = new Options();
- options.addOption("e", true, "obfuscate the given string");
- options.addOption("d", true, "deobfuscate the given string");
-
- CommandLineParser parser = new BasicParser();
-
- try {
- CommandLine cmd = parser.parse(options, args);
- String toProcess = null;
-
- if (cmd.hasOption("e")){
- toProcess = cmd.getOptionValue("e");
- String encoded = Password.obfuscate(toProcess);
- System.out.println(encoded);
- } else if (cmd.hasOption("d")) {
- toProcess = cmd.getOptionValue("d");
- String decoded_str = Password.deobfuscate(toProcess);
- System.out.println(decoded_str);
- } else {
- usage();
- }
- } catch (ParseException e) {
- System.out.println("failed to parse input");
- System.out.println(e.toString());
- usage();
- } catch (Exception e) {
- System.out.println("exception:" + e.toString());
- }
- }
-
- /**
- * Usage.
- */
- private static void usage(){
- System.out.println("usage:");;
- System.out.println("-e [string] to obfuscate");
- System.out.println("-d [string] to deobfuscate");
- System.out.println("-h help");
- }
+
+ /**
+ * The main method.
+ *
+ * @param args the arguments
+ */
+ public static void main(String[] args) {
+ Options options = new Options();
+ options.addOption("e", true, "obfuscate the given string");
+ options.addOption("d", true, "deobfuscate the given string");
+
+ CommandLineParser parser = new BasicParser();
+
+ try {
+ CommandLine cmd = parser.parse(options, args);
+ String toProcess = null;
+
+ if (cmd.hasOption("e")) {
+ toProcess = cmd.getOptionValue("e");
+ String encoded = Password.obfuscate(toProcess);
+ System.out.println(encoded);
+ } else if (cmd.hasOption("d")) {
+ toProcess = cmd.getOptionValue("d");
+ String decoded_str = Password.deobfuscate(toProcess);
+ System.out.println(decoded_str);
+ } else {
+ usage();
+ }
+ } catch (ParseException e) {
+ System.out.println("failed to parse input");
+ System.out.println(e.toString());
+ usage();
+ } catch (Exception e) {
+ System.out.println("exception:" + e.toString());
+ }
+ }
+
+ /**
+ * Usage.
+ */
+ private static void usage() {
+ System.out.println("usage:");;
+ System.out.println("-e [string] to obfuscate");
+ System.out.println("-d [string] to deobfuscate");
+ System.out.println("-h help");
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/restcore/MediaType.java b/aai-core/src/main/java/org/onap/aai/restcore/MediaType.java
index 66344a69..409c84cc 100644
--- a/aai-core/src/main/java/org/onap/aai/restcore/MediaType.java
+++ b/aai-core/src/main/java/org/onap/aai/restcore/MediaType.java
@@ -17,16 +17,16 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.restcore;
/**
* The Enum MediaType.
*/
public enum MediaType {
- APPLICATION_JSON_TYPE("application/json"),
- APPLICATION_XML_TYPE("application/xml");
-
- private final String text;
+ APPLICATION_JSON_TYPE("application/json"), APPLICATION_XML_TYPE("application/xml");
+
+ private final String text;
/**
* Instantiates a new media type.
@@ -36,7 +36,7 @@ public enum MediaType {
private MediaType(final String text) {
this.text = text;
}
-
+
/**
* Gets the enum.
*
@@ -44,20 +44,20 @@ public enum MediaType {
* @return the enum
*/
public static MediaType getEnum(String value) {
-
- for(MediaType v : values()) {
- if(v.toString().equalsIgnoreCase(value)) {
- return v;
- }
- }
-
+
+ for (MediaType v : values()) {
+ if (v.toString().equalsIgnoreCase(value)) {
+ return v;
+ }
+ }
+
throw new IllegalArgumentException("bad value: " + value);
-
+
}
-
+
/**
- * @{inheritDoc}
- */
+ * @{inheritDoc}
+ */
@Override
public String toString() {
return text;
diff --git a/aai-core/src/main/java/org/onap/aai/restcore/RESTAPI.java b/aai-core/src/main/java/org/onap/aai/restcore/RESTAPI.java
index 1b3796e2..ae102a83 100644
--- a/aai-core/src/main/java/org/onap/aai/restcore/RESTAPI.java
+++ b/aai-core/src/main/java/org/onap/aai/restcore/RESTAPI.java
@@ -17,19 +17,24 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.restcore;
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
+import com.google.common.base.Joiner;
+
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.util.ArrayList;
+import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import java.util.HashMap;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
-import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
-import java.util.concurrent.Callable;
import java.util.concurrent.TimeoutException;
import javax.ws.rs.core.HttpHeaders;
@@ -53,346 +58,343 @@ import org.onap.aai.logging.LoggingContext;
import org.onap.aai.util.AAIConfig;
import org.onap.aai.util.FormatDate;
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
-import com.google.common.base.Joiner;
-
-
/**
* Base class for AAI REST API classes.
* Provides method to validate header information
* TODO should authenticate caller and authorize them for the API they are calling
* TODO should store the transaction
-
*
+ *
*/
public class RESTAPI {
-
- private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(RESTAPI.class);
-
- protected final String COMPONENT = "aairest";
-
- /**
- * The Enum Action.
- */
- public enum Action {
- GET, PUT, POST, DELETE
- };
-
- /**
- * Gets the from app id.
- *
- * @param headers the headers
- * @return the from app id
- * @throws AAIException the AAI exception
- */
- protected String getFromAppId(HttpHeaders headers) throws AAIException {
- String fromAppId = null;
- if (headers != null) {
- List<String> fromAppIdHeader = headers.getRequestHeader("X-FromAppId");
- if (fromAppIdHeader != null) {
- for (String fromAppIdValue : fromAppIdHeader) {
- fromAppId = fromAppIdValue;
- }
- }
- }
-
- if (fromAppId == null) {
- throw new AAIException("AAI_4009");
- }
-
- LoggingContext.partnerName(fromAppId);
-
- return fromAppId;
- }
-
- /**
- * Gets the trans id.
- *
- * @param headers the headers
- * @return the trans id
- * @throws AAIException the AAI exception
- */
- protected String getTransId(HttpHeaders headers) throws AAIException {
- String transId = null;
- if (headers != null) {
- List<String> transIdHeader = headers.getRequestHeader("X-TransactionId");
- if (transIdHeader != null) {
- for (String transIdValue : transIdHeader) {
- transId = transIdValue;
- }
- }
- }
-
- if (transId == null) {
- throw new AAIException("AAI_4010");
- }
-
- LoggingContext.requestId(transId);
-
- return transId;
- }
-
-
- /**
- * Gen date.
- *
- * @return the string
- */
- protected String genDate() {
- FormatDate fd = new FormatDate( "YYMMdd-HH:mm:ss:SSS");
-
- return fd.getDateTime();
- }
-
- /**
- * Gets the media type.
- *
- * @param mediaTypeList the media type list
- * @return the media type
- */
- protected String getMediaType(List <MediaType> mediaTypeList) {
- String mediaType = MediaType.APPLICATION_JSON; // json is the default
- for (MediaType mt : mediaTypeList) {
- if (MediaType.APPLICATION_XML_TYPE.isCompatible(mt)) {
- mediaType = MediaType.APPLICATION_XML;
- }
- }
- return mediaType;
- }
-
-
- /* ----------helpers for common consumer actions ----------- */
-
- /**
- * Sets the depth.
- *
- * @param depthParam the depth param
- * @return the int
- * @throws AAIException the AAI exception
- */
- protected int setDepth(String depthParam) throws AAIException {
- int depth = AAIProperties.MAXIMUM_DEPTH; //default
- if (depthParam != null && depthParam.length() > 0 && !depthParam.equals("all")){
- try {
- depth = Integer.valueOf(depthParam);
- } catch (Exception e) {
- throw new AAIException("AAI_4016");
- }
- }
- return depth;
- }
-
- /**
- * Consumer exception response generator.
- *
- * @param headers the headers
- * @param info the info
- * @param templateAction the template action
- * @param e the e
- * @return the response
- */
- protected Response consumerExceptionResponseGenerator(HttpHeaders headers, UriInfo info, HttpMethod templateAction, AAIException e) {
- ArrayList<String> templateVars = new ArrayList<String>();
- templateVars.add(templateAction.toString()); //GET, PUT, etc
- templateVars.add(info.getPath().toString());
- templateVars.addAll(e.getTemplateVars());
-
- ErrorLogHelper.logException(e);
- return Response
- .status(e.getErrorObject().getHTTPResponseCode())
- .entity(ErrorLogHelper.getRESTAPIErrorResponseWithLogging(headers.getAcceptableMediaTypes(), e, templateVars))
- .build();
- }
-
- /**
- * Validate introspector.
- *
- * @param obj the obj
- * @param loader the loader
- * @param uri the uri
- * @throws AAIException the AAI exception
- * @throws UnsupportedEncodingException the unsupported encoding exception
- */
- protected void validateIntrospector(Introspector obj, Loader loader, URI uri, HttpMethod method) throws AAIException, UnsupportedEncodingException {
-
- int maximumDepth = AAIProperties.MAXIMUM_DEPTH;
- boolean validateRequired = true;
- if (method.equals(HttpMethod.MERGE_PATCH)) {
- validateRequired = false;
- maximumDepth = 0;
- }
- IntrospectorValidator validator = new IntrospectorValidator.Builder()
- .validateRequired(validateRequired)
- .restrictDepth(maximumDepth)
- .addResolver(new RemoveNonVisibleProperty())
- .addResolver(new CreateUUID())
- .addResolver(new DefaultFields())
- .addResolver(new InjectKeysFromURI(loader, uri))
- .build();
- boolean result = validator.validate(obj);
- if (!result) {
- result = validator.resolveIssues();
- }
- if (!result) {
- List<String> messages = new ArrayList<>();
- for (Issue issue : validator.getIssues()) {
- if (!issue.isResolved()) {
- messages.add(issue.getDetail());
- }
- }
- String errors = Joiner.on(",").join(messages);
- throw new AAIException("AAI_3000", errors);
- }
- //check that key in payload and key in request uri are the same
+
+ private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(RESTAPI.class);
+
+ protected final String COMPONENT = "aairest";
+
+ /**
+ * The Enum Action.
+ */
+ public enum Action {
+ GET, PUT, POST, DELETE
+ };
+
+ /**
+ * Gets the from app id.
+ *
+ * @param headers the headers
+ * @return the from app id
+ * @throws AAIException the AAI exception
+ */
+ protected String getFromAppId(HttpHeaders headers) throws AAIException {
+ String fromAppId = null;
+ if (headers != null) {
+ List<String> fromAppIdHeader = headers.getRequestHeader("X-FromAppId");
+ if (fromAppIdHeader != null) {
+ for (String fromAppIdValue : fromAppIdHeader) {
+ fromAppId = fromAppIdValue;
+ }
+ }
+ }
+
+ if (fromAppId == null) {
+ throw new AAIException("AAI_4009");
+ }
+
+ LoggingContext.partnerName(fromAppId);
+
+ return fromAppId;
+ }
+
+ /**
+ * Gets the trans id.
+ *
+ * @param headers the headers
+ * @return the trans id
+ * @throws AAIException the AAI exception
+ */
+ protected String getTransId(HttpHeaders headers) throws AAIException {
+ String transId = null;
+ if (headers != null) {
+ List<String> transIdHeader = headers.getRequestHeader("X-TransactionId");
+ if (transIdHeader != null) {
+ for (String transIdValue : transIdHeader) {
+ transId = transIdValue;
+ }
+ }
+ }
+
+ if (transId == null) {
+ throw new AAIException("AAI_4010");
+ }
+
+ LoggingContext.requestId(transId);
+
+ return transId;
+ }
+
+ /**
+ * Gen date.
+ *
+ * @return the string
+ */
+ protected String genDate() {
+ FormatDate fd = new FormatDate("YYMMdd-HH:mm:ss:SSS");
+
+ return fd.getDateTime();
+ }
+
+ /**
+ * Gets the media type.
+ *
+ * @param mediaTypeList the media type list
+ * @return the media type
+ */
+ protected String getMediaType(List<MediaType> mediaTypeList) {
+ String mediaType = MediaType.APPLICATION_JSON; // json is the default
+ for (MediaType mt : mediaTypeList) {
+ if (MediaType.APPLICATION_XML_TYPE.isCompatible(mt)) {
+ mediaType = MediaType.APPLICATION_XML;
+ }
+ }
+ return mediaType;
+ }
+
+ /* ----------helpers for common consumer actions ----------- */
+
+ /**
+ * Sets the depth.
+ *
+ * @param depthParam the depth param
+ * @return the int
+ * @throws AAIException the AAI exception
+ */
+ protected int setDepth(String depthParam) throws AAIException {
+ int depth = AAIProperties.MAXIMUM_DEPTH; // default
+ if (depthParam != null && depthParam.length() > 0 && !depthParam.equals("all")) {
+ try {
+ depth = Integer.valueOf(depthParam);
+ } catch (Exception e) {
+ throw new AAIException("AAI_4016");
+ }
+ }
+ return depth;
+ }
+
+ /**
+ * Consumer exception response generator.
+ *
+ * @param headers the headers
+ * @param info the info
+ * @param templateAction the template action
+ * @param e the e
+ * @return the response
+ */
+ protected Response consumerExceptionResponseGenerator(HttpHeaders headers, UriInfo info, HttpMethod templateAction,
+ AAIException e) {
+ ArrayList<String> templateVars = new ArrayList<String>();
+ templateVars.add(templateAction.toString()); // GET, PUT, etc
+ templateVars.add(info.getPath().toString());
+ templateVars.addAll(e.getTemplateVars());
+
+ ErrorLogHelper.logException(e);
+ return Response
+ .status(e.getErrorObject().getHTTPResponseCode()).entity(ErrorLogHelper
+ .getRESTAPIErrorResponseWithLogging(headers.getAcceptableMediaTypes(), e, templateVars))
+ .build();
+ }
+
+ /**
+ * Validate introspector.
+ *
+ * @param obj the obj
+ * @param loader the loader
+ * @param uri the uri
+ * @throws AAIException the AAI exception
+ * @throws UnsupportedEncodingException the unsupported encoding exception
+ */
+ protected void validateIntrospector(Introspector obj, Loader loader, URI uri, HttpMethod method)
+ throws AAIException, UnsupportedEncodingException {
+
+ int maximumDepth = AAIProperties.MAXIMUM_DEPTH;
+ boolean validateRequired = true;
+ if (method.equals(HttpMethod.MERGE_PATCH)) {
+ validateRequired = false;
+ maximumDepth = 0;
+ }
+ IntrospectorValidator validator = new IntrospectorValidator.Builder().validateRequired(validateRequired)
+ .restrictDepth(maximumDepth).addResolver(new RemoveNonVisibleProperty()).addResolver(new CreateUUID())
+ .addResolver(new DefaultFields()).addResolver(new InjectKeysFromURI(loader, uri)).build();
+ boolean result = validator.validate(obj);
+ if (!result) {
+ result = validator.resolveIssues();
+ }
+ if (!result) {
+ List<String> messages = new ArrayList<>();
+ for (Issue issue : validator.getIssues()) {
+ if (!issue.isResolved()) {
+ messages.add(issue.getDetail());
+ }
+ }
+ String errors = Joiner.on(",").join(messages);
+ throw new AAIException("AAI_3000", errors);
+ }
+ // check that key in payload and key in request uri are the same
String objURI = obj.getURI();
- //if requested object is a parent objURI will have a leading slash the input uri will lack
- //this adds that leading slash for the comparison
+ // if requested object is a parent objURI will have a leading slash the input uri will lack
+ // this adds that leading slash for the comparison
String testURI = "/" + uri.getRawPath();
if (!testURI.endsWith(objURI)) {
- throw new AAIException("AAI_3000", "uri and payload keys don't match");
+ throw new AAIException("AAI_3000", "uri and payload keys don't match");
}
- }
-
- protected DBConnectionType determineConnectionType(String fromAppId, String realTime) throws AAIException {
- if (fromAppId == null) {
- throw new AAIException("AAI_4009", "X-FromAppId is not set");
- }
-
- DBConnectionType type = DBConnectionType.REALTIME;
- boolean isRealTimeClient = AAIConfig.get("aai.realtime.clients", "").contains(fromAppId);
- if (isRealTimeClient || realTime != null) {
- type = DBConnectionType.REALTIME;
- } else {
- type = DBConnectionType.CACHED;
- }
-
- return type;
- }
-
- /**
- * Gets the input media type.
- *
- * @param mediaType the media type
- * @return the input media type
- */
- protected String getInputMediaType(MediaType mediaType) {
- String result = mediaType.getType() + "/" + mediaType.getSubtype();
-
- return result;
-
- }
-
- /**
- * Returns the app specific timeout in milliseconds, -1 overrides the timeout for an app
- *
- * @param sot
- * @param appTimeouts
- * @param defaultTimeout
- * @return integer timeout in or -1 to bypass
- * @throws AAIException
- */
-
- public int getTimeoutLimit(String sot, String appTimeouts, String defaultTimeout) throws AAIException{
- String[] ignoreAppIds = (appTimeouts).split("\\|");
- int appLimit = Integer.parseInt(defaultTimeout);
- final Map<String, Integer> m = new HashMap<String, Integer>();
- if(ignoreAppIds != null) {
- for (int i = 0; i < ignoreAppIds.length; i++) {
- String[] vals = ignoreAppIds[i].split(",");
- m.put(vals[0], Integer.parseInt(vals[1]));
- }
- if (m.get(sot) != null) {
- appLimit = m.get(sot);
- }
- }
- return appLimit;
- }
-
- /**
- * Returns whether time out is enabled
- * @param sot
- * @param isEnabled
- * @param appTimeouts
- * @param defaultTimeout
- * @return boolean of whether the timeout is enabled
- * @throws AAIException
- */
- public boolean isTimeoutEnabled(String sot, String isEnabled, String appTimeouts, String defaultTimeout) throws AAIException{
- Boolean isTimeoutEnabled = Boolean.parseBoolean(isEnabled);
- int ata = -1;
- if(isTimeoutEnabled) {
- ata = getTimeoutLimit(sot, appTimeouts, defaultTimeout);
- }
- return isTimeoutEnabled && (ata > -1);
- }
-
- /**
- * Executes the process thread and watches the future for the timeout
- * @param handler
- * @param sourceOfTruth
- * @param appTimeoutLimit
- * @param defaultTimeoutLimit
- * @param method
- * @param headers
- * @param info
- * @return the response
- */
-
- public Response executeProcess(Future<Response> handler, String sourceOfTruth, String appTimeoutLimit, String defaultTimeoutLimit, HttpMethod method, HttpHeaders headers, UriInfo info){
- Response response = null;
- int timeoutLimit = 0;
- try {
- timeoutLimit = getTimeoutLimit(sourceOfTruth, appTimeoutLimit, defaultTimeoutLimit);
- response = handler.get(timeoutLimit, TimeUnit.MILLISECONDS);
- } catch (TimeoutException e) {
- AAIException ex = new AAIException("AAI_7406", String.format("Timeout limit of %s seconds reached.", timeoutLimit/1000));
- response = consumerExceptionResponseGenerator(headers, info, method, ex);
- handler.cancel(true);
- } catch (Exception e) {
- AAIException ex = new AAIException("AAI_4000", e);
- response = consumerExceptionResponseGenerator(headers, info, method, ex);
- }
- return response;
- }
-
- /**
- * runner sets up the timer logic and invokes it
- * @param toe
- * @param tba
- * @param tdl
- * @param headers
- * @param info
- * @param httpMethod
- * @param c
- * @return the response
- */
- public Response runner(String toe, String tba, String tdl, HttpHeaders headers, UriInfo info, HttpMethod httpMethod, Callable c){
- Response response = null;
- Future<Response> handler = null;
- ExecutorService executor = null;
- try {
- String timeoutEnabled = AAIConfig.get(toe);
- String timeoutByApp = AAIConfig.get(tba);
- String timeoutDefaultLimit = AAIConfig.get(tdl);
- String sourceOfTruth = headers.getRequestHeaders().getFirst("X-FromAppId");
- if (isTimeoutEnabled(sourceOfTruth, timeoutEnabled, timeoutByApp, timeoutDefaultLimit)) {
- executor = Executors.newSingleThreadExecutor();
- handler = executor.submit(c);
- response = executeProcess(handler, sourceOfTruth, timeoutByApp, timeoutDefaultLimit, httpMethod, headers, info);
- } else {
- response = (Response) c.call();
- }
- }catch(Exception e){
- AAIException ex = new AAIException("AAI_4000", e);
- response = consumerExceptionResponseGenerator(headers, info, httpMethod, ex);
- }finally{
- if(executor != null && handler != null){
- executor.shutdownNow();
- }
- }
- return response;
- }
+ }
-}
+ protected DBConnectionType determineConnectionType(String fromAppId, String realTime) throws AAIException {
+ if (fromAppId == null) {
+ throw new AAIException("AAI_4009", "X-FromAppId is not set");
+ }
+
+ DBConnectionType type = DBConnectionType.REALTIME;
+ boolean isRealTimeClient = AAIConfig.get("aai.realtime.clients", "").contains(fromAppId);
+ if (isRealTimeClient || realTime != null) {
+ type = DBConnectionType.REALTIME;
+ } else {
+ type = DBConnectionType.CACHED;
+ }
+
+ return type;
+ }
+
+ /**
+ * Gets the input media type.
+ *
+ * @param mediaType the media type
+ * @return the input media type
+ */
+ protected String getInputMediaType(MediaType mediaType) {
+ String result = mediaType.getType() + "/" + mediaType.getSubtype();
+
+ return result;
+
+ }
+
+ /**
+ * Returns the app specific timeout in milliseconds, -1 overrides the timeout for an app
+ *
+ * @param sot
+ * @param appTimeouts
+ * @param defaultTimeout
+ * @return integer timeout in or -1 to bypass
+ * @throws AAIException
+ */
+
+ public int getTimeoutLimit(String sot, String appTimeouts, String defaultTimeout) throws AAIException {
+ String[] ignoreAppIds = (appTimeouts).split("\\|");
+ int appLimit = Integer.parseInt(defaultTimeout);
+ final Map<String, Integer> m = new HashMap<String, Integer>();
+ if (ignoreAppIds != null) {
+ for (int i = 0; i < ignoreAppIds.length; i++) {
+ String[] vals = ignoreAppIds[i].split(",");
+ m.put(vals[0], Integer.parseInt(vals[1]));
+ }
+ if (m.get(sot) != null) {
+ appLimit = m.get(sot);
+ }
+ }
+ return appLimit;
+ }
+ /**
+ * Returns whether time out is enabled
+ *
+ * @param sot
+ * @param isEnabled
+ * @param appTimeouts
+ * @param defaultTimeout
+ * @return boolean of whether the timeout is enabled
+ * @throws AAIException
+ */
+ public boolean isTimeoutEnabled(String sot, String isEnabled, String appTimeouts, String defaultTimeout)
+ throws AAIException {
+ Boolean isTimeoutEnabled = Boolean.parseBoolean(isEnabled);
+ int ata = -1;
+ if (isTimeoutEnabled) {
+ ata = getTimeoutLimit(sot, appTimeouts, defaultTimeout);
+ }
+ return isTimeoutEnabled && (ata > -1);
+ }
+
+ /**
+ * Executes the process thread and watches the future for the timeout
+ *
+ * @param handler
+ * @param sourceOfTruth
+ * @param appTimeoutLimit
+ * @param defaultTimeoutLimit
+ * @param method
+ * @param headers
+ * @param info
+ * @return the response
+ */
+
+ public Response executeProcess(Future<Response> handler, String sourceOfTruth, String appTimeoutLimit,
+ String defaultTimeoutLimit, HttpMethod method, HttpHeaders headers, UriInfo info) {
+ Response response = null;
+ int timeoutLimit = 0;
+ try {
+ timeoutLimit = getTimeoutLimit(sourceOfTruth, appTimeoutLimit, defaultTimeoutLimit);
+ response = handler.get(timeoutLimit, TimeUnit.MILLISECONDS);
+ } catch (TimeoutException e) {
+ AAIException ex = new AAIException("AAI_7406",
+ String.format("Timeout limit of %s seconds reached.", timeoutLimit / 1000));
+ response = consumerExceptionResponseGenerator(headers, info, method, ex);
+ handler.cancel(true);
+ } catch (Exception e) {
+ AAIException ex = new AAIException("AAI_4000", e);
+ response = consumerExceptionResponseGenerator(headers, info, method, ex);
+ }
+ return response;
+ }
+
+ /**
+ * runner sets up the timer logic and invokes it
+ *
+ * @param toe
+ * @param tba
+ * @param tdl
+ * @param headers
+ * @param info
+ * @param httpMethod
+ * @param c
+ * @return the response
+ */
+ public Response runner(String toe, String tba, String tdl, HttpHeaders headers, UriInfo info, HttpMethod httpMethod,
+ Callable c) {
+ Response response = null;
+ Future<Response> handler = null;
+ ExecutorService executor = null;
+ try {
+ String timeoutEnabled = AAIConfig.get(toe);
+ String timeoutByApp = AAIConfig.get(tba);
+ String timeoutDefaultLimit = AAIConfig.get(tdl);
+ String sourceOfTruth = headers.getRequestHeaders().getFirst("X-FromAppId");
+ if (isTimeoutEnabled(sourceOfTruth, timeoutEnabled, timeoutByApp, timeoutDefaultLimit)) {
+ executor = Executors.newSingleThreadExecutor();
+ handler = executor.submit(c);
+ response = executeProcess(handler, sourceOfTruth, timeoutByApp, timeoutDefaultLimit, httpMethod,
+ headers, info);
+ } else {
+ response = (Response) c.call();
+ }
+ } catch (Exception e) {
+ AAIException ex = new AAIException("AAI_4000", e);
+ response = consumerExceptionResponseGenerator(headers, info, httpMethod, ex);
+ } finally {
+ if (executor != null && handler != null) {
+ executor.shutdownNow();
+ }
+ }
+ return response;
+ }
+
+}
diff --git a/aai-core/src/main/java/org/onap/aai/restcore/search/AAIAbstractGroovyShell.java b/aai-core/src/main/java/org/onap/aai/restcore/search/AAIAbstractGroovyShell.java
index 4703331c..b521a617 100644
--- a/aai-core/src/main/java/org/onap/aai/restcore/search/AAIAbstractGroovyShell.java
+++ b/aai-core/src/main/java/org/onap/aai/restcore/search/AAIAbstractGroovyShell.java
@@ -17,10 +17,16 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.restcore.search;
import groovy.lang.GroovyShell;
import groovy.transform.TimedInterrupt;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
import org.codehaus.groovy.ast.ClassHelper;
import org.codehaus.groovy.ast.expr.ClassExpression;
@@ -30,51 +36,44 @@ import org.codehaus.groovy.control.customizers.ASTTransformationCustomizer;
import org.codehaus.groovy.control.customizers.ImportCustomizer;
import org.onap.aai.serialization.engines.TransactionalGraphEngine;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.concurrent.TimeUnit;
-
public abstract class AAIAbstractGroovyShell {
- protected final GroovyShell shell;
+ protected final GroovyShell shell;
- public AAIAbstractGroovyShell() {
- Map<String, Object> parameters = new HashMap<>();
- parameters.put("value", 30000);
- parameters.put("unit", new PropertyExpression(new ClassExpression(ClassHelper.make(TimeUnit.class)),"MILLISECONDS"));
+ public AAIAbstractGroovyShell() {
+ Map<String, Object> parameters = new HashMap<>();
+ parameters.put("value", 30000);
+ parameters.put("unit",
+ new PropertyExpression(new ClassExpression(ClassHelper.make(TimeUnit.class)), "MILLISECONDS"));
- ASTTransformationCustomizer custom = new ASTTransformationCustomizer(parameters, TimedInterrupt.class);
- ImportCustomizer imports = new ImportCustomizer();
- imports.addStaticStars(
- "org.apache.tinkerpop.gremlin.process.traversal.P",
- "org.apache.tinkerpop.gremlin.process.traversal.Order"
- );
- imports.addImports(
- "org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__",
- "org.apache.tinkerpop.gremlin.structure.T",
- "org.apache.tinkerpop.gremlin.process.traversal.P",
- "org.onap.aai.edges.enums.EdgeType",
- "java.util.Map.Entry");
- imports.addStarImports("java.util");
- CompilerConfiguration config = new CompilerConfiguration();
- config.addCompilationCustomizers(custom, imports);
+ ASTTransformationCustomizer custom = new ASTTransformationCustomizer(parameters, TimedInterrupt.class);
+ ImportCustomizer imports = new ImportCustomizer();
+ imports.addStaticStars("org.apache.tinkerpop.gremlin.process.traversal.P",
+ "org.apache.tinkerpop.gremlin.process.traversal.Order");
+ imports.addImports("org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__",
+ "org.apache.tinkerpop.gremlin.structure.T", "org.apache.tinkerpop.gremlin.process.traversal.P",
+ "org.onap.aai.edges.enums.EdgeType", "java.util.Map.Entry");
+ imports.addStarImports("java.util");
+ CompilerConfiguration config = new CompilerConfiguration();
+ config.addCompilationCustomizers(custom, imports);
- this.shell = new GroovyShell(config);
- }
+ this.shell = new GroovyShell(config);
+ }
- /**
- *
- * @param engine
- * @param traversal
- * @param params
- * @return result of graph traversal
- */
- public abstract String executeTraversal (TransactionalGraphEngine engine, String traversal, Map<String, Object> params);
+ /**
+ *
+ * @param engine
+ * @param traversal
+ * @param params
+ * @return result of graph traversal
+ */
+ public abstract String executeTraversal(TransactionalGraphEngine engine, String traversal,
+ Map<String, Object> params);
- /**
- * @param traversal
- * @param params
- * @return result of graph traversal
- */
- public abstract GraphTraversal<?, ?> executeTraversal (String traversal, Map<String, Object> params);
+ /**
+ * @param traversal
+ * @param params
+ * @return result of graph traversal
+ */
+ public abstract GraphTraversal<?, ?> executeTraversal(String traversal, Map<String, Object> params);
}
diff --git a/aai-core/src/main/java/org/onap/aai/restcore/search/GremlinGroovyShell.java b/aai-core/src/main/java/org/onap/aai/restcore/search/GremlinGroovyShell.java
index 1d074dd4..2b39af43 100644
--- a/aai-core/src/main/java/org/onap/aai/restcore/search/GremlinGroovyShell.java
+++ b/aai-core/src/main/java/org/onap/aai/restcore/search/GremlinGroovyShell.java
@@ -17,15 +17,17 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.restcore.search;
import groovy.lang.Binding;
import groovy.lang.Script;
-import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
-import org.onap.aai.serialization.engines.TransactionalGraphEngine;
import java.util.Map;
+import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
+import org.onap.aai.serialization.engines.TransactionalGraphEngine;
+
/**
* Creates and returns a groovy shell with the
* configuration to statically import graph classes
@@ -33,26 +35,26 @@ import java.util.Map;
*/
public class GremlinGroovyShell extends AAIAbstractGroovyShell {
- public GremlinGroovyShell() {
- super();
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public GraphTraversal<?, ?> executeTraversal (String traversal, Map<String, Object> params) {
- Binding binding = new Binding(params);
- Script script = shell.parse(traversal);
- script.setBinding(binding);
- return (GraphTraversal<?, ?>) script.run();
- }
-
- /**
- * @throws UnsupportedOperationException
- */
- @Override
- public String executeTraversal(TransactionalGraphEngine engine, String traversal, Map<String, Object> params) {
- throw new UnsupportedOperationException();
- }
+ public GremlinGroovyShell() {
+ super();
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public GraphTraversal<?, ?> executeTraversal(String traversal, Map<String, Object> params) {
+ Binding binding = new Binding(params);
+ Script script = shell.parse(traversal);
+ script.setBinding(binding);
+ return (GraphTraversal<?, ?>) script.run();
+ }
+
+ /**
+ * @throws UnsupportedOperationException
+ */
+ @Override
+ public String executeTraversal(TransactionalGraphEngine engine, String traversal, Map<String, Object> params) {
+ throw new UnsupportedOperationException();
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/restcore/search/GroovyQueryBuilder.java b/aai-core/src/main/java/org/onap/aai/restcore/search/GroovyQueryBuilder.java
index f5ec19d5..ba6acb66 100644
--- a/aai-core/src/main/java/org/onap/aai/restcore/search/GroovyQueryBuilder.java
+++ b/aai-core/src/main/java/org/onap/aai/restcore/search/GroovyQueryBuilder.java
@@ -17,10 +17,14 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.restcore.search;
import groovy.lang.Binding;
import groovy.lang.Script;
+
+import java.util.Map;
+
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.onap.aai.config.SpringContextAware;
@@ -32,8 +36,6 @@ import org.onap.aai.serialization.engines.QueryStyle;
import org.onap.aai.serialization.engines.TransactionalGraphEngine;
import org.onap.aai.setup.SchemaVersions;
-import java.util.Map;
-
/**
* Creates and returns a groovy shell with the
* configuration to statically import graph classes
@@ -41,34 +43,35 @@ import java.util.Map;
*/
public class GroovyQueryBuilder extends AAIAbstractGroovyShell {
- public GroovyQueryBuilder() {
- super();
- }
+ public GroovyQueryBuilder() {
+ super();
+ }
- /**
- * {@inheritDoc}
- */
- @Override
- public String executeTraversal (TransactionalGraphEngine engine, String traversal, Map<String, Object> params) {
- QueryBuilder<Vertex> builder = engine.getQueryBuilder(QueryStyle.GREMLIN_TRAVERSAL);
- SchemaVersions schemaVersions = (SchemaVersions) SpringContextAware.getBean("schemaVersions");
- Loader loader = SpringContextAware.getBean(LoaderFactory.class).createLoaderForVersion(ModelType.MOXY, schemaVersions.getDefaultVersion());
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public String executeTraversal(TransactionalGraphEngine engine, String traversal, Map<String, Object> params) {
+ QueryBuilder<Vertex> builder = engine.getQueryBuilder(QueryStyle.GREMLIN_TRAVERSAL);
+ SchemaVersions schemaVersions = (SchemaVersions) SpringContextAware.getBean("schemaVersions");
+ Loader loader = SpringContextAware.getBean(LoaderFactory.class).createLoaderForVersion(ModelType.MOXY,
+ schemaVersions.getDefaultVersion());
- builder.changeLoader(loader);
- Binding binding = new Binding(params);
- binding.setVariable("builder", builder);
- Script script = shell.parse(traversal);
- script.setBinding(binding);
- script.run();
+ builder.changeLoader(loader);
+ Binding binding = new Binding(params);
+ binding.setVariable("builder", builder);
+ Script script = shell.parse(traversal);
+ script.setBinding(binding);
+ script.run();
- return builder.getQuery();
- }
+ return builder.getQuery();
+ }
- /**
- * @throws UnsupportedOperationException
- */
- @Override
- public GraphTraversal<?, ?> executeTraversal(String traversal, Map<String, Object> params) {
- throw new UnsupportedOperationException();
- }
+ /**
+ * @throws UnsupportedOperationException
+ */
+ @Override
+ public GraphTraversal<?, ?> executeTraversal(String traversal, Map<String, Object> params) {
+ throw new UnsupportedOperationException();
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/restcore/util/URITools.java b/aai-core/src/main/java/org/onap/aai/restcore/util/URITools.java
index c12c080b..a757d3db 100644
--- a/aai-core/src/main/java/org/onap/aai/restcore/util/URITools.java
+++ b/aai-core/src/main/java/org/onap/aai/restcore/util/URITools.java
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.restcore.util;
import java.io.UnsupportedEncodingException;
@@ -33,83 +34,85 @@ import java.util.regex.Pattern;
import javax.ws.rs.core.MultivaluedHashMap;
import javax.ws.rs.core.MultivaluedMap;
-import org.springframework.web.util.UriUtils;
-
import org.onap.aai.introspection.Introspector;
import org.onap.aai.introspection.sideeffect.exceptions.AAIMissingRequiredPropertyException;
import org.onap.aai.schema.enums.PropertyMetadata;
+import org.springframework.web.util.UriUtils;
public class URITools {
- protected static final Pattern template = Pattern.compile("\\{(.*?)\\}");
+ protected static final Pattern template = Pattern.compile("\\{(.*?)\\}");
+
+ public static MultivaluedMap<String, String> getQueryMap(URI uri) {
+ MultivaluedMap<String, String> result = new MultivaluedHashMap<>();
+ String queryParams = uri.getRawQuery();
+ if (queryParams != null) {
+ try {
+ String[] sections = queryParams.split("&");
+ String[] query = null;
+ String key, value = "";
+ for (String section : sections) {
+ query = section.split("=");
+ key = UriUtils.decode(query[0], "UTF-8");
+ if (query[1] != null) {
+ query[1] = query[1].replaceAll("\\+", "%20");
+ }
+ value = UriUtils.decode(query[1], "UTF-8");
+ if (result.containsKey(key)) {
+ result.add(key, value);
+ } else {
+ result.putSingle(key, value);
+ }
+ }
+ } catch (UnsupportedEncodingException e) {
+
+ }
+ }
+ return result;
+
+ }
+
+ public static Optional<String> replaceTemplates(Introspector obj, String uriString, PropertyMetadata metadata,
+ boolean replaceWithWildcard) throws AAIMissingRequiredPropertyException {
+ String result = uriString;
+ final Map<String, String> propMap = URITools.findProperties(obj, uriString, metadata, replaceWithWildcard);
+ if (propMap.isEmpty()) {
+ return Optional.empty();
+ }
+ for (Entry<String, String> entry : propMap.entrySet()) {
+ result = result.replaceAll("\\{" + entry.getKey() + "\\}", entry.getValue());
+ }
+ // drop out wildcards if they exist
+ result = result.replaceFirst("/[^/]+?(?:/\\*)+", "");
+ return Optional.of(result);
+ }
+
+ private static Map<String, String> findProperties(Introspector obj, String uriString, PropertyMetadata metadata,
+ boolean replaceWithWildcard) throws AAIMissingRequiredPropertyException {
+
+ final Map<String, String> result = new HashMap<>();
+ final Set<String> missing = new LinkedHashSet<>();
+ Matcher m = template.matcher(uriString);
+ int properties = 0;
+ while (m.find()) {
+ String propName = m.group(1);
+ String value = obj.getValue(propName);
+ properties++;
+ if (value != null) {
+ result.put(propName, value);
+ } else {
+ if (replaceWithWildcard) {
+ result.put(propName, "*");
+ }
+ missing.add(propName);
+ }
+ }
+
+ if (!missing.isEmpty() && (properties != missing.size())) {
+ throw new AAIMissingRequiredPropertyException(
+ "Cannot complete " + metadata.toString() + " uri. Missing properties " + missing);
+ }
+ return result;
+ }
- public static MultivaluedMap<String, String> getQueryMap(URI uri) {
- MultivaluedMap<String, String> result = new MultivaluedHashMap<>();
- String queryParams = uri.getRawQuery();
- if (queryParams != null) {
- try {
- String[] sections = queryParams.split("&");
- String[] query = null;
- String key, value = "";
- for (String section : sections) {
- query = section.split("=");
- key = UriUtils.decode(query[0], "UTF-8");
- if(query[1] != null){
- query[1] = query[1].replaceAll("\\+", "%20");
- }
- value = UriUtils.decode(query[1], "UTF-8");
- if (result.containsKey(key)) {
- result.add(key, value);
- } else {
- result.putSingle(key, value);
- }
- }
- } catch (UnsupportedEncodingException e ) {
-
- }
- }
- return result;
-
- }
-
- public static Optional<String> replaceTemplates(Introspector obj, String uriString, PropertyMetadata metadata, boolean replaceWithWildcard) throws AAIMissingRequiredPropertyException {
- String result = uriString;
- final Map<String, String> propMap = URITools.findProperties(obj, uriString, metadata, replaceWithWildcard);
- if (propMap.isEmpty()) {
- return Optional.empty();
- }
- for (Entry<String, String> entry : propMap.entrySet()) {
- result = result.replaceAll("\\{" + entry.getKey() + "\\}", entry.getValue());
- }
- //drop out wildcards if they exist
- result = result.replaceFirst("/[^/]+?(?:/\\*)+", "");
- return Optional.of(result);
- }
-
- private static Map<String, String> findProperties(Introspector obj, String uriString, PropertyMetadata metadata, boolean replaceWithWildcard) throws AAIMissingRequiredPropertyException {
-
- final Map<String, String> result = new HashMap<>();
- final Set<String> missing = new LinkedHashSet<>();
- Matcher m = template.matcher(uriString);
- int properties = 0;
- while (m.find()) {
- String propName = m.group(1);
- String value = obj.getValue(propName);
- properties++;
- if (value != null) {
- result.put(propName, value);
- } else {
- if (replaceWithWildcard) {
- result.put(propName, "*");
- }
- missing.add(propName);
- }
- }
-
- if (!missing.isEmpty() && (properties != missing.size())) {
- throw new AAIMissingRequiredPropertyException("Cannot complete " + metadata.toString() + " uri. Missing properties " + missing);
- }
- return result;
- }
-
}
diff --git a/aai-core/src/main/java/org/onap/aai/serialization/db/DBSerializer.java b/aai-core/src/main/java/org/onap/aai/serialization/db/DBSerializer.java
index 7a941c69..3996c07d 100644
--- a/aai-core/src/main/java/org/onap/aai/serialization/db/DBSerializer.java
+++ b/aai-core/src/main/java/org/onap/aai/serialization/db/DBSerializer.java
@@ -17,12 +17,28 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-package org.onap.aai.serialization.db;
+package org.onap.aai.serialization.db;
import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
import com.google.common.base.CaseFormat;
+
+import java.io.UnsupportedEncodingException;
+import java.lang.reflect.Array;
+import java.lang.reflect.InvocationTargetException;
+import java.net.MalformedURLException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.*;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Future;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import javax.ws.rs.core.UriBuilder;
+
import org.apache.commons.collections.IteratorUtils;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__;
@@ -70,20 +86,6 @@ import org.onap.aai.util.AAIConstants;
import org.onap.aai.workarounds.NamingExceptions;
import org.springframework.context.ApplicationContext;
-import javax.ws.rs.core.UriBuilder;
-import java.io.UnsupportedEncodingException;
-import java.lang.reflect.Array;
-import java.lang.reflect.InvocationTargetException;
-import java.net.MalformedURLException;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.util.*;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Future;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
public class DBSerializer {
private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(DBSerializer.class);
@@ -106,6 +108,7 @@ public class DBSerializer {
private SchemaVersions schemaVersions;
private Set<String> namedPropNodes;
+
/**
* Instantiates a new DB serializer.
*
@@ -115,15 +118,18 @@ public class DBSerializer {
* @param sourceOfTruth the source of truth
* @throws AAIException
*/
- public DBSerializer(SchemaVersion version, TransactionalGraphEngine engine, ModelType introspectionType, String sourceOfTruth) throws AAIException {
+ public DBSerializer(SchemaVersion version, TransactionalGraphEngine engine, ModelType introspectionType,
+ String sourceOfTruth) throws AAIException {
this.engine = engine;
this.sourceOfTruth = sourceOfTruth;
this.introspectionType = introspectionType;
this.schemaVersions = (SchemaVersions) SpringContextAware.getBean("schemaVersions");
SchemaVersion LATEST = schemaVersions.getDefaultVersion();
- this.latestLoader = SpringContextAware.getBean(LoaderFactory.class).createLoaderForVersion(introspectionType, LATEST);
+ this.latestLoader =
+ SpringContextAware.getBean(LoaderFactory.class).createLoaderForVersion(introspectionType, LATEST);
this.version = version;
- this.loader = SpringContextAware.getBean(LoaderFactory.class).createLoaderForVersion(introspectionType, version);
+ this.loader =
+ SpringContextAware.getBean(LoaderFactory.class).createLoaderForVersion(introspectionType, version);
this.namedPropNodes = this.latestLoader.getNamedPropNodes();
this.baseURL = AAIConfig.get(AAIConstants.AAI_SERVER_URL_BASE);
this.currentTimeMillis = System.currentTimeMillis();
@@ -131,7 +137,7 @@ public class DBSerializer {
}
private void initBeans() {
- //TODO proper spring wiring, but that requires a lot of refactoring so for now we have this
+ // TODO proper spring wiring, but that requires a lot of refactoring so for now we have this
ApplicationContext ctx = SpringContextAware.getApplicationContext();
EdgeIngestor ei = ctx.getBean(EdgeIngestor.class);
setEdgeIngestor(ei);
@@ -186,14 +192,13 @@ public class DBSerializer {
}
-
/**
* Creates the new vertex.
*
* @param wrappedObject the wrapped object
* @return the vertex
* @throws UnsupportedEncodingException the unsupported encoding exception
- * @throws AAIException the AAI exception
+ * @throws AAIException the AAI exception
*/
public Vertex createNewVertex(Introspector wrappedObject) {
Vertex v;
@@ -230,33 +235,35 @@ public class DBSerializer {
/**
* Serialize to db.
*
- * @param obj the obj
- * @param v the v
- * @param uriQuery the uri query
+ * @param obj the obj
+ * @param v the v
+ * @param uriQuery the uri query
* @param identifier the identifier
- * @throws SecurityException the security exception
- * @throws IllegalAccessException the illegal access exception
- * @throws IllegalArgumentException the illegal argument exception
- * @throws InvocationTargetException the invocation target exception
- * @throws InstantiationException the instantiation exception
- * @throws InterruptedException the interrupted exception
- * @throws NoSuchMethodException the no such method exception
- * @throws AAIException the AAI exception
+ * @throws SecurityException the security exception
+ * @throws IllegalAccessException the illegal access exception
+ * @throws IllegalArgumentException the illegal argument exception
+ * @throws InvocationTargetException the invocation target exception
+ * @throws InstantiationException the instantiation exception
+ * @throws InterruptedException the interrupted exception
+ * @throws NoSuchMethodException the no such method exception
+ * @throws AAIException the AAI exception
* @throws UnsupportedEncodingException the unsupported encoding exception
* @throws AAIUnknownObjectException
*/
- public void serializeToDb(Introspector obj, Vertex v, QueryParser uriQuery, String identifier, String requestContext) throws AAIException, UnsupportedEncodingException {
+ public void serializeToDb(Introspector obj, Vertex v, QueryParser uriQuery, String identifier,
+ String requestContext) throws AAIException, UnsupportedEncodingException {
StopWatch.conditionalStart();
try {
if (uriQuery.isDependent()) {
- //try to find the parent
+ // try to find the parent
List<Vertex> vertices = uriQuery.getQueryBuilder().getParentQuery().toList();
if (!vertices.isEmpty()) {
Vertex parent = vertices.get(0);
this.reflectDependentVertex(parent, v, obj, requestContext);
} else {
dbTimeMsecs += StopWatch.stopIfStarted();
- throw new AAIException("AAI_6114", "No parent Node of type " + uriQuery.getParentResultType() + " for " + identifier);
+ throw new AAIException("AAI_6114",
+ "No parent Node of type " + uriQuery.getParentResultType() + " for " + identifier);
}
} else {
serializeSingleVertex(v, obj, requestContext);
@@ -269,7 +276,8 @@ public class DBSerializer {
dbTimeMsecs += StopWatch.stopIfStarted();
}
- public void serializeSingleVertex(Vertex v, Introspector obj, String requestContext) throws UnsupportedEncodingException, AAIException {
+ public void serializeSingleVertex(Vertex v, Introspector obj, String requestContext)
+ throws UnsupportedEncodingException, AAIException {
StopWatch.conditionalStart();
try {
boolean isTopLevel = obj.isTopLevel();
@@ -304,15 +312,15 @@ public class DBSerializer {
*
* @param <T> the generic type
* @param obj the obj
- * @param v the v
+ * @param v the v
* @return the list
- * @throws IllegalAccessException the illegal access exception
- * @throws IllegalArgumentException the illegal argument exception
- * @throws InvocationTargetException the invocation target exception
- * @throws InstantiationException the instantiation exception
- * @throws NoSuchMethodException the no such method exception
- * @throws SecurityException the security exception
- * @throws AAIException the AAI exception
+ * @throws IllegalAccessException the illegal access exception
+ * @throws IllegalArgumentException the illegal argument exception
+ * @throws InvocationTargetException the invocation target exception
+ * @throws InstantiationException the instantiation exception
+ * @throws NoSuchMethodException the no such method exception
+ * @throws SecurityException the security exception
+ * @throws AAIException the AAI exception
* @throws UnsupportedEncodingException the unsupported encoding exception
* @throws AAIUnknownObjectException
*/
@@ -320,7 +328,8 @@ public class DBSerializer {
* Helper method for reflectToDb
* Handles all the property setting
*/
- private <T> List<Vertex> processObject(Introspector obj, Vertex v, String requestContext) throws UnsupportedEncodingException, AAIException {
+ private <T> List<Vertex> processObject(Introspector obj, Vertex v, String requestContext)
+ throws UnsupportedEncodingException, AAIException {
Set<String> properties = new LinkedHashSet<>(obj.getProperties());
properties.remove(AAIProperties.RESOURCE_VERSION);
List<Vertex> dependentVertexes = new ArrayList<>();
@@ -349,8 +358,8 @@ public class DBSerializer {
dbProperty = metadata.get(PropertyMetadata.DB_ALIAS);
}
if (metadata.containsKey(PropertyMetadata.DATA_LINK)) {
- //data linked properties are ephemeral
- //they are populated dynamically on GETs
+ // data linked properties are ephemeral
+ // they are populated dynamically on GETs
continue;
}
if (value != null) {
@@ -376,12 +385,14 @@ public class DBSerializer {
}
}
} else {
- //simple list case
+ // simple list case
engine.setListProperty(v, property, list);
}
} else {
- //method.getReturnType() is not 'simple' then create a vertex and edge recursively returning an edge back to this method
- if (value != null) { //effectively ignore complex properties not included in the object we're processing
+ // method.getReturnType() is not 'simple' then create a vertex and edge recursively returning an edge
+ // back to this method
+ if (value != null) { // effectively ignore complex properties not included in the object we're
+ // processing
if (value.getClass().isArray()) {
int length = Array.getLength(value);
@@ -396,13 +407,15 @@ public class DBSerializer {
// container case
Introspector introspector = IntrospectorFactory.newInstance(this.introspectionType, value);
if (introspector.isContainer()) {
- dependentVertexes.addAll(this.engine.getQueryEngine().findChildrenOfType(v, introspector.getChildDBName()));
+ dependentVertexes.addAll(
+ this.engine.getQueryEngine().findChildrenOfType(v, introspector.getChildDBName()));
introspector.setURIChain(obj.getURI());
processedVertexes.addAll(processObject(introspector, v, requestContext));
} else {
- dependentVertexes.addAll(this.engine.getQueryEngine().findChildrenOfType(v, introspector.getDbName()));
+ dependentVertexes.addAll(
+ this.engine.getQueryEngine().findChildrenOfType(v, introspector.getDbName()));
processedVertexes.add(reflectDependentVertex(v, introspector, requestContext));
}
@@ -424,7 +437,7 @@ public class DBSerializer {
// is doing this so the SE can work with the clients making the call to
// tell them not to call this API and can hopefully deprecate this
// functionality in the future releases
- if(!dependentVertexes.isEmpty()){
+ if (!dependentVertexes.isEmpty()) {
LoggingContext.responseDescription(IMPLICIT_DELETE);
@@ -435,32 +448,31 @@ public class DBSerializer {
int impliedDeleteCount = impliedDeleteVertices.size();
LOGGER.warn(
- "For the vertex with id {}, doing an implicit delete on update will delete total of {} vertexes",
- v.id(),
- impliedDeleteCount
- );
+ "For the vertex with id {}, doing an implicit delete on update will delete total of {} vertexes",
+ v.id(), impliedDeleteCount);
String impliedDeleteLogEnabled = AAIConfig.get(AAIConstants.AAI_IMPLIED_DELETE_LOG_ENABLED, "true");
int impliedDeleteLogLimit = AAIConfig.getInt(AAIConstants.AAI_IMPLIED_DELETE_LOG_LIMIT, "-1");
- if(impliedDeleteLogLimit == -1){
+ if (impliedDeleteLogLimit == -1) {
impliedDeleteLogLimit = Integer.MAX_VALUE;
}
// If the logging is enabled for implied delete
// then log the payload in the latest format
- if("true".equals(impliedDeleteLogEnabled) &&
- impliedDeleteCount <= impliedDeleteLogLimit){
- for(Vertex vertex : impliedDeleteVertices){
+ if ("true".equals(impliedDeleteLogEnabled) && impliedDeleteCount <= impliedDeleteLogLimit) {
+ for (Vertex vertex : impliedDeleteVertices) {
Introspector introspector = null;
try {
introspector = getLatestVersionView(vertex);
- if(LOGGER.isInfoEnabled()){
+ if (LOGGER.isInfoEnabled()) {
LOGGER.info("Implied delete object in json format {}", introspector.marshal(false));
}
- } catch(Exception ex){
- LOGGER.warn("Encountered an exception during retrieval of vertex properties with vertex-id {} -> {}", v.id(), LogFormatTools.getStackTop(ex));
+ } catch (Exception ex) {
+ LOGGER.warn(
+ "Encountered an exception during retrieval of vertex properties with vertex-id {} -> {}",
+ v.id(), LogFormatTools.getStackTop(ex));
}
}
}
@@ -476,37 +488,36 @@ public class DBSerializer {
/**
* Handle relationships.
*
- * @param obj the obj
+ * @param obj the obj
* @param vertex the vertex
- * @throws SecurityException the security exception
- * @throws IllegalAccessException the illegal access exception
- * @throws IllegalArgumentException the illegal argument exception
- * @throws InvocationTargetException the invocation target exception
+ * @throws SecurityException the security exception
+ * @throws IllegalAccessException the illegal access exception
+ * @throws IllegalArgumentException the illegal argument exception
+ * @throws InvocationTargetException the invocation target exception
* @throws UnsupportedEncodingException the unsupported encoding exception
- * @throws AAIException the AAI exception
+ * @throws AAIException the AAI exception
*/
/*
* Handles the explicit relationships defined for an obj
*/
- private void handleRelationships(Introspector obj, Vertex vertex) throws UnsupportedEncodingException, AAIException {
-
+ private void handleRelationships(Introspector obj, Vertex vertex)
+ throws UnsupportedEncodingException, AAIException {
Introspector wrappedRl = obj.getWrappedValue("relationship-list");
processRelationshipList(wrappedRl, vertex);
-
}
-
/**
* Process relationship list.
*
* @param wrapped the wrapped
- * @param v the v
+ * @param v the v
* @throws UnsupportedEncodingException the unsupported encoding exception
- * @throws AAIException the AAI exception
+ * @throws AAIException the AAI exception
*/
- private void processRelationshipList(Introspector wrapped, Vertex v) throws UnsupportedEncodingException, AAIException {
+ private void processRelationshipList(Introspector wrapped, Vertex v)
+ throws UnsupportedEncodingException, AAIException {
List<Object> relationships = (List<Object>) wrapped.getValue("relationship");
@@ -526,12 +537,13 @@ public class DBSerializer {
List<Vertex> results = parser.getQueryBuilder().toList();
if (results.isEmpty()) {
- final AAIException ex = new AAIException("AAI_6129", "Node of type " + parser.getResultType() + ". Could not find object at: " + parser.getUri());
+ final AAIException ex = new AAIException("AAI_6129",
+ "Node of type " + parser.getResultType() + ". Could not find object at: " + parser.getUri());
ex.getTemplateVars().add(parser.getResultType());
ex.getTemplateVars().add(parser.getUri().toString());
throw ex;
} else {
- //still an issue if there's more than one
+ // still an issue if there's more than one
cousinVertex = results.get(0);
}
@@ -540,11 +552,14 @@ public class DBSerializer {
String cousinType = (String) cousinVertex.property(AAIProperties.NODE_TYPE).value();
EdgeRuleQuery.Builder baseQ = new EdgeRuleQuery.Builder(vType, cousinType).label(label);
-
if (!edgeRules.hasRule(baseQ.build())) {
- throw new AAIException("AAI_6120", "No EdgeRule found for passed nodeTypes: " + v.property(AAIProperties.NODE_TYPE).value().toString() + ", "
- + cousinVertex.property(AAIProperties.NODE_TYPE).value().toString() + (label != null ? (" with label " + label) : "") + ".");
- } else if (edgeRules.hasRule(baseQ.edgeType(EdgeType.TREE).build()) && !edgeRules.hasRule(baseQ.edgeType(EdgeType.COUSIN).build())) {
+ throw new AAIException("AAI_6120",
+ "No EdgeRule found for passed nodeTypes: "
+ + v.property(AAIProperties.NODE_TYPE).value().toString() + ", "
+ + cousinVertex.property(AAIProperties.NODE_TYPE).value().toString()
+ + (label != null ? (" with label " + label) : "") + ".");
+ } else if (edgeRules.hasRule(baseQ.edgeType(EdgeType.TREE).build())
+ && !edgeRules.hasRule(baseQ.edgeType(EdgeType.COUSIN).build())) {
throw new AAIException("AAI_6145");
}
@@ -563,7 +578,8 @@ public class DBSerializer {
}
for (Triplet<Vertex, Vertex, String> triplet : addEdges) {
try {
- edgeSer.addEdge(this.engine.asAdmin().getTraversalSource(), triplet.getValue0(), triplet.getValue1(), triplet.getValue2());
+ edgeSer.addEdge(this.engine.asAdmin().getTraversalSource(), triplet.getValue0(), triplet.getValue1(),
+ triplet.getValue2());
} catch (NoEdgeRuleFoundException e) {
throw new AAIException("AAI_6129", e);
}
@@ -574,7 +590,7 @@ public class DBSerializer {
/**
* Write through defaults.
*
- * @param v the v
+ * @param v the v
* @param obj the obj
* @throws AAIUnknownObjectException
*/
@@ -598,27 +614,27 @@ public class DBSerializer {
}
-
/**
* Reflect dependent vertex.
*
- * @param v the v
+ * @param v the v
* @param dependentObj the dependent obj
* @return the vertex
- * @throws IllegalAccessException the illegal access exception
- * @throws IllegalArgumentException the illegal argument exception
- * @throws InvocationTargetException the invocation target exception
- * @throws InstantiationException the instantiation exception
- * @throws NoSuchMethodException the no such method exception
- * @throws SecurityException the security exception
- * @throws AAIException the AAI exception
+ * @throws IllegalAccessException the illegal access exception
+ * @throws IllegalArgumentException the illegal argument exception
+ * @throws InvocationTargetException the invocation target exception
+ * @throws InstantiationException the instantiation exception
+ * @throws NoSuchMethodException the no such method exception
+ * @throws SecurityException the security exception
+ * @throws AAIException the AAI exception
* @throws UnsupportedEncodingException the unsupported encoding exception
* @throws AAIUnknownObjectException
*/
- private Vertex reflectDependentVertex(Vertex v, Introspector dependentObj, String requestContext) throws AAIException, UnsupportedEncodingException {
+ private Vertex reflectDependentVertex(Vertex v, Introspector dependentObj, String requestContext)
+ throws AAIException, UnsupportedEncodingException {
- //QueryParser p = this.engine.getQueryBuilder().createQueryFromURI(obj.getURI());
- //List<Vertex> items = p.getQuery().toList();
+ // QueryParser p = this.engine.getQueryBuilder().createQueryFromURI(obj.getURI());
+ // List<Vertex> items = p.getQuery().toList();
QueryBuilder<Vertex> query = this.engine.getQueryBuilder(v);
query.createEdgeTraversal(EdgeType.TREE, v, dependentObj);
query.createKeyQuery(dependentObj);
@@ -628,9 +644,12 @@ public class DBSerializer {
Vertex dependentVertex = null;
if (items.size() == 1) {
dependentVertex = items.get(0);
- this.verifyResourceVersion("update", dependentObj.getDbName(), dependentVertex.<String>property(AAIProperties.RESOURCE_VERSION).orElse(null), (String) dependentObj.getValue(AAIProperties.RESOURCE_VERSION), (String) dependentObj.getURI());
+ this.verifyResourceVersion("update", dependentObj.getDbName(),
+ dependentVertex.<String>property(AAIProperties.RESOURCE_VERSION).orElse(null),
+ (String) dependentObj.getValue(AAIProperties.RESOURCE_VERSION), (String) dependentObj.getURI());
} else {
- this.verifyResourceVersion("create", dependentObj.getDbName(), "", (String) dependentObj.getValue(AAIProperties.RESOURCE_VERSION), (String) dependentObj.getURI());
+ this.verifyResourceVersion("create", dependentObj.getDbName(), "",
+ (String) dependentObj.getValue(AAIProperties.RESOURCE_VERSION), (String) dependentObj.getURI());
dependentVertex = createNewVertex(dependentObj);
}
@@ -642,20 +661,21 @@ public class DBSerializer {
* Reflect dependent vertex.
*
* @param parent the parent
- * @param child the child
- * @param obj the obj
+ * @param child the child
+ * @param obj the obj
* @return the vertex
- * @throws IllegalAccessException the illegal access exception
- * @throws IllegalArgumentException the illegal argument exception
- * @throws InvocationTargetException the invocation target exception
- * @throws InstantiationException the instantiation exception
- * @throws NoSuchMethodException the no such method exception
- * @throws SecurityException the security exception
- * @throws AAIException the AAI exception
+ * @throws IllegalAccessException the illegal access exception
+ * @throws IllegalArgumentException the illegal argument exception
+ * @throws InvocationTargetException the invocation target exception
+ * @throws InstantiationException the instantiation exception
+ * @throws NoSuchMethodException the no such method exception
+ * @throws SecurityException the security exception
+ * @throws AAIException the AAI exception
* @throws UnsupportedEncodingException the unsupported encoding exception
* @throws AAIUnknownObjectException
*/
- private Vertex reflectDependentVertex(Vertex parent, Vertex child, Introspector obj, String requestContext) throws AAIException, UnsupportedEncodingException {
+ private Vertex reflectDependentVertex(Vertex parent, Vertex child, Introspector obj, String requestContext)
+ throws AAIException, UnsupportedEncodingException {
String parentUri = parent.<String>property(AAIProperties.AAI_URI).orElse(null);
if (parentUri != null) {
@@ -671,8 +691,10 @@ public class DBSerializer {
if (e == null) {
String canBeLinked = obj.getMetadata(ObjectMetadata.CAN_BE_LINKED);
if (canBeLinked != null && canBeLinked.equals("true")) {
- Loader ldrForCntxt = SpringContextAware.getBean(LoaderFactory.class).createLoaderForVersion(introspectionType, getVerForContext(requestContext));
- boolean isFirst = !this.engine.getQueryBuilder(ldrForCntxt, parent).createEdgeTraversal(EdgeType.TREE, parent, obj).hasNext();
+ Loader ldrForCntxt = SpringContextAware.getBean(LoaderFactory.class)
+ .createLoaderForVersion(introspectionType, getVerForContext(requestContext));
+ boolean isFirst = !this.engine.getQueryBuilder(ldrForCntxt, parent)
+ .createEdgeTraversal(EdgeType.TREE, parent, obj).hasNext();
if (isFirst) {
child.property(AAIProperties.LINKED, true);
}
@@ -697,23 +719,24 @@ public class DBSerializer {
* Db to object.
*
* @param vertices the vertices
- * @param obj the obj
- * @param depth the depth
- * @param cleanUp the clean up
+ * @param obj the obj
+ * @param depth the depth
+ * @param cleanUp the clean up
* @return the introspector
- * @throws AAIException the AAI exception
- * @throws IllegalAccessException the illegal access exception
- * @throws IllegalArgumentException the illegal argument exception
- * @throws InvocationTargetException the invocation target exception
- * @throws SecurityException the security exception
- * @throws InstantiationException the instantiation exception
- * @throws NoSuchMethodException the no such method exception
+ * @throws AAIException the AAI exception
+ * @throws IllegalAccessException the illegal access exception
+ * @throws IllegalArgumentException the illegal argument exception
+ * @throws InvocationTargetException the invocation target exception
+ * @throws SecurityException the security exception
+ * @throws InstantiationException the instantiation exception
+ * @throws NoSuchMethodException the no such method exception
* @throws UnsupportedEncodingException the unsupported encoding exception
- * @throws MalformedURLException the malformed URL exception
+ * @throws MalformedURLException the malformed URL exception
* @throws AAIUnknownObjectException
* @throws URISyntaxException
*/
- public Introspector dbToObject(List<Vertex> vertices, final Introspector obj, int depth, boolean nodeOnly, String cleanUp) throws UnsupportedEncodingException, AAIException {
+ public Introspector dbToObject(List<Vertex> vertices, final Introspector obj, int depth, boolean nodeOnly,
+ String cleanUp) throws UnsupportedEncodingException, AAIException {
final int internalDepth;
if (depth == Integer.MAX_VALUE) {
internalDepth = depth--;
@@ -723,7 +746,8 @@ public class DBSerializer {
StopWatch.conditionalStart();
if (vertices.size() > 1 && !obj.isContainer()) {
dbTimeMsecs += StopWatch.stopIfStarted();
- throw new AAIException("AAI_6136", "query object mismatch: this object cannot hold multiple items." + obj.getDbName());
+ throw new AAIException("AAI_6136",
+ "query object mismatch: this object cannot hold multiple items." + obj.getDbName());
} else if (obj.isContainer()) {
final List getList;
String listProperty = null;
@@ -736,7 +760,8 @@ public class DBSerializer {
final String propertyName = listProperty;
getList = (List) obj.getValue(listProperty);
- /* This is an experimental multithreading experiment
+ /*
+ * This is an experimental multithreading experiment
* on get alls.
*/
ExecutorService pool = GetAllPool.getInstance().getPool();
@@ -764,7 +789,7 @@ public class DBSerializer {
throw e;
}
return childObject.getUnderlyingObject();
- //getList.add(childObject.getUnderlyingObject());
+ // getList.add(childObject.getUnderlyingObject());
}
};
futures.add(pool.submit(task));
@@ -785,7 +810,7 @@ public class DBSerializer {
Set<Vertex> seen = new HashSet<>();
dbToObject(obj, vertices.get(0), seen, depth, nodeOnly, cleanUp);
} else {
- //obj = null;
+ // obj = null;
}
dbTimeMsecs += StopWatch.stopIfStarted();
@@ -795,25 +820,26 @@ public class DBSerializer {
/**
* Db to object.
*
- * @param obj the obj
- * @param v the v
- * @param seen the seen
- * @param depth the depth
+ * @param obj the obj
+ * @param v the v
+ * @param seen the seen
+ * @param depth the depth
* @param cleanUp the clean up
* @return the introspector
- * @throws IllegalAccessException the illegal access exception
- * @throws IllegalArgumentException the illegal argument exception
- * @throws InvocationTargetException the invocation target exception
- * @throws SecurityException the security exception
- * @throws InstantiationException the instantiation exception
- * @throws NoSuchMethodException the no such method exception
+ * @throws IllegalAccessException the illegal access exception
+ * @throws IllegalArgumentException the illegal argument exception
+ * @throws InvocationTargetException the invocation target exception
+ * @throws SecurityException the security exception
+ * @throws InstantiationException the instantiation exception
+ * @throws NoSuchMethodException the no such method exception
* @throws UnsupportedEncodingException the unsupported encoding exception
- * @throws AAIException the AAI exception
- * @throws MalformedURLException the malformed URL exception
+ * @throws AAIException the AAI exception
+ * @throws MalformedURLException the malformed URL exception
* @throws AAIUnknownObjectException
* @throws URISyntaxException
*/
- private Introspector dbToObject(Introspector obj, Vertex v, Set<Vertex> seen, int depth, boolean nodeOnly, String cleanUp) throws AAIException, UnsupportedEncodingException {
+ private Introspector dbToObject(Introspector obj, Vertex v, Set<Vertex> seen, int depth, boolean nodeOnly,
+ String cleanUp) throws AAIException, UnsupportedEncodingException {
if (depth < 0) {
return null;
@@ -863,14 +889,16 @@ public class DBSerializer {
EdgeRule rule;
try {
- rule = edgeRules.getRule(new EdgeRuleQuery.Builder(vType, childDbName).edgeType(EdgeType.TREE).build());
+ rule = edgeRules.getRule(
+ new EdgeRuleQuery.Builder(vType, childDbName).edgeType(EdgeType.TREE).build());
} catch (EdgeRuleNotFoundException e) {
throw new NoEdgeRuleFoundException(e);
} catch (AmbiguousRuleChoiceException e) {
throw new MultipleEdgeRuleFoundException(e);
}
if (!rule.getContains().equals(AAIDirection.NONE.toString())) {
- //vertices = this.queryEngine.findRelatedVertices(v, Direction.OUT, rule.getLabel(), childDbName);
+ // vertices = this.queryEngine.findRelatedVertices(v, Direction.OUT, rule.getLabel(),
+ // childDbName);
Direction ruleDirection = rule.getDirection();
Iterator<Vertex> itr = v.vertices(ruleDirection, rule.getLabel());
List<Vertex> verticesList = (List<Vertex>) IteratorUtils.toList(itr);
@@ -887,7 +915,8 @@ public class DBSerializer {
if (!seen.contains(childVertex)) {
Introspector argumentObject = obj.newIntrospectorInstanceOfNestedProperty(property);
- Object result = dbToObject(argumentObject, childVertex, seen, depth, nodeOnly, cleanUp);
+ Object result =
+ dbToObject(argumentObject, childVertex, seen, depth, nodeOnly, cleanUp);
if (result != null) {
getList.add(argumentObject.getUnderlyingObject());
}
@@ -895,11 +924,12 @@ public class DBSerializer {
processed++;
} else {
removed++;
- LOGGER.warn("Cycle found while serializing vertex id={}", childVertex.id().toString());
+ LOGGER.warn("Cycle found while serializing vertex id={}",
+ childVertex.id().toString());
}
}
if (processed == 0) {
- //vertices were all seen, reset the list
+ // vertices were all seen, reset the list
getList = null;
}
if (processed > 0) {
@@ -921,7 +951,7 @@ public class DBSerializer {
}
}
- //no changes were made to this obj, discard the instance
+ // no changes were made to this obj, discard the instance
if (!modified) {
return null;
}
@@ -930,7 +960,6 @@ public class DBSerializer {
}
-
public Introspector getVertexProperties(Vertex v) throws AAIException, UnsupportedEncodingException {
String nodeType = v.<String>property(AAIProperties.NODE_TYPE).orElse(null);
if (nodeType == null) {
@@ -969,14 +998,14 @@ public class DBSerializer {
* Copy simple property.
*
* @param property the property
- * @param obj the obj
- * @param v the v
- * @throws InstantiationException the instantiation exception
- * @throws IllegalAccessException the illegal access exception
- * @throws IllegalArgumentException the illegal argument exception
+ * @param obj the obj
+ * @param v the v
+ * @throws InstantiationException the instantiation exception
+ * @throws IllegalAccessException the illegal access exception
+ * @throws IllegalArgumentException the illegal argument exception
* @throws InvocationTargetException the invocation target exception
- * @throws NoSuchMethodException the no such method exception
- * @throws SecurityException the security exception
+ * @throws NoSuchMethodException the no such method exception
+ * @throws SecurityException the security exception
*/
private void copySimpleProperty(String property, Introspector obj, Vertex v) {
final Object temp = getProperty(obj, property, v);
@@ -985,15 +1014,14 @@ public class DBSerializer {
}
}
-
/**
* Load the introspector from the hashmap for the given property key
*
* @param property - vertex property
- * @param obj - introspector object representing the vertex
- * @param hashMap - Containing a list of pre-fetched properties for a given vertex
+ * @param obj - introspector object representing the vertex
+ * @param hashMap - Containing a list of pre-fetched properties for a given vertex
*/
- private void copySimplePropertyFromHashMap(String property, Introspector obj, Map<String, Object> hashMap){
+ private void copySimplePropertyFromHashMap(String property, Introspector obj, Map<String, Object> hashMap) {
final Map<PropertyMetadata, String> metadata = obj.getPropertyMetadata(property);
String dbPropertyName = property;
@@ -1013,28 +1041,27 @@ public class DBSerializer {
* Simple db to object.
*
* @param obj the obj
- * @param v the v
- * @throws InstantiationException the instantiation exception
- * @throws IllegalAccessException the illegal access exception
- * @throws IllegalArgumentException the illegal argument exception
+ * @param v the v
+ * @throws InstantiationException the instantiation exception
+ * @throws IllegalAccessException the illegal access exception
+ * @throws IllegalArgumentException the illegal argument exception
* @throws InvocationTargetException the invocation target exception
- * @throws NoSuchMethodException the no such method exception
- * @throws SecurityException the security exception
+ * @throws NoSuchMethodException the no such method exception
+ * @throws SecurityException the security exception
*/
private void simpleDbToObject(Introspector obj, Vertex v) {
- for(String key : obj.getProperties()){
+ for (String key : obj.getProperties()) {
this.copySimpleProperty(key, obj, v);
}
}
-
- public Map<String, Object> convertVertexToHashMap(Introspector obj, Vertex v){
+ public Map<String, Object> convertVertexToHashMap(Introspector obj, Vertex v) {
long startTime = System.currentTimeMillis();
Set<String> simpleProperties = obj.getSimpleProperties(PropertyPredicates.isVisible());
- String[] simplePropsArray = new String[simpleProperties.size()];
- simplePropsArray = simpleProperties.toArray(simplePropsArray);
+ String[] simplePropsArray = new String[simpleProperties.size()];
+ simplePropsArray = simpleProperties.toArray(simplePropsArray);
Map<String, Object> simplePropsHashMap = new HashMap<>(simplePropsArray.length * 2);
@@ -1045,39 +1072,42 @@ public class DBSerializer {
public Introspector dbToRelationshipObject(Vertex v) throws UnsupportedEncodingException, AAIException {
Introspector relationshipList = this.latestLoader.introspectorFromName("relationship-list");
- relationshipList = createRelationshipList(v, relationshipList, "false");
+ relationshipList = createRelationshipList(v, relationshipList, "false");
return relationshipList;
}
+
/**
* Creates the relationship list.
*
- * @param v the v
- * @param obj the obj
+ * @param v the v
+ * @param obj the obj
* @param cleanUp the clean up
* @return the object
- * @throws InstantiationException the instantiation exception
- * @throws IllegalAccessException the illegal access exception
- * @throws IllegalArgumentException the illegal argument exception
- * @throws InvocationTargetException the invocation target exception
- * @throws NoSuchMethodException the no such method exception
- * @throws SecurityException the security exception
+ * @throws InstantiationException the instantiation exception
+ * @throws IllegalAccessException the illegal access exception
+ * @throws IllegalArgumentException the illegal argument exception
+ * @throws InvocationTargetException the invocation target exception
+ * @throws NoSuchMethodException the no such method exception
+ * @throws SecurityException the security exception
* @throws UnsupportedEncodingException the unsupported encoding exception
- * @throws AAIException the AAI exception
- * @throws MalformedURLException the malformed URL exception
+ * @throws AAIException the AAI exception
+ * @throws MalformedURLException the malformed URL exception
* @throws URISyntaxException
*/
- private Introspector createRelationshipList(Vertex v, Introspector obj, String cleanUp) throws UnsupportedEncodingException, AAIException {
+ private Introspector createRelationshipList(Vertex v, Introspector obj, String cleanUp)
+ throws UnsupportedEncodingException, AAIException {
String[] cousinRules = new String[0];
try {
cousinRules = edgeRules.retrieveCachedCousinLabels(obj.getDbName());
} catch (ExecutionException e) {
- LOGGER.warn("Encountered an execution exception while retrieving labels for the node type {} using cached", obj.getDbName(), e);
+ LOGGER.warn("Encountered an execution exception while retrieving labels for the node type {} using cached",
+ obj.getDbName(), e);
}
List<Vertex> cousins = null;
- if(cousinRules != null && cousinRules.length != 0){
+ if (cousinRules != null && cousinRules.length != 0) {
cousins = this.engine.getQueryEngine().findCousinVertices(v, cousinRules);
} else {
cousins = this.engine.getQueryEngine().findCousinVertices(v);
@@ -1086,7 +1116,7 @@ public class DBSerializer {
List<Object> relationshipObjList = obj.getValue("relationship");
VertexProperty nodeTypeProperty = v.property(AAIProperties.NODE_TYPE);
- if(!nodeTypeProperty.isPresent()){
+ if (!nodeTypeProperty.isPresent()) {
LoggingContext.responseDescription(MISSING_REQUIRED_NODE_PROPERTY);
LOGGER.warn("Not processing the vertex {} because its missing required property aai-node-type", v.id());
LoggingContext.remove(LoggingContext.LoggingField.RESPONSE_DESCRIPTION.toString());
@@ -1115,14 +1145,14 @@ public class DBSerializer {
for (Vertex cousin : cousins) {
VertexProperty vertexProperty = cousin.property(AAIProperties.NODE_TYPE);
String bNodeType = null;
- if(vertexProperty.isPresent()){
+ if (vertexProperty.isPresent()) {
bNodeType = cousin.property(AAIProperties.NODE_TYPE).value().toString();
} else {
// If the vertex is missing the aai-node-type
// Then its either a bad vertex or its in the process
// of getting deleted so we should ignore these vertexes
LoggingContext.responseDescription(MISSING_REQUIRED_NODE_PROPERTY);
- if(LOGGER.isDebugEnabled()){
+ if (LOGGER.isDebugEnabled()) {
LOGGER.debug("For the vertex {}, unable to retrieve the aai-node-type", v.id().toString());
} else {
LOGGER.info("Unable to retrieve the aai-node-type for vertex, for more info enable debug log");
@@ -1132,9 +1162,9 @@ public class DBSerializer {
}
if (obj.getVersion().compareTo(schemaVersions.getEdgeLabelVersion()) >= 0) {
String edgeKey = alphabetizer.buildAlphabetizedKey(aNodeType, bNodeType);
- if(keysWithMultipleLabels.contains(edgeKey)){
+ if (keysWithMultipleLabels.contains(edgeKey)) {
List<String> edgeLabels = this.getEdgeLabelsBetween(EdgeType.COUSIN, v, cousin);
- for(String edgeLabel: edgeLabels){
+ for (String edgeLabel : edgeLabels) {
Introspector relationshipObj = obj.newIntrospectorInstanceOfNestedProperty("relationship");
Object result = processEdgeRelationship(relationshipObj, cousin, cleanUp, edgeLabel);
if (result != null) {
@@ -1154,27 +1184,25 @@ public class DBSerializer {
// only for the older apis and the new apis if the edge rule
// is removed will not be seen in the newer version of the API
- EdgeRuleQuery ruleQuery = queryBuilder
- .to(bNodeType)
- .edgeType(EdgeType.COUSIN)
- .version(obj.getVersion())
- .build();
+ EdgeRuleQuery ruleQuery =
+ queryBuilder.to(bNodeType).edgeType(EdgeType.COUSIN).version(obj.getVersion()).build();
try {
edgeRule = edgeIngestor.getRule(ruleQuery);
} catch (EdgeRuleNotFoundException e) {
- LOGGER.warn("Caught an edge rule not found exception for query {}, {}," +
- " it could be the edge rule is no longer valid for the existing edge in db",
- ruleQuery, LogFormatTools.getStackTop(e));
+ LOGGER.warn(
+ "Caught an edge rule not found exception for query {}, {},"
+ + " it could be the edge rule is no longer valid for the existing edge in db",
+ ruleQuery, LogFormatTools.getStackTop(e));
continue;
} catch (AmbiguousRuleChoiceException e) {
- LOGGER.error("Caught an ambiguous rule not found exception for query {}, {}",
- ruleQuery, LogFormatTools.getStackTop(e));
+ LOGGER.error("Caught an ambiguous rule not found exception for query {}, {}", ruleQuery,
+ LogFormatTools.getStackTop(e));
continue;
}
Introspector relationshipObj = obj.newIntrospectorInstanceOfNestedProperty("relationship");
- Object result = processEdgeRelationship(relationshipObj, cousin, cleanUp,edgeRule.getLabel());
+ Object result = processEdgeRelationship(relationshipObj, cousin, cleanUp, edgeRule.getLabel());
if (result != null) {
relationshipObjList.add(result);
}
@@ -1200,26 +1228,27 @@ public class DBSerializer {
* Process edge relationship.
*
* @param relationshipObj the relationship obj
- * @param edge the edge
- * @param cleanUp the clean up
+ * @param edge the edge
+ * @param cleanUp the clean up
* @return the object
- * @throws InstantiationException the instantiation exception
- * @throws IllegalAccessException the illegal access exception
- * @throws IllegalArgumentException the illegal argument exception
- * @throws InvocationTargetException the invocation target exception
- * @throws NoSuchMethodException the no such method exception
- * @throws SecurityException the security exception
+ * @throws InstantiationException the instantiation exception
+ * @throws IllegalAccessException the illegal access exception
+ * @throws IllegalArgumentException the illegal argument exception
+ * @throws InvocationTargetException the invocation target exception
+ * @throws NoSuchMethodException the no such method exception
+ * @throws SecurityException the security exception
* @throws UnsupportedEncodingException the unsupported encoding exception
- * @throws AAIException the AAI exception
- * @throws MalformedURLException the malformed URL exception
+ * @throws AAIException the AAI exception
+ * @throws MalformedURLException the malformed URL exception
* @throws AAIUnknownObjectException
* @throws URISyntaxException
*/
- private Object processEdgeRelationship(Introspector relationshipObj, Vertex cousin, String cleanUp, String edgeLabel) throws UnsupportedEncodingException, AAIUnknownObjectException {
+ private Object processEdgeRelationship(Introspector relationshipObj, Vertex cousin, String cleanUp,
+ String edgeLabel) throws UnsupportedEncodingException, AAIUnknownObjectException {
VertexProperty aaiUriProperty = cousin.property("aai-uri");
- if(!aaiUriProperty.isPresent()){
+ if (!aaiUriProperty.isPresent()) {
return null;
}
@@ -1231,16 +1260,16 @@ public class DBSerializer {
uriParser = new URIToRelationshipObject(relationshipObj.getLoader(), uri, this.baseURL);
result = uriParser.getResult();
} catch (AAIException | URISyntaxException e) {
- LOGGER.error("Error while processing edge relationship in version " + relationshipObj.getVersion() + " (bad vertex ID=" + ": "
- + e.getMessage() + " " + LogFormatTools.getStackTop(e));
+ LOGGER.error("Error while processing edge relationship in version " + relationshipObj.getVersion()
+ + " (bad vertex ID=" + ": " + e.getMessage() + " " + LogFormatTools.getStackTop(e));
return null;
}
VertexProperty cousinVertexNodeType = cousin.property(AAIProperties.NODE_TYPE);
- if(cousinVertexNodeType.isPresent()){
+ if (cousinVertexNodeType.isPresent()) {
String cousinType = cousinVertexNodeType.value().toString();
- if(namedPropNodes.contains(cousinType)){
+ if (namedPropNodes.contains(cousinType)) {
this.addRelatedToProperty(result, cousin, cousinType);
}
}
@@ -1257,12 +1286,12 @@ public class DBSerializer {
*
* @param v the v
* @return the URI for vertex
- * @throws InstantiationException the instantiation exception
- * @throws IllegalAccessException the illegal access exception
- * @throws IllegalArgumentException the illegal argument exception
- * @throws InvocationTargetException the invocation target exception
- * @throws NoSuchMethodException the no such method exception
- * @throws SecurityException the security exception
+ * @throws InstantiationException the instantiation exception
+ * @throws IllegalAccessException the illegal access exception
+ * @throws IllegalArgumentException the illegal argument exception
+ * @throws InvocationTargetException the invocation target exception
+ * @throws NoSuchMethodException the no such method exception
+ * @throws SecurityException the security exception
* @throws UnsupportedEncodingException the unsupported encoding exception
* @throws AAIUnknownObjectException
*/
@@ -1301,15 +1330,17 @@ public class DBSerializer {
return UriBuilder.fromPath(uri).build();
}
- public void addRelatedToProperty(Introspector relationship, Vertex cousinVertex, String cousinType) throws AAIUnknownObjectException {
+ public void addRelatedToProperty(Introspector relationship, Vertex cousinVertex, String cousinType)
+ throws AAIUnknownObjectException {
Introspector obj = null;
try {
obj = this.loader.introspectorFromName(cousinType);
- } catch(AAIUnknownObjectException ex){
- if(LOGGER.isTraceEnabled()){
- LOGGER.trace("Encountered unknown object exception when trying to load nodetype of {} for vertex id {}", cousinType, cousinVertex.id());
+ } catch (AAIUnknownObjectException ex) {
+ if (LOGGER.isTraceEnabled()) {
+ LOGGER.trace("Encountered unknown object exception when trying to load nodetype of {} for vertex id {}",
+ cousinType, cousinVertex.id());
}
return;
}
@@ -1337,7 +1368,7 @@ public class DBSerializer {
}
- private Object getProperty(Introspector obj, String prop, Vertex vertex){
+ private Object getProperty(Introspector obj, String prop, Vertex vertex) {
final Map<PropertyMetadata, String> metadata = obj.getPropertyMetadata(prop);
String dbPropertyName = prop;
@@ -1353,12 +1384,13 @@ public class DBSerializer {
* Creates the edge.
*
* @param relationship the relationship
- * @param inputVertex the input vertex
+ * @param inputVertex the input vertex
* @return true, if successful
* @throws UnsupportedEncodingException the unsupported encoding exception
- * @throws AAIException the AAI exception
+ * @throws AAIException the AAI exception
*/
- public boolean createEdge(Introspector relationship, Vertex inputVertex) throws UnsupportedEncodingException, AAIException {
+ public boolean createEdge(Introspector relationship, Vertex inputVertex)
+ throws UnsupportedEncodingException, AAIException {
Vertex relatedVertex = null;
StopWatch.conditionalStart();
@@ -1372,12 +1404,13 @@ public class DBSerializer {
List<Vertex> results = parser.getQueryBuilder().toList();
if (results.isEmpty()) {
dbTimeMsecs += StopWatch.stopIfStarted();
- AAIException e = new AAIException("AAI_6129", "Node of type " + parser.getResultType() + ". Could not find object at: " + parser.getUri());
+ AAIException e = new AAIException("AAI_6129",
+ "Node of type " + parser.getResultType() + ". Could not find object at: " + parser.getUri());
e.getTemplateVars().add(parser.getResultType());
e.getTemplateVars().add(parser.getUri().toString());
throw e;
} else {
- //still an issue if there's more than one
+ // still an issue if there's more than one
relatedVertex = results.get(0);
}
@@ -1389,7 +1422,7 @@ public class DBSerializer {
if (e == null) {
edgeSer.addEdge(this.engine.asAdmin().getTraversalSource(), inputVertex, relatedVertex, label);
} else {
- //attempted to link two vertexes already linked
+ // attempted to link two vertexes already linked
}
} finally {
dbTimeMsecs += StopWatch.stopIfStarted();
@@ -1406,7 +1439,7 @@ public class DBSerializer {
* @param aVertex the out vertex
* @param bVertex the in vertex
* @return the edges between
- * @throws AAIException the AAI exception
+ * @throws AAIException the AAI exception
* @throws NoEdgeRuleFoundException
*/
private Edge getEdgeBetweenWithLabel(EdgeType type, Vertex aVertex, Vertex bVertex, EdgeRule edgeRule) {
@@ -1416,32 +1449,25 @@ public class DBSerializer {
if (bVertex != null) {
GraphTraversal<Vertex, Edge> findEdgesBetween = null;
if (EdgeType.TREE.equals(type)) {
- GraphTraversal<Vertex,Vertex> findVertex = this.engine.asAdmin().getTraversalSource().V(bVertex);
- if(edgeRule.getDirection().equals(Direction.IN)){
+ GraphTraversal<Vertex, Vertex> findVertex = this.engine.asAdmin().getTraversalSource().V(bVertex);
+ if (edgeRule.getDirection().equals(Direction.IN)) {
findEdgesBetween = findVertex.outE(edgeRule.getLabel())
- .has(EdgeProperty.CONTAINS.toString(), edgeRule.getContains())
- .not(
- __.has(EdgeField.PRIVATE.toString(), true)
- );
+ .has(EdgeProperty.CONTAINS.toString(), edgeRule.getContains())
+ .not(__.has(EdgeField.PRIVATE.toString(), true));
} else {
findEdgesBetween = findVertex.inE(edgeRule.getLabel())
- .has(EdgeProperty.CONTAINS.toString(), edgeRule.getContains())
- .not(
- __.has(EdgeField.PRIVATE.toString(), true)
- );
+ .has(EdgeProperty.CONTAINS.toString(), edgeRule.getContains())
+ .not(__.has(EdgeField.PRIVATE.toString(), true));
}
findEdgesBetween = findEdgesBetween.filter(__.otherV().hasId(aVertex.id())).limit(1);
} else {
findEdgesBetween = this.engine.asAdmin().getTraversalSource().V(aVertex).bothE(edgeRule.getLabel());
- findEdgesBetween = findEdgesBetween
- .has(EdgeProperty.CONTAINS.toString(), "NONE")
- .not(
- __.has(EdgeField.PRIVATE.toString(), true)
- );
+ findEdgesBetween = findEdgesBetween.has(EdgeProperty.CONTAINS.toString(), "NONE")
+ .not(__.has(EdgeField.PRIVATE.toString(), true));
findEdgesBetween = findEdgesBetween.filter(__.otherV().hasId(bVertex.id())).limit(1);
}
List<Edge> list = findEdgesBetween.toList();
- if(!list.isEmpty()){
+ if (!list.isEmpty()) {
result = list.get(0);
}
}
@@ -1455,7 +1481,7 @@ public class DBSerializer {
* @param aVertex the out vertex
* @param bVertex the in vertex
* @return the edges between
- * @throws AAIException the AAI exception
+ * @throws AAIException the AAI exception
* @throws NoEdgeRuleFoundException
*/
private List<Edge> getEdgesBetween(EdgeType type, Vertex aVertex, Vertex bVertex) {
@@ -1466,19 +1492,11 @@ public class DBSerializer {
GraphTraversal<Vertex, Edge> findEdgesBetween = null;
findEdgesBetween = this.engine.asAdmin().getTraversalSource().V(aVertex).bothE();
if (EdgeType.TREE.equals(type)) {
- findEdgesBetween = findEdgesBetween
- .not(
- __.or(
- __.has(EdgeProperty.CONTAINS.toString(), "NONE"),
- __.has(EdgeField.PRIVATE.toString(), true)
- )
- );
+ findEdgesBetween = findEdgesBetween.not(__.or(__.has(EdgeProperty.CONTAINS.toString(), "NONE"),
+ __.has(EdgeField.PRIVATE.toString(), true)));
} else {
- findEdgesBetween = findEdgesBetween
- .has(EdgeProperty.CONTAINS.toString(), "NONE")
- .not(
- __.has(EdgeField.PRIVATE.toString(), true)
- );
+ findEdgesBetween = findEdgesBetween.has(EdgeProperty.CONTAINS.toString(), "NONE")
+ .not(__.has(EdgeField.PRIVATE.toString(), true));
}
findEdgesBetween = findEdgesBetween.filter(__.otherV().hasId(bVertex.id()));
result = findEdgesBetween.toList();
@@ -1504,19 +1522,11 @@ public class DBSerializer {
GraphTraversal<Vertex, Edge> findEdgesBetween = null;
findEdgesBetween = this.engine.asAdmin().getTraversalSource().V(aVertex).bothE();
if (EdgeType.TREE.equals(type)) {
- findEdgesBetween = findEdgesBetween
- .not(
- __.or(
- __.has(EdgeProperty.CONTAINS.toString(), "NONE"),
- __.has(EdgeField.PRIVATE.toString(), true)
- )
- );
+ findEdgesBetween = findEdgesBetween.not(__.or(__.has(EdgeProperty.CONTAINS.toString(), "NONE"),
+ __.has(EdgeField.PRIVATE.toString(), true)));
} else {
- findEdgesBetween = findEdgesBetween
- .has(EdgeProperty.CONTAINS.toString(), "NONE")
- .not(
- __.has(EdgeField.PRIVATE.toString(), true)
- );
+ findEdgesBetween = findEdgesBetween.has(EdgeProperty.CONTAINS.toString(), "NONE")
+ .not(__.has(EdgeField.PRIVATE.toString(), true));
}
findEdgesBetween = findEdgesBetween.filter(__.otherV().hasId(bVertex.id()));
result = findEdgesBetween.label().toList();
@@ -1540,16 +1550,14 @@ public class DBSerializer {
if (bVertex != null) {
GraphTraversal<Vertex, Edge> findEdgesBetween = null;
findEdgesBetween = this.engine.asAdmin().getTraversalSource().V(aVertex).bothE();
- findEdgesBetween = findEdgesBetween
- .has(EdgeProperty.CONTAINS.toString(), "NONE")
- .not(
- __.has(EdgeField.PRIVATE.toString(), true)
- );
+ findEdgesBetween = findEdgesBetween.has(EdgeProperty.CONTAINS.toString(), "NONE")
+ .not(__.has(EdgeField.PRIVATE.toString(), true));
findEdgesBetween = findEdgesBetween.filter(__.otherV().hasId(bVertex.id()));
result = findEdgesBetween.count().next();
}
return result;
}
+
/**
* Gets all the edges between the vertexes with the label and type.
*
@@ -1588,7 +1596,7 @@ public class DBSerializer {
* @param bVertex the in vertex
* @param label
* @return the edge between
- * @throws AAIException the AAI exception
+ * @throws AAIException the AAI exception
* @throws NoEdgeRuleFoundException
*/
public Edge getEdgeBetween(EdgeType type, Vertex aVertex, Vertex bVertex, String label) throws AAIException {
@@ -1611,17 +1619,17 @@ public class DBSerializer {
return this.getEdgeBetween(type, aVertex, bVertex, null);
}
-
/**
* Delete edge.
*
* @param relationship the relationship
- * @param inputVertex the input vertex
+ * @param inputVertex the input vertex
* @return true, if successful
* @throws UnsupportedEncodingException the unsupported encoding exception
- * @throws AAIException the AAI exception
+ * @throws AAIException the AAI exception
*/
- public boolean deleteEdge(Introspector relationship, Vertex inputVertex) throws UnsupportedEncodingException, AAIException {
+ public boolean deleteEdge(Introspector relationship, Vertex inputVertex)
+ throws UnsupportedEncodingException, AAIException {
Vertex relatedVertex = null;
StopWatch.conditionalStart();
@@ -1707,7 +1715,7 @@ public class DBSerializer {
*
* @param vertices - list of vertices to delete from the graph
*/
- void delete(List<Vertex> vertices){
+ void delete(List<Vertex> vertices) {
StopWatch.conditionalStart();
for (Vertex v : vertices) {
@@ -1721,13 +1729,14 @@ public class DBSerializer {
/**
* Delete.
*
- * @param v the v
+ * @param v the v
* @param resourceVersion the resource version
* @throws IllegalArgumentException the illegal argument exception
- * @throws AAIException the AAI exception
- * @throws InterruptedException the interrupted exception
+ * @throws AAIException the AAI exception
+ * @throws InterruptedException the interrupted exception
*/
- public void delete(Vertex v, List<Vertex> deletableVertices, String resourceVersion, boolean enableResourceVersion) throws IllegalArgumentException, AAIException {
+ public void delete(Vertex v, List<Vertex> deletableVertices, String resourceVersion, boolean enableResourceVersion)
+ throws IllegalArgumentException, AAIException {
boolean result = verifyDeleteSemantics(v, resourceVersion, enableResourceVersion);
/*
@@ -1750,17 +1759,17 @@ public class DBSerializer {
}
-
/**
* Delete.
*
- * @param v the v
+ * @param v the v
* @param resourceVersion the resource version
* @throws IllegalArgumentException the illegal argument exception
- * @throws AAIException the AAI exception
- * @throws InterruptedException the interrupted exception
+ * @throws AAIException the AAI exception
+ * @throws InterruptedException the interrupted exception
*/
- public void delete(Vertex v, String resourceVersion, boolean enableResourceVersion) throws IllegalArgumentException, AAIException {
+ public void delete(Vertex v, String resourceVersion, boolean enableResourceVersion)
+ throws IllegalArgumentException, AAIException {
boolean result = verifyDeleteSemantics(v, resourceVersion, enableResourceVersion);
@@ -1779,18 +1788,20 @@ public class DBSerializer {
/**
* Verify delete semantics.
*
- * @param vertex the vertex
+ * @param vertex the vertex
* @param resourceVersion the resource version
* @return true, if successful
* @throws AAIException the AAI exception
*/
- private boolean verifyDeleteSemantics(Vertex vertex, String resourceVersion, boolean enableResourceVersion) throws AAIException {
+ private boolean verifyDeleteSemantics(Vertex vertex, String resourceVersion, boolean enableResourceVersion)
+ throws AAIException {
boolean result = true;
String nodeType = "";
String errorDetail = " unknown delete semantic found";
String aaiExceptionCode = "";
nodeType = vertex.<String>property(AAIProperties.NODE_TYPE).orElse(null);
- if (enableResourceVersion && !this.verifyResourceVersion("delete", nodeType, vertex.<String>property(AAIProperties.RESOURCE_VERSION).orElse(null), resourceVersion, nodeType)) {
+ if (enableResourceVersion && !this.verifyResourceVersion("delete", nodeType,
+ vertex.<String>property(AAIProperties.RESOURCE_VERSION).orElse(null), resourceVersion, nodeType)) {
}
List<Vertex> vertices = new ArrayList<Vertex>();
vertices.add(vertex);
@@ -1814,21 +1825,26 @@ public class DBSerializer {
StopWatch.conditionalStart();
/*
- * This takes in all the vertices in a cascade-delete-chain and checks if there is any edge with a "prevent-delete" condition
+ * This takes in all the vertices in a cascade-delete-chain and checks if there is any edge with a
+ * "prevent-delete" condition
* If yes - that should prevent the deletion of the vertex
* Dedup makes sure we dont capture the prevent-delete vertices twice
* The prevent-delete vertices are stored so that the error message displays what prevents the delete
*/
- List<Object> preventDeleteVertices = this.engine.asAdmin().getReadOnlyTraversalSource().V(vertices).
- union(__.inE().has(EdgeProperty.PREVENT_DELETE.toString(), AAIDirection.IN.toString()).outV().values(AAIProperties.NODE_TYPE),
- __.outE().has(EdgeProperty.PREVENT_DELETE.toString(), AAIDirection.OUT.toString()).inV().values(AAIProperties.NODE_TYPE))
- .dedup().toList();
+ List<Object> preventDeleteVertices = this.engine.asAdmin().getReadOnlyTraversalSource().V(vertices)
+ .union(__.inE().has(EdgeProperty.PREVENT_DELETE.toString(), AAIDirection.IN.toString()).outV()
+ .values(AAIProperties.NODE_TYPE),
+ __.outE().has(EdgeProperty.PREVENT_DELETE.toString(), AAIDirection.OUT.toString()).inV()
+ .values(AAIProperties.NODE_TYPE))
+ .dedup().toList();
dbTimeMsecs += StopWatch.stopIfStarted();
if (!preventDeleteVertices.isEmpty()) {
aaiExceptionCode = "AAI_6110";
- errorDetail = String.format("Object is being reference by additional objects preventing it from being deleted. Please clean up references from the following types %s", preventDeleteVertices);
+ errorDetail = String.format(
+ "Object is being reference by additional objects preventing it from being deleted. Please clean up references from the following types %s",
+ preventDeleteVertices);
result = false;
}
if (!result) {
@@ -1840,15 +1856,16 @@ public class DBSerializer {
/**
* Verify resource version.
*
- * @param action the action
- * @param nodeType the node type
+ * @param action the action
+ * @param nodeType the node type
* @param currentResourceVersion the current resource version
- * @param resourceVersion the resource version
- * @param uri the uri
+ * @param resourceVersion the resource version
+ * @param uri the uri
* @return true, if successful
* @throws AAIException the AAI exception
*/
- public boolean verifyResourceVersion(String action, String nodeType, String currentResourceVersion, String resourceVersion, String uri) throws AAIException {
+ public boolean verifyResourceVersion(String action, String nodeType, String currentResourceVersion,
+ String resourceVersion, String uri) throws AAIException {
String enabled = "";
String errorDetail = "";
String aaiExceptionCode = "";
@@ -1870,7 +1887,8 @@ public class DBSerializer {
if ("delete".equals(action)) {
isDeleteResourceVersionOk = verifyResourceVersionForDelete(currentResourceVersion, resourceVersion);
}
- if ((!isDeleteResourceVersionOk) || ((!"delete".equals(action)) && (!currentResourceVersion.equals(resourceVersion)))) {
+ if ((!isDeleteResourceVersionOk)
+ || ((!"delete".equals(action)) && (!currentResourceVersion.equals(resourceVersion)))) {
if ("create".equals(action) && !resourceVersion.equals("")) {
errorDetail = "resource-version passed for " + action + " of " + uri;
aaiExceptionCode = "AAI_6135";
@@ -1893,16 +1911,17 @@ public class DBSerializer {
* Verify resource version for delete.
*
* @param currentResourceVersion the current resource version
- * @param resourceVersion the resource version
+ * @param resourceVersion the resource version
* @return true, if successful or false if there is a mismatch
*/
private boolean verifyResourceVersionForDelete(String currentResourceVersion, String resourceVersion) {
boolean isDeleteResourceVersionOk = true;
String resourceVersionDisabledUuid = AAIConfig.get(AAIConstants.AAI_RESVERSION_DISABLED_UUID,
- AAIConstants.AAI_RESVERSION_DISABLED_UUID_DEFAULT);
+ AAIConstants.AAI_RESVERSION_DISABLED_UUID_DEFAULT);
- if ((!currentResourceVersion.equals(resourceVersion)) && (!resourceVersion.equals(resourceVersionDisabledUuid))) {
+ if ((!currentResourceVersion.equals(resourceVersion))
+ && (!resourceVersion.equals(resourceVersionDisabledUuid))) {
isDeleteResourceVersionOk = false;
}
return isDeleteResourceVersionOk;
@@ -1939,24 +1958,24 @@ public class DBSerializer {
private void executePreSideEffects(Introspector obj, Vertex self) throws AAIException {
- SideEffectRunner runner = new SideEffectRunner
- .Builder(this.engine, this).addSideEffect(DataCopy.class).addSideEffect(PrivateEdge.class).build();
+ SideEffectRunner runner = new SideEffectRunner.Builder(this.engine, this).addSideEffect(DataCopy.class)
+ .addSideEffect(PrivateEdge.class).build();
runner.execute(obj, self);
}
private void executePostSideEffects(Introspector obj, Vertex self) throws AAIException {
- SideEffectRunner runner = new SideEffectRunner
- .Builder(this.engine, this).addSideEffect(DataLinkWriter.class).build();
+ SideEffectRunner runner =
+ new SideEffectRunner.Builder(this.engine, this).addSideEffect(DataLinkWriter.class).build();
runner.execute(obj, self);
}
private void enrichData(Introspector obj, Vertex self) throws AAIException {
- SideEffectRunner runner = new SideEffectRunner
- .Builder(this.engine, this).addSideEffect(DataLinkReader.class).build();
+ SideEffectRunner runner =
+ new SideEffectRunner.Builder(this.engine, this).addSideEffect(DataLinkReader.class).build();
runner.execute(obj, self);
}
@@ -1970,26 +1989,28 @@ public class DBSerializer {
* This is for a one-time run with Tenant Isloation to only filter relationships
* TODO: Chnage the original dbToObject to take filter parent/cousins
*
- * @param obj the obj
- * @param v the vertex from the graph
- * @param depth the depth
- * @param nodeOnly specify if to exclude relationships or not
+ * @param obj the obj
+ * @param v the vertex from the graph
+ * @param depth the depth
+ * @param nodeOnly specify if to exclude relationships or not
* @param filterCousinNodes
* @return the introspector
- * @throws AAIException the AAI exception
- * @throws IllegalAccessException the illegal access exception
- * @throws IllegalArgumentException the illegal argument exception
- * @throws InvocationTargetException the invocation target exception
- * @throws SecurityException the security exception
- * @throws InstantiationException the instantiation exception
- * @throws NoSuchMethodException the no such method exception
+ * @throws AAIException the AAI exception
+ * @throws IllegalAccessException the illegal access exception
+ * @throws IllegalArgumentException the illegal argument exception
+ * @throws InvocationTargetException the invocation target exception
+ * @throws SecurityException the security exception
+ * @throws InstantiationException the instantiation exception
+ * @throws NoSuchMethodException the no such method exception
* @throws UnsupportedEncodingException the unsupported encoding exception
- * @throws MalformedURLException the malformed URL exception
+ * @throws MalformedURLException the malformed URL exception
* @throws AAIUnknownObjectException
* @throws URISyntaxException
*/
- //TODO - See if you can merge the 2 dbToObjectWithFilters
- public Introspector dbToObjectWithFilters(Introspector obj, Vertex v, Set<Vertex> seen, int depth, boolean nodeOnly, List<String> filterCousinNodes, List<String> filterParentNodes) throws AAIException, UnsupportedEncodingException {
+ // TODO - See if you can merge the 2 dbToObjectWithFilters
+ public Introspector dbToObjectWithFilters(Introspector obj, Vertex v, Set<Vertex> seen, int depth, boolean nodeOnly,
+ List<String> filterCousinNodes, List<String> filterParentNodes)
+ throws AAIException, UnsupportedEncodingException {
String cleanUp = "false";
if (depth < 0) {
return null;
@@ -2010,7 +2031,8 @@ public class DBSerializer {
if (!property.equals("relationship-list") && depth >= 0) {
Introspector argumentObject = obj.newIntrospectorInstanceOfProperty(property);
- Object result = dbToObjectWithFilters(argumentObject, v, seen, depth + 1, nodeOnly, filterCousinNodes, filterParentNodes);
+ Object result = dbToObjectWithFilters(argumentObject, v, seen, depth + 1, nodeOnly,
+ filterCousinNodes, filterParentNodes);
if (result != null) {
obj.setValue(property, argumentObject.getUnderlyingObject());
modified = true;
@@ -2018,7 +2040,8 @@ public class DBSerializer {
} else if (property.equals("relationship-list") && !nodeOnly) {
/* relationships need to be handled correctly */
Introspector relationshipList = obj.newIntrospectorInstanceOfProperty(property);
- relationshipList = createFilteredRelationshipList(v, relationshipList, cleanUp, filterCousinNodes);
+ relationshipList =
+ createFilteredRelationshipList(v, relationshipList, cleanUp, filterCousinNodes);
if (relationshipList != null) {
modified = true;
obj.setValue(property, relationshipList.getUnderlyingObject());
@@ -2037,7 +2060,8 @@ public class DBSerializer {
String vType = v.<String>property(AAIProperties.NODE_TYPE).orElse(null);
EdgeRule rule;
- boolean isthisParentRequired = filterParentNodes.parallelStream().anyMatch(childDbName::contains);
+ boolean isthisParentRequired =
+ filterParentNodes.parallelStream().anyMatch(childDbName::contains);
EdgeRuleQuery q = new EdgeRuleQuery.Builder(vType, childDbName).edgeType(EdgeType.TREE).build();
@@ -2049,7 +2073,8 @@ public class DBSerializer {
throw new MultipleEdgeRuleFoundException(e);
}
if (!rule.getContains().equals(AAIDirection.NONE.toString()) && isthisParentRequired) {
- //vertices = this.queryEngine.findRelatedVertices(v, Direction.OUT, rule.getLabel(), childDbName);
+ // vertices = this.queryEngine.findRelatedVertices(v, Direction.OUT, rule.getLabel(),
+ // childDbName);
Direction ruleDirection = rule.getDirection();
Iterator<Vertex> itr = v.vertices(ruleDirection, rule.getLabel());
List<Vertex> verticesList = (List<Vertex>) IteratorUtils.toList(itr);
@@ -2066,7 +2091,8 @@ public class DBSerializer {
if (!seen.contains(childVertex)) {
Introspector argumentObject = obj.newIntrospectorInstanceOfNestedProperty(property);
- Object result = dbToObjectWithFilters(argumentObject, childVertex, seen, depth, nodeOnly, filterCousinNodes, filterParentNodes);
+ Object result = dbToObjectWithFilters(argumentObject, childVertex, seen, depth,
+ nodeOnly, filterCousinNodes, filterParentNodes);
if (result != null) {
getList.add(argumentObject.getUnderlyingObject());
}
@@ -2074,11 +2100,12 @@ public class DBSerializer {
processed++;
} else {
removed++;
- LOGGER.warn("Cycle found while serializing vertex id={}", childVertex.id().toString());
+ LOGGER.warn("Cycle found while serializing vertex id={}",
+ childVertex.id().toString());
}
}
if (processed == 0) {
- //vertices were all seen, reset the list
+ // vertices were all seen, reset the list
getList = null;
}
if (processed > 0) {
@@ -2100,7 +2127,7 @@ public class DBSerializer {
}
}
- //no changes were made to this obj, discard the instance
+ // no changes were made to this obj, discard the instance
if (!modified) {
return null;
}
@@ -2112,22 +2139,23 @@ public class DBSerializer {
/**
* Creates the relationship list with the filtered node types.
*
- * @param v the v
- * @param obj the obj
+ * @param v the v
+ * @param obj the obj
* @param cleanUp the clean up
* @return the object
- * @throws InstantiationException the instantiation exception
- * @throws IllegalAccessException the illegal access exception
- * @throws IllegalArgumentException the illegal argument exception
- * @throws InvocationTargetException the invocation target exception
- * @throws NoSuchMethodException the no such method exception
- * @throws SecurityException the security exception
+ * @throws InstantiationException the instantiation exception
+ * @throws IllegalAccessException the illegal access exception
+ * @throws IllegalArgumentException the illegal argument exception
+ * @throws InvocationTargetException the invocation target exception
+ * @throws NoSuchMethodException the no such method exception
+ * @throws SecurityException the security exception
* @throws UnsupportedEncodingException the unsupported encoding exception
- * @throws AAIException the AAI exception
- * @throws MalformedURLException the malformed URL exception
+ * @throws AAIException the AAI exception
+ * @throws MalformedURLException the malformed URL exception
* @throws URISyntaxException
*/
- private Introspector createFilteredRelationshipList(Vertex v, Introspector obj, String cleanUp, List<String> filterNodes) throws UnsupportedEncodingException, AAIException {
+ private Introspector createFilteredRelationshipList(Vertex v, Introspector obj, String cleanUp,
+ List<String> filterNodes) throws UnsupportedEncodingException, AAIException {
List<Vertex> allCousins = this.engine.getQueryEngine().findCousinVertices(v);
Iterator<Vertex> cousinVertices = allCousins.stream().filter(item -> {
@@ -2135,10 +2163,9 @@ public class DBSerializer {
return filterNodes.parallelStream().anyMatch(node::contains);
}).iterator();
-
List<Vertex> cousins = (List<Vertex>) IteratorUtils.toList(cousinVertices);
- //items.parallelStream().anyMatch(inputStr::contains)
+ // items.parallelStream().anyMatch(inputStr::contains)
List<Object> relationshipObjList = obj.getValue("relationship");
for (Vertex cousin : cousins) {
@@ -2148,7 +2175,6 @@ public class DBSerializer {
relationshipObjList.add(result);
}
-
}
if (relationshipObjList.isEmpty()) {
diff --git a/aai-core/src/main/java/org/onap/aai/serialization/db/DeleteSemantic.java b/aai-core/src/main/java/org/onap/aai/serialization/db/DeleteSemantic.java
index abaa8763..caa64caa 100644
--- a/aai-core/src/main/java/org/onap/aai/serialization/db/DeleteSemantic.java
+++ b/aai-core/src/main/java/org/onap/aai/serialization/db/DeleteSemantic.java
@@ -17,23 +17,18 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-package org.onap.aai.serialization.db;
+package org.onap.aai.serialization.db;
/**
- * Possible values for deleteScope can be:
- * USE_DEFAULT - Get the scope from ref data for this node
- * THIS_NODE_ONLY (but should fail if it there are nodes that depend on it for uniqueness)
- * CASCADE_TO_CHILDREN - will look for OUT-Edges that have parentOf/hasDelTarget = true and follow those down
- * ERROR_4_IN_EDGES_OR_CASCADE - combo of error-if-any-IN-edges + CascadeToChildren
- * ERROR_IF_ANY_IN_EDGES - Fail if this node has any existing IN edges
- * ERROR_IF_ANY_EDGES - Fail if this node has any existing edges at all!
+ * Possible values for deleteScope can be:
+ * USE_DEFAULT - Get the scope from ref data for this node
+ * THIS_NODE_ONLY (but should fail if it there are nodes that depend on it for uniqueness)
+ * CASCADE_TO_CHILDREN - will look for OUT-Edges that have parentOf/hasDelTarget = true and follow those down
+ * ERROR_4_IN_EDGES_OR_CASCADE - combo of error-if-any-IN-edges + CascadeToChildren
+ * ERROR_IF_ANY_IN_EDGES - Fail if this node has any existing IN edges
+ * ERROR_IF_ANY_EDGES - Fail if this node has any existing edges at all!
*/
public enum DeleteSemantic {
- USE_DEFAULT,
- THIS_NODE_ONLY,
- CASCADE_TO_CHILDREN,
- ERROR_4_IN_EDGES_OR_CASCADE,
- ERROR_IF_ANY_IN_EDGES,
- ERROR_IF_ANY_EDGES,
+ USE_DEFAULT, THIS_NODE_ONLY, CASCADE_TO_CHILDREN, ERROR_4_IN_EDGES_OR_CASCADE, ERROR_IF_ANY_IN_EDGES, ERROR_IF_ANY_EDGES,
}
diff --git a/aai-core/src/main/java/org/onap/aai/serialization/db/EdgeProperties.java b/aai-core/src/main/java/org/onap/aai/serialization/db/EdgeProperties.java
index c8340a7c..e460a270 100644
--- a/aai-core/src/main/java/org/onap/aai/serialization/db/EdgeProperties.java
+++ b/aai-core/src/main/java/org/onap/aai/serialization/db/EdgeProperties.java
@@ -17,28 +17,29 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.serialization.db;
import org.onap.aai.edges.enums.EdgeProperty;
public class EdgeProperties {
- public static String out(EdgeProperty prop) {
+ public static String out(EdgeProperty prop) {
+
+ return out(prop.toString());
+ }
- return out(prop.toString());
- }
+ public static String in(EdgeProperty prop) {
+ return in(prop.toString());
+ }
- public static String in(EdgeProperty prop) {
- return in(prop.toString());
- }
-
- public static String out(String prop) {
+ public static String out(String prop) {
- return prop;
- }
+ return prop;
+ }
- public static String in(String prop) {
- return prop + "-REV";
- }
+ public static String in(String prop) {
+ return prop + "-REV";
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/serialization/db/EdgePropertyMap.java b/aai-core/src/main/java/org/onap/aai/serialization/db/EdgePropertyMap.java
index a6838848..777ddd87 100644
--- a/aai-core/src/main/java/org/onap/aai/serialization/db/EdgePropertyMap.java
+++ b/aai-core/src/main/java/org/onap/aai/serialization/db/EdgePropertyMap.java
@@ -17,42 +17,42 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-package org.onap.aai.serialization.db;
-import org.apache.tinkerpop.gremlin.structure.Direction;
+package org.onap.aai.serialization.db;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
+import org.apache.tinkerpop.gremlin.structure.Direction;
+
public class EdgePropertyMap<K, V> extends HashMap<K, V> {
- private static final long serialVersionUID = -8298355506617458683L;
-
- private static final Pattern variablePattern = Pattern.compile("(!)?\\$\\{(\\w+)\\}");
-
- @Override
- public V get(Object arg0) {
-
- V value = super.get(arg0);
-
- Matcher m = variablePattern.matcher(value.toString());
- if (m.find()) {
- if (m.groupCount() == 2) {
- if (m.group(1) == null) {
- value = super.get(m.group(2));
- } else {
- value = reverse(super.get(m.group(2)));
- }
- }
- }
-
- return value;
- }
-
-
- protected V reverse(V value) {
-
- return (V)Direction.valueOf(value.toString()).opposite().toString();
- }
+ private static final long serialVersionUID = -8298355506617458683L;
+
+ private static final Pattern variablePattern = Pattern.compile("(!)?\\$\\{(\\w+)\\}");
+
+ @Override
+ public V get(Object arg0) {
+
+ V value = super.get(arg0);
+
+ Matcher m = variablePattern.matcher(value.toString());
+ if (m.find()) {
+ if (m.groupCount() == 2) {
+ if (m.group(1) == null) {
+ value = super.get(m.group(2));
+ } else {
+ value = reverse(super.get(m.group(2)));
+ }
+ }
+ }
+
+ return value;
+ }
+
+ protected V reverse(V value) {
+
+ return (V) Direction.valueOf(value.toString()).opposite().toString();
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/serialization/db/EdgeSerializer.java b/aai-core/src/main/java/org/onap/aai/serialization/db/EdgeSerializer.java
index d4a2b51b..a5a08203 100644
--- a/aai-core/src/main/java/org/onap/aai/serialization/db/EdgeSerializer.java
+++ b/aai-core/src/main/java/org/onap/aai/serialization/db/EdgeSerializer.java
@@ -17,13 +17,14 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.serialization.db;
import java.util.EnumMap;
import java.util.Map;
+import java.util.Map.Entry;
import java.util.Optional;
import java.util.UUID;
-import java.util.Map.Entry;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.structure.Direction;
@@ -49,224 +50,236 @@ import org.springframework.stereotype.Component;
@Component
public class EdgeSerializer {
- @Autowired
- private EdgeIngestor edgerules;
-
- public EdgeSerializer(EdgeIngestor ei) {
- this.edgerules = ei;
- }
-
- /**
- * Adds the tree edge.
- *
- * @param aVertex the out vertex
- * @param bVertex the in vertex
- * @return the edge
- * @throws AAIException the AAI exception
- */
- public Edge addTreeEdge(GraphTraversalSource traversalSource, Vertex aVertex, Vertex bVertex) throws AAIException {
- return this.addEdge(EdgeType.TREE, traversalSource, aVertex, bVertex, false, null);
- }
-
- /**
- * Adds the edge.
- *
- * @param aVertex the out vertex
- * @param bVertex the in vertex
- * @return the edge
- * @throws AAIException the AAI exception
- */
- public Edge addEdge(GraphTraversalSource traversalSource, Vertex aVertex, Vertex bVertex) throws AAIException {
- return this.addEdge(traversalSource, aVertex, bVertex, null);
- }
-
- public Edge addEdge(GraphTraversalSource traversalSource, Vertex aVertex, Vertex bVertex, String label) throws AAIException {
- return this.addEdge(EdgeType.COUSIN, traversalSource, aVertex, bVertex, false, label);
- }
-
- public Edge addPrivateEdge(GraphTraversalSource traversalSource, Vertex aVertex, Vertex bVertex, String label) throws AAIException, EdgeRuleNotFoundException, AmbiguousRuleChoiceException {
- return this.addEdge(EdgeType.COUSIN, traversalSource, aVertex, bVertex, false, label, true);
- }
-
- private Edge addEdge(EdgeType type, GraphTraversalSource traversalSource, Vertex aVertex, Vertex bVertex, boolean isBestEffort, String label, boolean isPrivateEdge) throws AAIException, EdgeRuleNotFoundException, AmbiguousRuleChoiceException {
-
- EdgeRule rule = null;
-
- String aType = aVertex.<String>property(AAIProperties.NODE_TYPE).orElse(null);
- String bType = bVertex.<String>property(AAIProperties.NODE_TYPE).orElse(null);
- EdgeRuleQuery edgeQuery = new EdgeRuleQuery.Builder(aType, bType).label(label).setPrivate(isPrivateEdge).build();
-
- rule = edgerules.getRule(edgeQuery);
-
- if(rule.isPrivateEdge() != isPrivateEdge){
- return null;
- }
-
- Edge e = null;
-
- Optional<String> message = this.validateMultiplicity(rule, traversalSource, aVertex, bVertex);
-
- if (message.isPresent() && !isBestEffort) {
- throw new EdgeMultiplicityException(message.get());
- }
- if (!message.isPresent()) {
- if (rule.getDirection().equals(Direction.OUT)) {
- e = aVertex.addEdge(rule.getLabel(), bVertex);
- } else if (rule.getDirection().equals(Direction.IN)) {
- e = bVertex.addEdge(rule.getLabel(), aVertex);
- }
-
- this.addProperties(e, rule);
- }
- return e;
- }
-
- /**
- * Adds the tree edge.
- *
- * @param aVertex the out vertex
- * @param bVertex the in vertex
- * @return the edge
- * @throws AAIException the AAI exception
- */
- public Edge addTreeEdgeIfPossible(GraphTraversalSource traversalSource, Vertex aVertex, Vertex bVertex) throws AAIException {
- return this.addEdge(EdgeType.TREE, traversalSource, aVertex, bVertex, true, null);
- }
-
- /**
- * Adds the edge.
- *
- * @param aVertex the out vertex
- * @param bVertex the in vertex
- * @return the edge
- * @throws AAIException the AAI exception
- */
- public Edge addEdgeIfPossible(GraphTraversalSource traversalSource, Vertex aVertex, Vertex bVertex) throws AAIException {
- return this.addEdgeIfPossible(traversalSource, aVertex, bVertex, null);
- }
-
- public Edge addEdgeIfPossible(GraphTraversalSource traversalSource, Vertex aVertex, Vertex bVertex, String label) throws AAIException {
- return this.addEdge(EdgeType.COUSIN, traversalSource, aVertex, bVertex, true, label);
- }
-
- /**
- * Adds the edge.
- *
- * @param type the type
- * @param aVertex the out vertex
- * @param bVertex the in vertex
- * @return the edge
- * @throws AAIException the AAI exception
- */
- private Edge addEdge(EdgeType type, GraphTraversalSource traversalSource, Vertex aVertex, Vertex bVertex, boolean isBestEffort, String label) throws AAIException {
- String aNodeType = (String)aVertex.property(AAIProperties.NODE_TYPE).value();
- String bNodeType = (String)bVertex.property(AAIProperties.NODE_TYPE).value();
- EdgeRuleQuery q = new EdgeRuleQuery.Builder(aNodeType, bNodeType).label(label).edgeType(type).build();
- EdgeRule rule;
- try {
- rule = edgerules.getRule(q);
- } catch (EdgeRuleNotFoundException e1) {
- throw new NoEdgeRuleFoundException(e1);
- } catch (AmbiguousRuleChoiceException e1) {
- throw new MultipleEdgeRuleFoundException(e1);
- }
-
- Edge e = null;
-
- Optional<String> message = this.validateMultiplicity(rule, traversalSource, aVertex, bVertex);
-
- if (message.isPresent() && !isBestEffort) {
- throw new EdgeMultiplicityException(message.get());
- }
- if (!message.isPresent()) {
- if (rule.getDirection().equals(Direction.OUT)) {
- e = aVertex.addEdge(rule.getLabel(), bVertex);
- } else if (rule.getDirection().equals(Direction.IN)) {
- e = bVertex.addEdge(rule.getLabel(), aVertex);
- }
-
- this.addProperties(e, rule);
- }
- return e;
- }
-
- /**
- * Adds the properties.
- *
- * @param edge the edge
- * @param rule the rule
- */
- public void addProperties(Edge edge, EdgeRule rule) {
- Map<EdgeProperty, String> propMap = new EnumMap<>(EdgeProperty.class);
- propMap.put(EdgeProperty.CONTAINS, rule.getContains());
- propMap.put(EdgeProperty.DELETE_OTHER_V, rule.getDeleteOtherV());
- propMap.put(EdgeProperty.PREVENT_DELETE, rule.getPreventDelete());
-
- for (Entry<EdgeProperty, String> entry : propMap.entrySet()) {
- edge.property(entry.getKey().toString(), entry.getValue());
- }
-
- edge.property(EdgeField.PRIVATE.toString(), rule.isPrivateEdge());
- edge.property(AAIProperties.AAI_UUID, UUID.randomUUID().toString());
- }
-
- /**
- * Validate multiplicity.
- *
- * @param rule the rule
- * @param aVertex the out vertex
- * @param bVertex the in vertex
- * @return true, if successful
- * @throws AAIException the AAI exception
- */
- private Optional<String> validateMultiplicity(EdgeRule rule, GraphTraversalSource traversalSource, Vertex aVertex, Vertex bVertex) {
-
- Vertex a = aVertex;
- Vertex b = bVertex;
-
- if (rule.getDirection().equals(Direction.OUT)) {
- a = aVertex;
- b = bVertex;
- } else if (rule.getDirection().equals(Direction.IN)) {
- a = bVertex;
- b = aVertex;
- }
-
- String aVertexType = a.<String>property(AAIProperties.NODE_TYPE).orElse(null);
- String bVertexType = b.<String>property(AAIProperties.NODE_TYPE).orElse(null);
- String label = rule.getLabel();
-
- MultiplicityRule multiplicityRule = rule.getMultiplicityRule();
-
- String detail = "";
- final String msg = "multiplicity rule violated: only one edge can exist with label: ";
-
- if (multiplicityRule.equals(MultiplicityRule.ONE2ONE)) {
- Long outEdgesCnt = traversalSource.V(a).out(label).has(AAIProperties.NODE_TYPE, bVertexType).count().next();
- Long inEdgesCnt = traversalSource.V(b).in(label).has(AAIProperties.NODE_TYPE, aVertexType).count().next();
- if (aVertexType.equals(bVertexType)) {
- inEdgesCnt = inEdgesCnt + traversalSource.V(a).in(label).has(AAIProperties.NODE_TYPE, aVertexType).count().next();
- outEdgesCnt = outEdgesCnt + traversalSource.V(b).out(label).has(AAIProperties.NODE_TYPE, bVertexType).count().next();
- }
- if ( (inEdgesCnt != 0) || (outEdgesCnt != 0) ) {
- detail = msg + label + " between " + aVertexType + " and " + bVertexType;
- }
- } else if (multiplicityRule.equals(MultiplicityRule.ONE2MANY)) {
- Long inEdgesCnt = traversalSource.V(b).in(label).has(AAIProperties.NODE_TYPE, aVertexType).count().next();
- if (inEdgesCnt != 0) {
- detail = msg + label + " between " + aVertexType + " and " + bVertexType;
- }
- } else if (multiplicityRule.equals(MultiplicityRule.MANY2ONE)) {
- Long outEdgesCnt = traversalSource.V(a).out(label).has(AAIProperties.NODE_TYPE, bVertexType).count().next();
- if (outEdgesCnt != 0) {
- detail = msg + label + " between " + aVertexType + " and " + bVertexType;
- }
- }
-
- if (!"".equals(detail)) {
- return Optional.of(detail);
- } else {
- return Optional.empty();
- }
- }
+ @Autowired
+ private EdgeIngestor edgerules;
+
+ public EdgeSerializer(EdgeIngestor ei) {
+ this.edgerules = ei;
+ }
+
+ /**
+ * Adds the tree edge.
+ *
+ * @param aVertex the out vertex
+ * @param bVertex the in vertex
+ * @return the edge
+ * @throws AAIException the AAI exception
+ */
+ public Edge addTreeEdge(GraphTraversalSource traversalSource, Vertex aVertex, Vertex bVertex) throws AAIException {
+ return this.addEdge(EdgeType.TREE, traversalSource, aVertex, bVertex, false, null);
+ }
+
+ /**
+ * Adds the edge.
+ *
+ * @param aVertex the out vertex
+ * @param bVertex the in vertex
+ * @return the edge
+ * @throws AAIException the AAI exception
+ */
+ public Edge addEdge(GraphTraversalSource traversalSource, Vertex aVertex, Vertex bVertex) throws AAIException {
+ return this.addEdge(traversalSource, aVertex, bVertex, null);
+ }
+
+ public Edge addEdge(GraphTraversalSource traversalSource, Vertex aVertex, Vertex bVertex, String label)
+ throws AAIException {
+ return this.addEdge(EdgeType.COUSIN, traversalSource, aVertex, bVertex, false, label);
+ }
+
+ public Edge addPrivateEdge(GraphTraversalSource traversalSource, Vertex aVertex, Vertex bVertex, String label)
+ throws AAIException, EdgeRuleNotFoundException, AmbiguousRuleChoiceException {
+ return this.addEdge(EdgeType.COUSIN, traversalSource, aVertex, bVertex, false, label, true);
+ }
+
+ private Edge addEdge(EdgeType type, GraphTraversalSource traversalSource, Vertex aVertex, Vertex bVertex,
+ boolean isBestEffort, String label, boolean isPrivateEdge)
+ throws AAIException, EdgeRuleNotFoundException, AmbiguousRuleChoiceException {
+
+ EdgeRule rule = null;
+
+ String aType = aVertex.<String>property(AAIProperties.NODE_TYPE).orElse(null);
+ String bType = bVertex.<String>property(AAIProperties.NODE_TYPE).orElse(null);
+ EdgeRuleQuery edgeQuery =
+ new EdgeRuleQuery.Builder(aType, bType).label(label).setPrivate(isPrivateEdge).build();
+
+ rule = edgerules.getRule(edgeQuery);
+
+ if (rule.isPrivateEdge() != isPrivateEdge) {
+ return null;
+ }
+
+ Edge e = null;
+
+ Optional<String> message = this.validateMultiplicity(rule, traversalSource, aVertex, bVertex);
+
+ if (message.isPresent() && !isBestEffort) {
+ throw new EdgeMultiplicityException(message.get());
+ }
+ if (!message.isPresent()) {
+ if (rule.getDirection().equals(Direction.OUT)) {
+ e = aVertex.addEdge(rule.getLabel(), bVertex);
+ } else if (rule.getDirection().equals(Direction.IN)) {
+ e = bVertex.addEdge(rule.getLabel(), aVertex);
+ }
+
+ this.addProperties(e, rule);
+ }
+ return e;
+ }
+
+ /**
+ * Adds the tree edge.
+ *
+ * @param aVertex the out vertex
+ * @param bVertex the in vertex
+ * @return the edge
+ * @throws AAIException the AAI exception
+ */
+ public Edge addTreeEdgeIfPossible(GraphTraversalSource traversalSource, Vertex aVertex, Vertex bVertex)
+ throws AAIException {
+ return this.addEdge(EdgeType.TREE, traversalSource, aVertex, bVertex, true, null);
+ }
+
+ /**
+ * Adds the edge.
+ *
+ * @param aVertex the out vertex
+ * @param bVertex the in vertex
+ * @return the edge
+ * @throws AAIException the AAI exception
+ */
+ public Edge addEdgeIfPossible(GraphTraversalSource traversalSource, Vertex aVertex, Vertex bVertex)
+ throws AAIException {
+ return this.addEdgeIfPossible(traversalSource, aVertex, bVertex, null);
+ }
+
+ public Edge addEdgeIfPossible(GraphTraversalSource traversalSource, Vertex aVertex, Vertex bVertex, String label)
+ throws AAIException {
+ return this.addEdge(EdgeType.COUSIN, traversalSource, aVertex, bVertex, true, label);
+ }
+
+ /**
+ * Adds the edge.
+ *
+ * @param type the type
+ * @param aVertex the out vertex
+ * @param bVertex the in vertex
+ * @return the edge
+ * @throws AAIException the AAI exception
+ */
+ private Edge addEdge(EdgeType type, GraphTraversalSource traversalSource, Vertex aVertex, Vertex bVertex,
+ boolean isBestEffort, String label) throws AAIException {
+ String aNodeType = (String) aVertex.property(AAIProperties.NODE_TYPE).value();
+ String bNodeType = (String) bVertex.property(AAIProperties.NODE_TYPE).value();
+ EdgeRuleQuery q = new EdgeRuleQuery.Builder(aNodeType, bNodeType).label(label).edgeType(type).build();
+ EdgeRule rule;
+ try {
+ rule = edgerules.getRule(q);
+ } catch (EdgeRuleNotFoundException e1) {
+ throw new NoEdgeRuleFoundException(e1);
+ } catch (AmbiguousRuleChoiceException e1) {
+ throw new MultipleEdgeRuleFoundException(e1);
+ }
+
+ Edge e = null;
+
+ Optional<String> message = this.validateMultiplicity(rule, traversalSource, aVertex, bVertex);
+
+ if (message.isPresent() && !isBestEffort) {
+ throw new EdgeMultiplicityException(message.get());
+ }
+ if (!message.isPresent()) {
+ if (rule.getDirection().equals(Direction.OUT)) {
+ e = aVertex.addEdge(rule.getLabel(), bVertex);
+ } else if (rule.getDirection().equals(Direction.IN)) {
+ e = bVertex.addEdge(rule.getLabel(), aVertex);
+ }
+
+ this.addProperties(e, rule);
+ }
+ return e;
+ }
+
+ /**
+ * Adds the properties.
+ *
+ * @param edge the edge
+ * @param rule the rule
+ */
+ public void addProperties(Edge edge, EdgeRule rule) {
+ Map<EdgeProperty, String> propMap = new EnumMap<>(EdgeProperty.class);
+ propMap.put(EdgeProperty.CONTAINS, rule.getContains());
+ propMap.put(EdgeProperty.DELETE_OTHER_V, rule.getDeleteOtherV());
+ propMap.put(EdgeProperty.PREVENT_DELETE, rule.getPreventDelete());
+
+ for (Entry<EdgeProperty, String> entry : propMap.entrySet()) {
+ edge.property(entry.getKey().toString(), entry.getValue());
+ }
+
+ edge.property(EdgeField.PRIVATE.toString(), rule.isPrivateEdge());
+ edge.property(AAIProperties.AAI_UUID, UUID.randomUUID().toString());
+ }
+
+ /**
+ * Validate multiplicity.
+ *
+ * @param rule the rule
+ * @param aVertex the out vertex
+ * @param bVertex the in vertex
+ * @return true, if successful
+ * @throws AAIException the AAI exception
+ */
+ private Optional<String> validateMultiplicity(EdgeRule rule, GraphTraversalSource traversalSource, Vertex aVertex,
+ Vertex bVertex) {
+
+ Vertex a = aVertex;
+ Vertex b = bVertex;
+
+ if (rule.getDirection().equals(Direction.OUT)) {
+ a = aVertex;
+ b = bVertex;
+ } else if (rule.getDirection().equals(Direction.IN)) {
+ a = bVertex;
+ b = aVertex;
+ }
+
+ String aVertexType = a.<String>property(AAIProperties.NODE_TYPE).orElse(null);
+ String bVertexType = b.<String>property(AAIProperties.NODE_TYPE).orElse(null);
+ String label = rule.getLabel();
+
+ MultiplicityRule multiplicityRule = rule.getMultiplicityRule();
+
+ String detail = "";
+ final String msg = "multiplicity rule violated: only one edge can exist with label: ";
+
+ if (multiplicityRule.equals(MultiplicityRule.ONE2ONE)) {
+ Long outEdgesCnt = traversalSource.V(a).out(label).has(AAIProperties.NODE_TYPE, bVertexType).count().next();
+ Long inEdgesCnt = traversalSource.V(b).in(label).has(AAIProperties.NODE_TYPE, aVertexType).count().next();
+ if (aVertexType.equals(bVertexType)) {
+ inEdgesCnt = inEdgesCnt
+ + traversalSource.V(a).in(label).has(AAIProperties.NODE_TYPE, aVertexType).count().next();
+ outEdgesCnt = outEdgesCnt
+ + traversalSource.V(b).out(label).has(AAIProperties.NODE_TYPE, bVertexType).count().next();
+ }
+ if ((inEdgesCnt != 0) || (outEdgesCnt != 0)) {
+ detail = msg + label + " between " + aVertexType + " and " + bVertexType;
+ }
+ } else if (multiplicityRule.equals(MultiplicityRule.ONE2MANY)) {
+ Long inEdgesCnt = traversalSource.V(b).in(label).has(AAIProperties.NODE_TYPE, aVertexType).count().next();
+ if (inEdgesCnt != 0) {
+ detail = msg + label + " between " + aVertexType + " and " + bVertexType;
+ }
+ } else if (multiplicityRule.equals(MultiplicityRule.MANY2ONE)) {
+ Long outEdgesCnt = traversalSource.V(a).out(label).has(AAIProperties.NODE_TYPE, bVertexType).count().next();
+ if (outEdgesCnt != 0) {
+ detail = msg + label + " between " + aVertexType + " and " + bVertexType;
+ }
+ }
+
+ if (!"".equals(detail)) {
+ return Optional.of(detail);
+ } else {
+ return Optional.empty();
+ }
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/serialization/db/GetAllPool.java b/aai-core/src/main/java/org/onap/aai/serialization/db/GetAllPool.java
index 599906b9..08815432 100644
--- a/aai-core/src/main/java/org/onap/aai/serialization/db/GetAllPool.java
+++ b/aai-core/src/main/java/org/onap/aai/serialization/db/GetAllPool.java
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.serialization.db;
import java.util.concurrent.ExecutorService;
@@ -24,22 +25,22 @@ import java.util.concurrent.Executors;
public class GetAllPool {
- private ExecutorService pool;
-
- private GetAllPool() {
- pool = Executors.newWorkStealingPool(Runtime.getRuntime().availableProcessors());
- }
-
- private static class Helper {
- private static final GetAllPool INSTANCE = new GetAllPool();
- }
-
- public static GetAllPool getInstance() {
- return Helper.INSTANCE;
- }
-
- public ExecutorService getPool() {
-
- return this.pool;
- }
+ private ExecutorService pool;
+
+ private GetAllPool() {
+ pool = Executors.newWorkStealingPool(Runtime.getRuntime().availableProcessors());
+ }
+
+ private static class Helper {
+ private static final GetAllPool INSTANCE = new GetAllPool();
+ }
+
+ public static GetAllPool getInstance() {
+ return Helper.INSTANCE;
+ }
+
+ public ExecutorService getPool() {
+
+ return this.pool;
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/serialization/db/GraphSingleton.java b/aai-core/src/main/java/org/onap/aai/serialization/db/GraphSingleton.java
index d70a7ee7..cb713d56 100644
--- a/aai-core/src/main/java/org/onap/aai/serialization/db/GraphSingleton.java
+++ b/aai-core/src/main/java/org/onap/aai/serialization/db/GraphSingleton.java
@@ -17,52 +17,53 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.serialization.db;
+import java.util.concurrent.atomic.AtomicInteger;
+
import org.janusgraph.core.JanusGraph;
import org.onap.aai.dbmap.AAIGraph;
import org.onap.aai.dbmap.DBConnectionType;
-import java.util.concurrent.atomic.AtomicInteger;
-
/* This class simply calls AAIGraph under the covers for now */
public class GraphSingleton {
- protected AtomicInteger totalCount = new AtomicInteger();
-
- private static class Helper {
- private static final GraphSingleton INSTANCE = new GraphSingleton();
- }
-
- /**
- * Gets the single instance of GraphSingleton.
- *
- * @return single instance of GraphSingleton
- */
- public static GraphSingleton getInstance() {
- return Helper.INSTANCE;
+ protected AtomicInteger totalCount = new AtomicInteger();
+
+ private static class Helper {
+ private static final GraphSingleton INSTANCE = new GraphSingleton();
+ }
+
+ /**
+ * Gets the single instance of GraphSingleton.
+ *
+ * @return single instance of GraphSingleton
+ */
+ public static GraphSingleton getInstance() {
+ return Helper.INSTANCE;
+
+ }
+
+ /**
+ * Gets the count.
+ *
+ * @return the count
+ */
+ public AtomicInteger getCount() {
+ return totalCount;
+ }
+
+ /**
+ * Gets the tx graph.
+ *
+ * @return the tx graph
+ */
+ public JanusGraph getTxGraph() {
+ return AAIGraph.getInstance().getGraph();
+ }
- }
-
- /**
- * Gets the count.
- *
- * @return the count
- */
- public AtomicInteger getCount() {
- return totalCount;
- }
-
- /**
- * Gets the tx graph.
- *
- * @return the tx graph
- */
- public JanusGraph getTxGraph() {
- return AAIGraph.getInstance().getGraph();
- }
-
- public JanusGraph getTxGraph(DBConnectionType connectionType) {
- return AAIGraph.getInstance().getGraph(connectionType);
- }
+ public JanusGraph getTxGraph(DBConnectionType connectionType) {
+ return AAIGraph.getInstance().getGraph(connectionType);
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/serialization/db/InMemoryGraphSingleton.java b/aai-core/src/main/java/org/onap/aai/serialization/db/InMemoryGraphSingleton.java
index 0f4c3e7d..90f71db5 100644
--- a/aai-core/src/main/java/org/onap/aai/serialization/db/InMemoryGraphSingleton.java
+++ b/aai-core/src/main/java/org/onap/aai/serialization/db/InMemoryGraphSingleton.java
@@ -17,42 +17,42 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-package org.onap.aai.serialization.db;
-import org.onap.aai.dbmap.DBConnectionType;
+package org.onap.aai.serialization.db;
import org.janusgraph.core.JanusGraph;
+import org.onap.aai.dbmap.DBConnectionType;
public class InMemoryGraphSingleton extends GraphSingleton {
- private static JanusGraph inMemgraph;
-
- private static class Helper {
- private static final InMemoryGraphSingleton INSTANCE = new InMemoryGraphSingleton();
- }
-
- /**
- * Gets the single instance of JanusGraphSingleton.
- *
- * @return single instance of JanusGraphSingleton
- */
- public static InMemoryGraphSingleton getInstance(JanusGraph graph) {
- inMemgraph = graph;
- return Helper.INSTANCE;
- }
-
- /**
- * Gets the tx graph.
- *
- * @return the tx graph
- */
- @Override
- public JanusGraph getTxGraph() {
- return inMemgraph;
- }
-
- @Override
- public JanusGraph getTxGraph(DBConnectionType connectionType) {
- return inMemgraph;
- }
+ private static JanusGraph inMemgraph;
+
+ private static class Helper {
+ private static final InMemoryGraphSingleton INSTANCE = new InMemoryGraphSingleton();
+ }
+
+ /**
+ * Gets the single instance of JanusGraphSingleton.
+ *
+ * @return single instance of JanusGraphSingleton
+ */
+ public static InMemoryGraphSingleton getInstance(JanusGraph graph) {
+ inMemgraph = graph;
+ return Helper.INSTANCE;
+ }
+
+ /**
+ * Gets the tx graph.
+ *
+ * @return the tx graph
+ */
+ @Override
+ public JanusGraph getTxGraph() {
+ return inMemgraph;
+ }
+
+ @Override
+ public JanusGraph getTxGraph(DBConnectionType connectionType) {
+ return inMemgraph;
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/serialization/db/JanusGraphSingleton.java b/aai-core/src/main/java/org/onap/aai/serialization/db/JanusGraphSingleton.java
index 4513d107..6482b011 100644
--- a/aai-core/src/main/java/org/onap/aai/serialization/db/JanusGraphSingleton.java
+++ b/aai-core/src/main/java/org/onap/aai/serialization/db/JanusGraphSingleton.java
@@ -17,21 +17,22 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.serialization.db;
/* This is class is just a wrapper of its parent */
public class JanusGraphSingleton extends GraphSingleton {
- private static class Helper {
- private static final JanusGraphSingleton INSTANCE = new JanusGraphSingleton();
- }
-
- /**
- * Gets the single instance of JanusGraphSingleton.
- *
- * @return single instance of JanusGraphSingleton
- */
- public static JanusGraphSingleton getInstance() {
- return Helper.INSTANCE;
- }
+ private static class Helper {
+ private static final JanusGraphSingleton INSTANCE = new JanusGraphSingleton();
+ }
+
+ /**
+ * Gets the single instance of JanusGraphSingleton.
+ *
+ * @return single instance of JanusGraphSingleton
+ */
+ public static JanusGraphSingleton getInstance() {
+ return Helper.INSTANCE;
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/serialization/db/exceptions/EdgeMultiplicityException.java b/aai-core/src/main/java/org/onap/aai/serialization/db/exceptions/EdgeMultiplicityException.java
index 74961cb8..675dfb77 100644
--- a/aai-core/src/main/java/org/onap/aai/serialization/db/exceptions/EdgeMultiplicityException.java
+++ b/aai-core/src/main/java/org/onap/aai/serialization/db/exceptions/EdgeMultiplicityException.java
@@ -17,23 +17,24 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.serialization.db.exceptions;
import org.onap.aai.exceptions.AAIException;
public class EdgeMultiplicityException extends AAIException {
- private static final long serialVersionUID = -5575661036426538012L;
+ private static final long serialVersionUID = -5575661036426538012L;
- public EdgeMultiplicityException(String message) {
- super("AAI_6140", message);
- }
+ public EdgeMultiplicityException(String message) {
+ super("AAI_6140", message);
+ }
- public EdgeMultiplicityException(Throwable cause) {
- super("AAI_6140",cause);
- }
+ public EdgeMultiplicityException(Throwable cause) {
+ super("AAI_6140", cause);
+ }
- public EdgeMultiplicityException(String message, Throwable cause) {
- super("AAI_6140", cause, message);
- }
+ public EdgeMultiplicityException(String message, Throwable cause) {
+ super("AAI_6140", cause, message);
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/serialization/db/exceptions/MultipleEdgeRuleFoundException.java b/aai-core/src/main/java/org/onap/aai/serialization/db/exceptions/MultipleEdgeRuleFoundException.java
index 98ba75be..c2a3c1a2 100644
--- a/aai-core/src/main/java/org/onap/aai/serialization/db/exceptions/MultipleEdgeRuleFoundException.java
+++ b/aai-core/src/main/java/org/onap/aai/serialization/db/exceptions/MultipleEdgeRuleFoundException.java
@@ -17,23 +17,24 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.serialization.db.exceptions;
import org.onap.aai.exceptions.AAIException;
public class MultipleEdgeRuleFoundException extends AAIException {
- private static final long serialVersionUID = -906843868234976763L;
+ private static final long serialVersionUID = -906843868234976763L;
- public MultipleEdgeRuleFoundException(String message) {
- super("AAI_6107", message);
- }
+ public MultipleEdgeRuleFoundException(String message) {
+ super("AAI_6107", message);
+ }
- public MultipleEdgeRuleFoundException(Throwable cause) {
- super("AAI_6107",cause);
- }
+ public MultipleEdgeRuleFoundException(Throwable cause) {
+ super("AAI_6107", cause);
+ }
- public MultipleEdgeRuleFoundException(String message, Throwable cause) {
- super("AAI_6107", cause, message);
- }
+ public MultipleEdgeRuleFoundException(String message, Throwable cause) {
+ super("AAI_6107", cause, message);
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/serialization/db/exceptions/NoEdgeRuleFoundException.java b/aai-core/src/main/java/org/onap/aai/serialization/db/exceptions/NoEdgeRuleFoundException.java
index 758d76c0..0f2a044d 100644
--- a/aai-core/src/main/java/org/onap/aai/serialization/db/exceptions/NoEdgeRuleFoundException.java
+++ b/aai-core/src/main/java/org/onap/aai/serialization/db/exceptions/NoEdgeRuleFoundException.java
@@ -17,23 +17,24 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.serialization.db.exceptions;
import org.onap.aai.exceptions.AAIException;
public class NoEdgeRuleFoundException extends AAIException {
- private static final long serialVersionUID = -906843868234976763L;
-
- public NoEdgeRuleFoundException(String message) {
- super("AAI_6107", message);
- }
+ private static final long serialVersionUID = -906843868234976763L;
+
+ public NoEdgeRuleFoundException(String message) {
+ super("AAI_6107", message);
+ }
- public NoEdgeRuleFoundException(Throwable cause) {
- super("AAI_6107",cause);
- }
+ public NoEdgeRuleFoundException(Throwable cause) {
+ super("AAI_6107", cause);
+ }
- public NoEdgeRuleFoundException(String message, Throwable cause) {
- super("AAI_6107", cause, message);
- }
+ public NoEdgeRuleFoundException(String message, Throwable cause) {
+ super("AAI_6107", cause, message);
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/serialization/engines/InMemoryDBEngine.java b/aai-core/src/main/java/org/onap/aai/serialization/engines/InMemoryDBEngine.java
index afc91bd3..86c32f4a 100644
--- a/aai-core/src/main/java/org/onap/aai/serialization/engines/InMemoryDBEngine.java
+++ b/aai-core/src/main/java/org/onap/aai/serialization/engines/InMemoryDBEngine.java
@@ -17,14 +17,19 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.serialization.engines;
-import org.janusgraph.core.JanusGraph;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.process.traversal.strategy.verification.ReadOnlyStrategy;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.VertexProperty;
+import org.janusgraph.core.JanusGraph;
import org.onap.aai.dbmap.DBConnectionType;
import org.onap.aai.introspection.Loader;
import org.onap.aai.query.builder.*;
@@ -32,174 +37,168 @@ import org.onap.aai.serialization.db.InMemoryGraphSingleton;
import org.onap.aai.serialization.engines.query.GraphTraversalQueryEngine;
import org.onap.aai.serialization.engines.query.QueryEngine;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
public class InMemoryDBEngine extends TransactionalGraphEngine {
- /**
- * Instantiates a new JanusGraph DB engine.
- *
- * @param style
- * the style
- * @param loader
- * the loader
- */
- private JanusGraph graph = null;
-
- private static final TransactionalGraphEngine.Admin admin = null;
-
- public InMemoryDBEngine(QueryStyle style, DBConnectionType connectionType, Loader loader, JanusGraph graph) {
- super(style, loader, connectionType, InMemoryGraphSingleton.getInstance(graph));
- this.graph = graph;
- }
-
- /**
- * Instantiates a new JanusGraph DB engine.
- *
- * @param style
- * the style
- * @param loader
- * the loader
- * @param connect
- * the connect
- */
- public InMemoryDBEngine(QueryStyle style, Loader loader, boolean connect, JanusGraph graph) {
- super(style, loader);
- if (connect) {
- this.singleton = InMemoryGraphSingleton.getInstance(graph);
- }
- this.graph = graph;
- }
-
- @Override
- public QueryEngine getQueryEngine() {
-
- if (style.equals(QueryStyle.TRAVERSAL) || style.equals(QueryStyle.TRAVERSAL_URI)) {
-
- GraphTraversalSource traversalSource = graph.traversal();
- return new GraphTraversalQueryEngine(traversalSource);
-
- } else {
- throw new IllegalArgumentException("Query Engine type not recognized");
- }
-
- }
-
- @Override
- public QueryBuilder<Vertex> getQueryBuilder(QueryStyle style, Loader loader) {
- if (style.equals(QueryStyle.GREMLIN_TRAVERSAL)) {
- return new GremlinTraversal<>(loader, graph.traversal());
- } else if (style.equals(QueryStyle.TRAVERSAL)) {
- return new TraversalQuery<>(loader, graph.traversal());
- } else if (style.equals(QueryStyle.TRAVERSAL_URI)) {
- return new TraversalURIOptimizedQuery<>(loader, graph.traversal());
- } else {
- throw new IllegalArgumentException("Query Builder type is Not recognized");
- }
-
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean setListProperty(Vertex v, String name, List<?> objs) {
-
- // clear out list full replace style
-
- Iterator<VertexProperty<Object>> iterator = v.properties(name);
- while (iterator.hasNext()) {
- iterator.next().remove();
- }
- if (objs != null) {
- for (Object obj : objs) {
- v.property(name, obj);
- }
- }
- return true;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public List<Object> getListProperty(Vertex v, String name) {
-
- List<Object> result = new ArrayList<>();
-
- Iterator<VertexProperty<Object>> iterator = v.properties(name);
-
- while (iterator.hasNext()) {
- result.add(iterator.next().value());
- }
-
- if (result.isEmpty()) {
- result = null;
- }
-
- return result;
-
- }
-
- @Override
- public QueryBuilder<Vertex> getQueryBuilder() {
- return getQueryBuilder(this.loader);
- }
-
- @Override
- public QueryBuilder<Vertex> getQueryBuilder(Loader loader) {
- if (style.equals(QueryStyle.GREMLIN_TRAVERSAL)) {
- return new GremlinTraversal<>(loader, this.asAdmin().getTraversalSource());
- } else if (style.equals(QueryStyle.GREMLIN_UNIQUE)) {
- return new GremlinUnique<>(loader, this.asAdmin().getTraversalSource());
- } else if (style.equals(QueryStyle.TRAVERSAL)) {
- return new TraversalQuery<>(loader, graph.traversal());
- } else if (style.equals(QueryStyle.TRAVERSAL_URI)) {
- return new TraversalURIOptimizedQuery<>(loader, graph.traversal());
- } else {
- throw new IllegalArgumentException("Query Builder type not recognized");
- }
-
- }
-
- @Override
- public QueryBuilder<Vertex> getQueryBuilder(Vertex start) {
- return getQueryBuilder(this.loader, start);
- }
-
- public GraphTraversalSource getTraversalSource() {
- return graph.traversal();
- }
-
- @Override
- public QueryBuilder<Vertex> getQueryBuilder(Loader loader, Vertex start) {
- if (style.equals(QueryStyle.GREMLIN_TRAVERSAL)) {
- return new GremlinTraversal<>(loader, graph.traversal(), start);
- } else if (style.equals(QueryStyle.GREMLIN_UNIQUE)) {
- return new GremlinUnique<>(loader, this.asAdmin().getTraversalSource(), start);
- } else if (style.equals(QueryStyle.TRAVERSAL)) {
- return new TraversalQuery<>(loader, graph.traversal(), start);
- } else if (style.equals(QueryStyle.TRAVERSAL_URI)) {
- return new TraversalURIOptimizedQuery<>(loader, graph.traversal(), start);
- } else {
- throw new IllegalArgumentException("Query Builder type not recognized");
- }
-
- }
-
- @Override
- public Graph startTransaction() {
- if (this.tx() == null) {
- this.currentTx = graph.newTransaction();
- this.currentTraversal = this.tx().traversal();
- this.readOnlyTraversal = this.tx()
- .traversal(GraphTraversalSource.build().with(ReadOnlyStrategy.instance()));
- }
- return currentTx;
- }
-
-
+ /**
+ * Instantiates a new JanusGraph DB engine.
+ *
+ * @param style
+ * the style
+ * @param loader
+ * the loader
+ */
+ private JanusGraph graph = null;
+
+ private static final TransactionalGraphEngine.Admin admin = null;
+
+ public InMemoryDBEngine(QueryStyle style, DBConnectionType connectionType, Loader loader, JanusGraph graph) {
+ super(style, loader, connectionType, InMemoryGraphSingleton.getInstance(graph));
+ this.graph = graph;
+ }
+
+ /**
+ * Instantiates a new JanusGraph DB engine.
+ *
+ * @param style
+ * the style
+ * @param loader
+ * the loader
+ * @param connect
+ * the connect
+ */
+ public InMemoryDBEngine(QueryStyle style, Loader loader, boolean connect, JanusGraph graph) {
+ super(style, loader);
+ if (connect) {
+ this.singleton = InMemoryGraphSingleton.getInstance(graph);
+ }
+ this.graph = graph;
+ }
+
+ @Override
+ public QueryEngine getQueryEngine() {
+
+ if (style.equals(QueryStyle.TRAVERSAL) || style.equals(QueryStyle.TRAVERSAL_URI)) {
+
+ GraphTraversalSource traversalSource = graph.traversal();
+ return new GraphTraversalQueryEngine(traversalSource);
+
+ } else {
+ throw new IllegalArgumentException("Query Engine type not recognized");
+ }
+
+ }
+
+ @Override
+ public QueryBuilder<Vertex> getQueryBuilder(QueryStyle style, Loader loader) {
+ if (style.equals(QueryStyle.GREMLIN_TRAVERSAL)) {
+ return new GremlinTraversal<>(loader, graph.traversal());
+ } else if (style.equals(QueryStyle.TRAVERSAL)) {
+ return new TraversalQuery<>(loader, graph.traversal());
+ } else if (style.equals(QueryStyle.TRAVERSAL_URI)) {
+ return new TraversalURIOptimizedQuery<>(loader, graph.traversal());
+ } else {
+ throw new IllegalArgumentException("Query Builder type is Not recognized");
+ }
+
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public boolean setListProperty(Vertex v, String name, List<?> objs) {
+
+ // clear out list full replace style
+
+ Iterator<VertexProperty<Object>> iterator = v.properties(name);
+ while (iterator.hasNext()) {
+ iterator.next().remove();
+ }
+ if (objs != null) {
+ for (Object obj : objs) {
+ v.property(name, obj);
+ }
+ }
+ return true;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public List<Object> getListProperty(Vertex v, String name) {
+
+ List<Object> result = new ArrayList<>();
+
+ Iterator<VertexProperty<Object>> iterator = v.properties(name);
+
+ while (iterator.hasNext()) {
+ result.add(iterator.next().value());
+ }
+
+ if (result.isEmpty()) {
+ result = null;
+ }
+
+ return result;
+
+ }
+
+ @Override
+ public QueryBuilder<Vertex> getQueryBuilder() {
+ return getQueryBuilder(this.loader);
+ }
+
+ @Override
+ public QueryBuilder<Vertex> getQueryBuilder(Loader loader) {
+ if (style.equals(QueryStyle.GREMLIN_TRAVERSAL)) {
+ return new GremlinTraversal<>(loader, this.asAdmin().getTraversalSource());
+ } else if (style.equals(QueryStyle.GREMLIN_UNIQUE)) {
+ return new GremlinUnique<>(loader, this.asAdmin().getTraversalSource());
+ } else if (style.equals(QueryStyle.TRAVERSAL)) {
+ return new TraversalQuery<>(loader, graph.traversal());
+ } else if (style.equals(QueryStyle.TRAVERSAL_URI)) {
+ return new TraversalURIOptimizedQuery<>(loader, graph.traversal());
+ } else {
+ throw new IllegalArgumentException("Query Builder type not recognized");
+ }
+
+ }
+
+ @Override
+ public QueryBuilder<Vertex> getQueryBuilder(Vertex start) {
+ return getQueryBuilder(this.loader, start);
+ }
+
+ public GraphTraversalSource getTraversalSource() {
+ return graph.traversal();
+ }
+
+ @Override
+ public QueryBuilder<Vertex> getQueryBuilder(Loader loader, Vertex start) {
+ if (style.equals(QueryStyle.GREMLIN_TRAVERSAL)) {
+ return new GremlinTraversal<>(loader, graph.traversal(), start);
+ } else if (style.equals(QueryStyle.GREMLIN_UNIQUE)) {
+ return new GremlinUnique<>(loader, this.asAdmin().getTraversalSource(), start);
+ } else if (style.equals(QueryStyle.TRAVERSAL)) {
+ return new TraversalQuery<>(loader, graph.traversal(), start);
+ } else if (style.equals(QueryStyle.TRAVERSAL_URI)) {
+ return new TraversalURIOptimizedQuery<>(loader, graph.traversal(), start);
+ } else {
+ throw new IllegalArgumentException("Query Builder type not recognized");
+ }
+
+ }
+
+ @Override
+ public Graph startTransaction() {
+ if (this.tx() == null) {
+ this.currentTx = graph.newTransaction();
+ this.currentTraversal = this.tx().traversal();
+ this.readOnlyTraversal =
+ this.tx().traversal(GraphTraversalSource.build().with(ReadOnlyStrategy.instance()));
+ }
+ return currentTx;
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/serialization/engines/JanusGraphDBEngine.java b/aai-core/src/main/java/org/onap/aai/serialization/engines/JanusGraphDBEngine.java
index c12aa603..346cf026 100644
--- a/aai-core/src/main/java/org/onap/aai/serialization/engines/JanusGraphDBEngine.java
+++ b/aai-core/src/main/java/org/onap/aai/serialization/engines/JanusGraphDBEngine.java
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.serialization.engines;
import java.util.ArrayList;
@@ -31,70 +32,70 @@ import org.onap.aai.serialization.db.JanusGraphSingleton;
public class JanusGraphDBEngine extends TransactionalGraphEngine {
- /**
- * Instantiates a new JanusGraph DB engine.
- *
- * @param style the style
- * @param loader the loader
- */
- public JanusGraphDBEngine(QueryStyle style, DBConnectionType connectionType, Loader loader) {
- super(style, loader, connectionType, JanusGraphSingleton.getInstance());
- }
-
- /**
- * Instantiates a new JanusGraph DB engine.
- *
- * @param style the style
- * @param loader the loader
- * @param connect the connect
- */
- public JanusGraphDBEngine(QueryStyle style, Loader loader, boolean connect) {
- super(style, loader);
- if (connect) {
- this.singleton = JanusGraphSingleton.getInstance();
- }
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean setListProperty(Vertex v, String name, List<?> objs) {
-
- //clear out list full replace style
-
- Iterator<VertexProperty<Object>> iterator = v.properties(name);
- while (iterator.hasNext()) {
- iterator.next().remove();
- }
- if (objs != null) {
- for (Object obj : objs) {
- v.property(name, obj);
- }
- }
- return true;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public List<Object> getListProperty(Vertex v, String name) {
-
- List<Object> result = new ArrayList<Object>();
-
- Iterator<VertexProperty<Object>> iterator = v.properties(name);
-
- while (iterator.hasNext()) {
- result.add(iterator.next().value());
- }
-
- if (result.size() == 0) {
- result = null;
- }
-
- return result;
-
- }
-
+ /**
+ * Instantiates a new JanusGraph DB engine.
+ *
+ * @param style the style
+ * @param loader the loader
+ */
+ public JanusGraphDBEngine(QueryStyle style, DBConnectionType connectionType, Loader loader) {
+ super(style, loader, connectionType, JanusGraphSingleton.getInstance());
+ }
+
+ /**
+ * Instantiates a new JanusGraph DB engine.
+ *
+ * @param style the style
+ * @param loader the loader
+ * @param connect the connect
+ */
+ public JanusGraphDBEngine(QueryStyle style, Loader loader, boolean connect) {
+ super(style, loader);
+ if (connect) {
+ this.singleton = JanusGraphSingleton.getInstance();
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public boolean setListProperty(Vertex v, String name, List<?> objs) {
+
+ // clear out list full replace style
+
+ Iterator<VertexProperty<Object>> iterator = v.properties(name);
+ while (iterator.hasNext()) {
+ iterator.next().remove();
+ }
+ if (objs != null) {
+ for (Object obj : objs) {
+ v.property(name, obj);
+ }
+ }
+ return true;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public List<Object> getListProperty(Vertex v, String name) {
+
+ List<Object> result = new ArrayList<Object>();
+
+ Iterator<VertexProperty<Object>> iterator = v.properties(name);
+
+ while (iterator.hasNext()) {
+ result.add(iterator.next().value());
+ }
+
+ if (result.size() == 0) {
+ result = null;
+ }
+
+ return result;
+
+ }
+
}
diff --git a/aai-core/src/main/java/org/onap/aai/serialization/engines/QueryStyle.java b/aai-core/src/main/java/org/onap/aai/serialization/engines/QueryStyle.java
index 2a069588..c291fbcb 100644
--- a/aai-core/src/main/java/org/onap/aai/serialization/engines/QueryStyle.java
+++ b/aai-core/src/main/java/org/onap/aai/serialization/engines/QueryStyle.java
@@ -17,8 +17,9 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.serialization.engines;
public enum QueryStyle {
- GREMLIN_TRAVERSAL, GREMLIN_UNIQUE, GREMLINPIPELINE_TRAVERSAL, TRAVERSAL, TRAVERSAL_URI
+ GREMLIN_TRAVERSAL, GREMLIN_UNIQUE, GREMLINPIPELINE_TRAVERSAL, TRAVERSAL, TRAVERSAL_URI
}
diff --git a/aai-core/src/main/java/org/onap/aai/serialization/engines/TransactionalGraphEngine.java b/aai-core/src/main/java/org/onap/aai/serialization/engines/TransactionalGraphEngine.java
index eaf6829c..731d6c23 100644
--- a/aai-core/src/main/java/org/onap/aai/serialization/engines/TransactionalGraphEngine.java
+++ b/aai-core/src/main/java/org/onap/aai/serialization/engines/TransactionalGraphEngine.java
@@ -17,14 +17,18 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.serialization.engines;
-import org.janusgraph.core.JanusGraph;
-import org.janusgraph.core.schema.JanusGraphManagement;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicInteger;
+
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.process.traversal.strategy.verification.ReadOnlyStrategy;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.Vertex;
+import org.janusgraph.core.JanusGraph;
+import org.janusgraph.core.schema.JanusGraphManagement;
import org.onap.aai.dbmap.DBConnectionType;
import org.onap.aai.introspection.Loader;
import org.onap.aai.query.builder.*;
@@ -32,213 +36,216 @@ import org.onap.aai.serialization.db.GraphSingleton;
import org.onap.aai.serialization.engines.query.GraphTraversalQueryEngine;
import org.onap.aai.serialization.engines.query.QueryEngine;
-import java.util.List;
-import java.util.concurrent.atomic.AtomicInteger;
-
public abstract class TransactionalGraphEngine {
-
- protected GraphSingleton singleton = null;
- protected QueryEngine queryEngine = null;
- protected QueryBuilder<Vertex> queryBuilder = null;
- protected QueryStyle style = null;
- protected final DBConnectionType connectionType;
- protected final Loader loader;
- protected Graph currentTx = null;
- protected GraphTraversalSource currentTraversal = null;
- protected GraphTraversalSource readOnlyTraversal = null;
- private final Admin admin;
- /**
- * Instantiates a new transactional graph engine.
- *
- * @param style the style
- * @param loader the loader
- */
- public TransactionalGraphEngine (QueryStyle style, Loader loader, DBConnectionType connectionType, GraphSingleton singleton) {
- this.loader = loader;
- this.style = style;
- this.singleton = singleton;
- this.connectionType = connectionType;
- admin = new Admin();
- }
-
- public TransactionalGraphEngine (QueryStyle style, Loader loader) {
- this.loader = loader;
- this.style = style;
- this.connectionType = DBConnectionType.REALTIME;
- admin = new Admin();
-
- }
-
- /**
- * Sets the list property.
- *
- * @param v the v
- * @param name the name
- * @param obj the obj
- * @return true, if successful
- */
- public abstract boolean setListProperty(Vertex v, String name, List<?> obj);
-
- /**
- * Gets the list property.
- *
- * @param v the v
- * @param name the name
- * @return the list property
- */
- public abstract List<Object> getListProperty(Vertex v, String name);
-
- /**
- * Gets the graph.
- *
- * @return the graph
- */
- private JanusGraph getGraph() {
- return singleton.getTxGraph(this.connectionType);
- }
-
- /**
- * Gets the count.
- *
- * @return the count
- */
- public AtomicInteger getCount() {
- return singleton.getCount();
- }
-
-
- /**
- * Gets the query engine.
- *
- * @return the query engine
- */
- public QueryEngine getQueryEngine() {
- QueryEngine engine = null;
- if (style.equals(QueryStyle.GREMLIN_TRAVERSAL)) {
- //this.queryEngine = new GremlinQueryEngine(this);
- } else if (style.equals(QueryStyle.GREMLIN_UNIQUE)) {
- //this.queryEngine = new GremlinQueryEngine(this);
- } else if (style.equals(QueryStyle.GREMLINPIPELINE_TRAVERSAL)) {
- //this.queryEngine = new GremlinPipelineQueryEngine(this);
- } else if (style.equals(QueryStyle.TRAVERSAL) || style.equals(QueryStyle.TRAVERSAL_URI)) {
-
- return new GraphTraversalQueryEngine(this.asAdmin().getTraversalSource());
-
- } else {
- throw new IllegalArgumentException("Query Engine type not recognized");
- }
-
- return engine;
- }
-
- /**
- * Gets the query builder.
- *
- * @return the query builder
- */
- public QueryBuilder<Vertex> getQueryBuilder() {
- return getQueryBuilder(this.loader);
- }
-
- public QueryBuilder<Vertex> getQueryBuilder(QueryStyle style) {
- return getQueryBuilder(style, this.loader);
- }
-
- public QueryBuilder<Vertex> getQueryBuilder(Loader loader) {
- return getQueryBuilder(this.style, loader);
- }
-
- public QueryBuilder<Vertex> getQueryBuilder(QueryStyle style, Loader loader) {
- if (style.equals(QueryStyle.GREMLIN_TRAVERSAL)) {
- return new GremlinTraversal<>(loader, this.asAdmin().getTraversalSource());
- } else if (style.equals(QueryStyle.GREMLIN_UNIQUE)) {
- return new GremlinUnique<>(loader, this.asAdmin().getTraversalSource());
- } else if (style.equals(QueryStyle.GREMLINPIPELINE_TRAVERSAL)) {
- //return new GremlinPipelineTraversal(loader);
- } else if (style.equals(QueryStyle.TRAVERSAL)) {
- return new TraversalQuery<>(loader, this.asAdmin().getTraversalSource());
- } else if (style.equals(QueryStyle.TRAVERSAL_URI)) {
- return new TraversalURIOptimizedQuery<>(loader, this.asAdmin().getTraversalSource());
- } else {
- throw new IllegalArgumentException("Query Builder type not recognized");
- }
- return queryBuilder;
- }
- /**
- * Gets the query builder.
- *
- * @param start the start
- * @return the query builder
- */
- public QueryBuilder<Vertex> getQueryBuilder(Vertex start) {
- return getQueryBuilder(this.loader, start);
- }
-
- public QueryBuilder<Vertex> getQueryBuilder(Loader loader, Vertex start) {
- return getQueryBuilder(this.style, loader, start);
- }
-
- public QueryBuilder<Vertex> getQueryBuilder(QueryStyle style, Loader loader, Vertex start) {
- if (style.equals(QueryStyle.GREMLIN_TRAVERSAL)) {
- return new GremlinTraversal<>(loader, this.asAdmin().getTraversalSource(), start);
- } else if (style.equals(QueryStyle.GREMLIN_UNIQUE)) {
- return new GremlinUnique<>(loader, this.asAdmin().getTraversalSource(), start);
- } else if (style.equals(QueryStyle.GREMLINPIPELINE_TRAVERSAL)) {
- //return new GremlinPipelineTraversal(loader,start);
- } else if (style.equals(QueryStyle.TRAVERSAL)) {
- return new TraversalQuery<>(loader, this.asAdmin().getTraversalSource(), start);
- } else if (style.equals(QueryStyle.TRAVERSAL_URI)) {
- return new TraversalURIOptimizedQuery<>(loader, this.asAdmin().getTraversalSource(), start);
- } else {
- throw new IllegalArgumentException("Query Builder type not recognized");
- }
- return queryBuilder;
- }
- public Graph startTransaction() {
- if (this.tx() == null) {
- this.currentTx = this.getGraph().newTransaction();
- this.currentTraversal = this.tx().traversal();
- this.readOnlyTraversal = this.tx().traversal(GraphTraversalSource.build().with(ReadOnlyStrategy.instance()));
- }
- return currentTx;
- }
-
- public void rollback() {
- if (this.tx() != null) {
- this.tx().tx().rollback();
- this.currentTx = null;
- this.currentTraversal = null;
- this.readOnlyTraversal = null;
- }
- }
- public void commit() {
- if (this.tx() != null) {
- this.tx().tx().commit();
- this.currentTx = null;
- this.currentTraversal = null;
- this.readOnlyTraversal = null;
- }
- }
-
- public Graph tx() {
- return this.currentTx;
- }
-
- public Admin asAdmin() {
- return admin;
- }
-
- public class Admin {
-
- public GraphTraversalSource getTraversalSource() {
- return currentTraversal;
- }
- public GraphTraversalSource getReadOnlyTraversalSource() {
- return readOnlyTraversal;
- }
-
- public JanusGraphManagement getManagementSystem() {
- return getGraph().openManagement();
- }
- }
+
+ protected GraphSingleton singleton = null;
+ protected QueryEngine queryEngine = null;
+ protected QueryBuilder<Vertex> queryBuilder = null;
+ protected QueryStyle style = null;
+ protected final DBConnectionType connectionType;
+ protected final Loader loader;
+ protected Graph currentTx = null;
+ protected GraphTraversalSource currentTraversal = null;
+ protected GraphTraversalSource readOnlyTraversal = null;
+ private final Admin admin;
+
+ /**
+ * Instantiates a new transactional graph engine.
+ *
+ * @param style the style
+ * @param loader the loader
+ */
+ public TransactionalGraphEngine(QueryStyle style, Loader loader, DBConnectionType connectionType,
+ GraphSingleton singleton) {
+ this.loader = loader;
+ this.style = style;
+ this.singleton = singleton;
+ this.connectionType = connectionType;
+ admin = new Admin();
+ }
+
+ public TransactionalGraphEngine(QueryStyle style, Loader loader) {
+ this.loader = loader;
+ this.style = style;
+ this.connectionType = DBConnectionType.REALTIME;
+ admin = new Admin();
+
+ }
+
+ /**
+ * Sets the list property.
+ *
+ * @param v the v
+ * @param name the name
+ * @param obj the obj
+ * @return true, if successful
+ */
+ public abstract boolean setListProperty(Vertex v, String name, List<?> obj);
+
+ /**
+ * Gets the list property.
+ *
+ * @param v the v
+ * @param name the name
+ * @return the list property
+ */
+ public abstract List<Object> getListProperty(Vertex v, String name);
+
+ /**
+ * Gets the graph.
+ *
+ * @return the graph
+ */
+ private JanusGraph getGraph() {
+ return singleton.getTxGraph(this.connectionType);
+ }
+
+ /**
+ * Gets the count.
+ *
+ * @return the count
+ */
+ public AtomicInteger getCount() {
+ return singleton.getCount();
+ }
+
+ /**
+ * Gets the query engine.
+ *
+ * @return the query engine
+ */
+ public QueryEngine getQueryEngine() {
+ QueryEngine engine = null;
+ if (style.equals(QueryStyle.GREMLIN_TRAVERSAL)) {
+ // this.queryEngine = new GremlinQueryEngine(this);
+ } else if (style.equals(QueryStyle.GREMLIN_UNIQUE)) {
+ // this.queryEngine = new GremlinQueryEngine(this);
+ } else if (style.equals(QueryStyle.GREMLINPIPELINE_TRAVERSAL)) {
+ // this.queryEngine = new GremlinPipelineQueryEngine(this);
+ } else if (style.equals(QueryStyle.TRAVERSAL) || style.equals(QueryStyle.TRAVERSAL_URI)) {
+
+ return new GraphTraversalQueryEngine(this.asAdmin().getTraversalSource());
+
+ } else {
+ throw new IllegalArgumentException("Query Engine type not recognized");
+ }
+
+ return engine;
+ }
+
+ /**
+ * Gets the query builder.
+ *
+ * @return the query builder
+ */
+ public QueryBuilder<Vertex> getQueryBuilder() {
+ return getQueryBuilder(this.loader);
+ }
+
+ public QueryBuilder<Vertex> getQueryBuilder(QueryStyle style) {
+ return getQueryBuilder(style, this.loader);
+ }
+
+ public QueryBuilder<Vertex> getQueryBuilder(Loader loader) {
+ return getQueryBuilder(this.style, loader);
+ }
+
+ public QueryBuilder<Vertex> getQueryBuilder(QueryStyle style, Loader loader) {
+ if (style.equals(QueryStyle.GREMLIN_TRAVERSAL)) {
+ return new GremlinTraversal<>(loader, this.asAdmin().getTraversalSource());
+ } else if (style.equals(QueryStyle.GREMLIN_UNIQUE)) {
+ return new GremlinUnique<>(loader, this.asAdmin().getTraversalSource());
+ } else if (style.equals(QueryStyle.GREMLINPIPELINE_TRAVERSAL)) {
+ // return new GremlinPipelineTraversal(loader);
+ } else if (style.equals(QueryStyle.TRAVERSAL)) {
+ return new TraversalQuery<>(loader, this.asAdmin().getTraversalSource());
+ } else if (style.equals(QueryStyle.TRAVERSAL_URI)) {
+ return new TraversalURIOptimizedQuery<>(loader, this.asAdmin().getTraversalSource());
+ } else {
+ throw new IllegalArgumentException("Query Builder type not recognized");
+ }
+ return queryBuilder;
+ }
+
+ /**
+ * Gets the query builder.
+ *
+ * @param start the start
+ * @return the query builder
+ */
+ public QueryBuilder<Vertex> getQueryBuilder(Vertex start) {
+ return getQueryBuilder(this.loader, start);
+ }
+
+ public QueryBuilder<Vertex> getQueryBuilder(Loader loader, Vertex start) {
+ return getQueryBuilder(this.style, loader, start);
+ }
+
+ public QueryBuilder<Vertex> getQueryBuilder(QueryStyle style, Loader loader, Vertex start) {
+ if (style.equals(QueryStyle.GREMLIN_TRAVERSAL)) {
+ return new GremlinTraversal<>(loader, this.asAdmin().getTraversalSource(), start);
+ } else if (style.equals(QueryStyle.GREMLIN_UNIQUE)) {
+ return new GremlinUnique<>(loader, this.asAdmin().getTraversalSource(), start);
+ } else if (style.equals(QueryStyle.GREMLINPIPELINE_TRAVERSAL)) {
+ // return new GremlinPipelineTraversal(loader,start);
+ } else if (style.equals(QueryStyle.TRAVERSAL)) {
+ return new TraversalQuery<>(loader, this.asAdmin().getTraversalSource(), start);
+ } else if (style.equals(QueryStyle.TRAVERSAL_URI)) {
+ return new TraversalURIOptimizedQuery<>(loader, this.asAdmin().getTraversalSource(), start);
+ } else {
+ throw new IllegalArgumentException("Query Builder type not recognized");
+ }
+ return queryBuilder;
+ }
+
+ public Graph startTransaction() {
+ if (this.tx() == null) {
+ this.currentTx = this.getGraph().newTransaction();
+ this.currentTraversal = this.tx().traversal();
+ this.readOnlyTraversal =
+ this.tx().traversal(GraphTraversalSource.build().with(ReadOnlyStrategy.instance()));
+ }
+ return currentTx;
+ }
+
+ public void rollback() {
+ if (this.tx() != null) {
+ this.tx().tx().rollback();
+ this.currentTx = null;
+ this.currentTraversal = null;
+ this.readOnlyTraversal = null;
+ }
+ }
+
+ public void commit() {
+ if (this.tx() != null) {
+ this.tx().tx().commit();
+ this.currentTx = null;
+ this.currentTraversal = null;
+ this.readOnlyTraversal = null;
+ }
+ }
+
+ public Graph tx() {
+ return this.currentTx;
+ }
+
+ public Admin asAdmin() {
+ return admin;
+ }
+
+ public class Admin {
+
+ public GraphTraversalSource getTraversalSource() {
+ return currentTraversal;
+ }
+
+ public GraphTraversalSource getReadOnlyTraversalSource() {
+ return readOnlyTraversal;
+ }
+
+ public JanusGraphManagement getManagementSystem() {
+ return getGraph().openManagement();
+ }
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/serialization/engines/query/GraphTraversalQueryEngine.java b/aai-core/src/main/java/org/onap/aai/serialization/engines/query/GraphTraversalQueryEngine.java
index 94557b08..e012aef3 100644
--- a/aai-core/src/main/java/org/onap/aai/serialization/engines/query/GraphTraversalQueryEngine.java
+++ b/aai-core/src/main/java/org/onap/aai/serialization/engines/query/GraphTraversalQueryEngine.java
@@ -17,8 +17,8 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-package org.onap.aai.serialization.engines.query;
+package org.onap.aai.serialization.engines.query;
import static org.onap.aai.edges.enums.AAIDirection.IN;
import static org.onap.aai.edges.enums.AAIDirection.NONE;
@@ -55,31 +55,32 @@ import org.onap.aai.logging.StopWatch;
*/
public class GraphTraversalQueryEngine extends QueryEngine {
- /**
- * Instantiates a new graph traversal query engine.
- *
- * @param g graph traversal source to traverse the graph
- */
- public GraphTraversalQueryEngine(GraphTraversalSource g) {
- super(g);
- }
+ /**
+ * Instantiates a new graph traversal query engine.
+ *
+ * @param g graph traversal source to traverse the graph
+ */
+ public GraphTraversalQueryEngine(GraphTraversalSource g) {
+ super(g);
+ }
- /**
- * {@inheritDoc}
- */
- @Override
- public List<Vertex> findParents(Vertex start) {
- try {
- StopWatch.conditionalStart();
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public List<Vertex> findParents(Vertex start) {
+ try {
+ StopWatch.conditionalStart();
- @SuppressWarnings("unchecked")
- final GraphTraversal<Vertex, Vertex> pipe = this.g.V(start).emit(v -> true).repeat(__.union(__.inE().has(CONTAINS.toString(), OUT.toString()).outV(), __.outE().has(CONTAINS.toString(), IN.toString()).inV()));
- return pipe.toList();
- }
- finally {
- dbTimeMsecs += StopWatch.stopIfStarted();
- }
- }
+ @SuppressWarnings("unchecked")
+ final GraphTraversal<Vertex, Vertex> pipe = this.g.V(start).emit(v -> true)
+ .repeat(__.union(__.inE().has(CONTAINS.toString(), OUT.toString()).outV(),
+ __.outE().has(CONTAINS.toString(), IN.toString()).inV()));
+ return pipe.toList();
+ } finally {
+ dbTimeMsecs += StopWatch.stopIfStarted();
+ }
+ }
/**
* {@inheritDoc}
@@ -88,80 +89,73 @@ public class GraphTraversalQueryEngine extends QueryEngine {
public List<Vertex> findParents(String[] uris) {
try {
StopWatch.conditionalStart();
- final GraphTraversal<Vertex, Vertex> pipe = this.g.V()
- .has(AAIProperties.AAI_URI, P.within(uris))
- .order().by(AAIProperties.AAI_URI, Order.decr);
+ final GraphTraversal<Vertex, Vertex> pipe =
+ this.g.V().has(AAIProperties.AAI_URI, P.within(uris)).order().by(AAIProperties.AAI_URI, Order.decr);
return pipe.toList();
- }
- finally {
+ } finally {
dbTimeMsecs += StopWatch.stopIfStarted();
}
}
- /**
- * {@inheritDoc}
- */
- @Override
- public List<Vertex> findAllChildren(Vertex start) {
-
- @SuppressWarnings("unchecked")
- GraphTraversal<Vertex, Vertex> pipe = this.g
- .V(start).emit(v -> true).repeat(__.union(__.outE().has(CONTAINS.toString(), OUT.toString()).inV(), __.inE().has(CONTAINS.toString(), IN.toString()).outV()));
-
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public List<Vertex> findAllChildren(Vertex start) {
- return pipe.toList();
+ @SuppressWarnings("unchecked")
+ GraphTraversal<Vertex, Vertex> pipe = this.g.V(start).emit(v -> true)
+ .repeat(__.union(__.outE().has(CONTAINS.toString(), OUT.toString()).inV(),
+ __.inE().has(CONTAINS.toString(), IN.toString()).outV()));
- }
+ return pipe.toList();
- /**
- * {@inheritDoc}
- */
- @Override
- public List<Vertex> findChildrenOfType(Vertex start, String type) {
- @SuppressWarnings("unchecked")
- GraphTraversal<Vertex, Vertex> pipe = this.g.V(start).union(
- __.outE().has(CONTAINS.toString(), OUT.toString()).inV(),
- __.inE().has(CONTAINS.toString(), IN.toString()).outV()
- ).has(AAIProperties.NODE_TYPE, type).dedup();
+ }
- return pipe.toList();
- }
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public List<Vertex> findChildrenOfType(Vertex start, String type) {
+ @SuppressWarnings("unchecked")
+ GraphTraversal<Vertex, Vertex> pipe = this.g.V(start)
+ .union(__.outE().has(CONTAINS.toString(), OUT.toString()).inV(),
+ __.inE().has(CONTAINS.toString(), IN.toString()).outV())
+ .has(AAIProperties.NODE_TYPE, type).dedup();
+
+ return pipe.toList();
+ }
- /**
- * {@inheritDoc}
- */
- @Override
- public List<Vertex> findChildren(Vertex start) {
- @SuppressWarnings("unchecked")
- GraphTraversal<Vertex, Vertex> pipe = this.g.V(start).union(
- __.outE().has(CONTAINS.toString(), OUT.toString()),
- __.inE().has(CONTAINS.toString(), IN.toString())
- ).otherV().dedup();
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public List<Vertex> findChildren(Vertex start) {
+ @SuppressWarnings("unchecked")
+ GraphTraversal<Vertex, Vertex> pipe = this.g.V(start).union(__.outE().has(CONTAINS.toString(), OUT.toString()),
+ __.inE().has(CONTAINS.toString(), IN.toString())).otherV().dedup();
- return pipe.toList();
- }
+ return pipe.toList();
+ }
- /**
- * {@inheritDoc}
- */
- @Override
- public List<Vertex> findDeletable(Vertex start) {
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public List<Vertex> findDeletable(Vertex start) {
try {
StopWatch.conditionalStart();
@SuppressWarnings("unchecked")
- GraphTraversal<Vertex, Vertex> pipe = this.g
- .V(start).emit(v -> true).repeat(
- __.union(
- __.outE().has(DELETE_OTHER_V.toString(), OUT.toString()).inV(),
- __.inE().has(DELETE_OTHER_V.toString(), IN.toString()).outV()
- )
- ).dedup();
+ GraphTraversal<Vertex, Vertex> pipe = this.g.V(start).emit(v -> true)
+ .repeat(__.union(__.outE().has(DELETE_OTHER_V.toString(), OUT.toString()).inV(),
+ __.inE().has(DELETE_OTHER_V.toString(), IN.toString()).outV()))
+ .dedup();
return pipe.toList();
} finally {
dbTimeMsecs += StopWatch.stopIfStarted();
}
- }
+ }
/**
* {@inheritDoc}
@@ -172,119 +166,97 @@ public class GraphTraversalQueryEngine extends QueryEngine {
StopWatch.conditionalStart();
Vertex[] vertices = new Vertex[startVertexes.size()];
vertices = startVertexes.toArray(vertices);
- GraphTraversal<Vertex, Vertex> pipe = this.g
- .V(vertices).emit(v -> true).repeat(
- __.union(
- __.outE().has(DELETE_OTHER_V.toString(), OUT.toString()).inV(),
- __.inE().has(DELETE_OTHER_V.toString(), IN.toString()).outV()
- )
- ).dedup();
+ GraphTraversal<Vertex, Vertex> pipe = this.g.V(vertices).emit(v -> true)
+ .repeat(__.union(__.outE().has(DELETE_OTHER_V.toString(), OUT.toString()).inV(),
+ __.inE().has(DELETE_OTHER_V.toString(), IN.toString()).outV()))
+ .dedup();
return pipe.toList();
- }
- finally {
+ } finally {
dbTimeMsecs += StopWatch.stopIfStarted();
}
}
- /**
- * {@inheritDoc}
- */
- @Override
- public List<Vertex> findRelatedVertices(Vertex start, Direction direction, String label, String nodeType) {
- GraphTraversal<Vertex, Vertex> pipe = this.g.V(start);
- switch (direction) {
- case OUT:
- pipe.out(label);
- break;
- case IN:
- pipe.in(label);
- break;
- case BOTH:
- pipe.both(label);
- break;
- default:
- break;
- }
-
- pipe.has(AAIProperties.NODE_TYPE, nodeType).dedup();
- return pipe.toList();
- }
-
- @Override
- public Tree<Element> findSubGraph(Vertex start, int iterations, boolean nodeOnly) {
- final GraphTraversal<Vertex, ?> t = this.g.V(start).emit(v -> true).times(iterations).repeat(
- __.union(
- __.outE().has(CONTAINS.toString(), OUT.toString()).inV(),
- __.inE().has(CONTAINS.toString(), IN.toString()).outV())
- );
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public List<Vertex> findRelatedVertices(Vertex start, Direction direction, String label, String nodeType) {
+ GraphTraversal<Vertex, Vertex> pipe = this.g.V(start);
+ switch (direction) {
+ case OUT:
+ pipe.out(label);
+ break;
+ case IN:
+ pipe.in(label);
+ break;
+ case BOTH:
+ pipe.both(label);
+ break;
+ default:
+ break;
+ }
- if (!nodeOnly) {
- t.union(
- __.identity(),
- __.bothE().has(CONTAINS.toString(), NONE.toString()).dedup().otherV()
- );
- }
- t.tree();
- if (t.hasNext()) {
- return (Tree)t.next();
- } else {
- return new Tree();
- }
- }
+ pipe.has(AAIProperties.NODE_TYPE, nodeType).dedup();
+ return pipe.toList();
+ }
- @Override
- public List<Edge> findEdgesForVersion(Vertex start, Loader loader) {
- // From the given start vertex find both the
- // out edges that has property CONTAINS set to NONE
- // whose in vertexes has an object that is declared in the oxm
- // And do the same thing vice versa to get a list of edges
- // Then check that the edge should not have the property private set to true
- // and remove the duplicates and return the list of edges
- final Set<String> objects = loader.getAllObjects().keySet();
- GraphTraversal<Vertex, Edge> pipeline = this.g
- .V(start)
- .union(
- __.inE().has(CONTAINS.toString(), NONE.toString()).where(__.outV().has(AAIProperties.NODE_TYPE, P.within(objects))),
- __.outE().has(CONTAINS.toString(), NONE.toString()).where(__.inV().has(AAIProperties.NODE_TYPE, P.within(objects)))
- )
- .not(
- __.has("private", true)
- )
- .dedup();
+ @Override
+ public Tree<Element> findSubGraph(Vertex start, int iterations, boolean nodeOnly) {
+ final GraphTraversal<Vertex, ?> t = this.g.V(start).emit(v -> true).times(iterations)
+ .repeat(__.union(__.outE().has(CONTAINS.toString(), OUT.toString()).inV(),
+ __.inE().has(CONTAINS.toString(), IN.toString()).outV()));
- return pipeline.toList();
- }
+ if (!nodeOnly) {
+ t.union(__.identity(), __.bothE().has(CONTAINS.toString(), NONE.toString()).dedup().otherV());
+ }
+ t.tree();
+ if (t.hasNext()) {
+ return (Tree) t.next();
+ } else {
+ return new Tree();
+ }
+ }
+ @Override
+ public List<Edge> findEdgesForVersion(Vertex start, Loader loader) {
+ // From the given start vertex find both the
+ // out edges that has property CONTAINS set to NONE
+ // whose in vertexes has an object that is declared in the oxm
+ // And do the same thing vice versa to get a list of edges
+ // Then check that the edge should not have the property private set to true
+ // and remove the duplicates and return the list of edges
+ final Set<String> objects = loader.getAllObjects().keySet();
+ GraphTraversal<Vertex, Edge> pipeline = this.g.V(start)
+ .union(__.inE().has(CONTAINS.toString(), NONE.toString())
+ .where(__.outV().has(AAIProperties.NODE_TYPE, P.within(objects))),
+ __.outE().has(CONTAINS.toString(), NONE.toString())
+ .where(__.inV().has(AAIProperties.NODE_TYPE, P.within(objects))))
+ .not(__.has("private", true)).dedup();
+
+ return pipeline.toList();
+ }
- @Override
- public List<Vertex> findCousinVertices(Vertex start, String... labels) {
- // Start at the given vertex
- // Do a union to copy the start vertex to be run against all
- // so for the start vertex it gets all of in edges that contains other v set to none
- // and also all the other out edges with contains other v set to none
- // And filter the edges based on the property private not set
+ @Override
+ public List<Vertex> findCousinVertices(Vertex start, String... labels) {
+ // Start at the given vertex
+ // Do a union to copy the start vertex to be run against all
+ // so for the start vertex it gets all of in edges that contains other v set to none
+ // and also all the other out edges with contains other v set to none
+ // And filter the edges based on the property private not set
// so that means it will be a regular edge
- // and find the other end of the vertex so if setup like this:
- // v2 -> e1 -> v3
- // It will return v3
- GraphTraversal<Vertex, Vertex> pipeline = this.g
- .V(start)
- .union(
- __.inE(labels).has(CONTAINS.toString(), NONE.toString()),
- __.outE(labels).has(CONTAINS.toString(), NONE.toString())
- )
- .not(
- __.has(PRIVATE.toString(), true)
- )
- .otherV()
- .dedup();
-
- return pipeline.toList();
- }
+ // and find the other end of the vertex so if setup like this:
+ // v2 -> e1 -> v3
+ // It will return v3
+ GraphTraversal<Vertex, Vertex> pipeline = this.g.V(start)
+ .union(__.inE(labels).has(CONTAINS.toString(), NONE.toString()),
+ __.outE(labels).has(CONTAINS.toString(), NONE.toString()))
+ .not(__.has(PRIVATE.toString(), true)).otherV().dedup();
+
+ return pipeline.toList();
+ }
- public double getDBTimeMsecs() {
- return (dbTimeMsecs);
- }
+ public double getDBTimeMsecs() {
+ return (dbTimeMsecs);
+ }
}
-
diff --git a/aai-core/src/main/java/org/onap/aai/serialization/engines/query/GremlinPipelineQueryEngine.java b/aai-core/src/main/java/org/onap/aai/serialization/engines/query/GremlinPipelineQueryEngine.java
index 74a23ef9..c206ced7 100644
--- a/aai-core/src/main/java/org/onap/aai/serialization/engines/query/GremlinPipelineQueryEngine.java
+++ b/aai-core/src/main/java/org/onap/aai/serialization/engines/query/GremlinPipelineQueryEngine.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,
@@ -17,188 +17,189 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.serialization.engines.query;/*-
- * ============LICENSE_START=======================================================
- * org.onap.aai
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * ============LICENSE_START=======================================================
+ * org.onap.aai
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+/*
+ * package org.onap.aai.serialization.engines.query;
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * import java.util.HashSet;
+ * import java.util.List;
+ * import java.util.Set;
*
- * 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=========================================================
+ * import org.onap.aai.db.AAIProperties;
+ * import org.onap.aai.query.builder.QueryBuilder;
+ * import org.onap.aai.serialization.engines.TransactionalGraphEngine;
+ * import com.tinkerpop.blueprints.Direction;
+ * import com.tinkerpop.blueprints.TransactionalGraph;
+ * import com.tinkerpop.blueprints.Vertex;
+ * import com.tinkerpop.gremlin.java.GremlinPipeline;
+ * import com.tinkerpop.pipes.IdentityPipe;
+ * import com.tinkerpop.pipes.PipeFunction;
+ * import com.tinkerpop.pipes.branch.LoopPipe;
+ *
+ * public class GremlinPipelineQueryEngine extends QueryEngine {
+ *
+ * public GremlinPipelineQueryEngine(TransactionalGraphEngine graphEngine) {
+ * super(graphEngine);
+ * }
+ *
+ * @Override
+ * public List<Vertex> executeQuery(TransactionalGraph g, QueryBuilder query) {
+ * List<Vertex> results = null;
+ * Vertex start = query.getStart();
+ * if (start != null) {
+ * results = ((GremlinPipeline)query.getQuery()).cast(Vertex.class).toList();
+ * } else {
+ * GremlinPipeline pipe = new GremlinPipeline(g);
+ * results = process(pipe, (GremlinPipeline)query.getQuery());
+ *
+ * }
+ * return results;
+ * }
+ *
+ * @Override
+ * public List<Vertex> executeParentQuery(TransactionalGraph g, QueryBuilder query) {
+ * List<Vertex> results = null;
+ * Vertex start = query.getStart();
+ * if (start != null) {
+ * results = ((GremlinPipeline)query.getParentQuery()).cast(Vertex.class).toList();
+ * } else {
+ * GremlinPipeline pipe = new GremlinPipeline(g);
+ * results = process(pipe, (GremlinPipeline)query.getParentQuery());
+ *
+ * }
+ * return results;
+ * }
+ *
+ * @Override
+ * public List<Vertex> findParents(Vertex start) {
+ * GremlinPipeline<Vertex, Vertex> pipe = new GremlinPipeline(start).as("x").inE()
+ * .has("isParent", true).outV().loop("x", new PipeFunction<LoopPipe.LoopBundle<Vertex>, Boolean>() {
+ *
+ * @Override
+ * public Boolean compute(LoopPipe.LoopBundle<Vertex> argument) {
+ * GremlinPipeline<Vertex, Long> pipe = new GremlinPipeline<>(argument.getObject());
+ * return pipe.inE().has("isParent", true).count() == 1 || argument.getLoops() < 100;
+ * }
+ *
+ * }, new PipeFunction<LoopPipe.LoopBundle<Vertex>, Boolean>() {
+ *
+ * @Override
+ * public Boolean compute(LoopPipe.LoopBundle<Vertex> argument) {
+ * return true;
+ * }
+ *
+ * });
+ *
+ * List<Vertex> results = pipe.toList();
+ * results.add(0, start);
+ * return results;
+ * }
+ *
+ * @Override
+ * public List<Vertex> findChildren(Vertex start) {
+ * Set<Vertex> seen = new HashSet<>();
+ * seen.add(start);
+ * GremlinPipeline<Vertex, Vertex> pipe = new GremlinPipeline(start).as("x").outE().has("isParent", true).inV()
+ * .except(seen).store(seen).loop("x", new PipeFunction<LoopPipe.LoopBundle<Vertex>, Boolean>() {
+ *
+ * @Override
+ * public Boolean compute(LoopPipe.LoopBundle<Vertex> argument) {
+ * GremlinPipeline<Vertex, Long> pipe = new GremlinPipeline<>(argument.getObject());
+ * return pipe.outE().has("isParent", true).count() >= 1 || argument.getLoops() < 100;
+ * }
+ *
+ * }, new PipeFunction<LoopPipe.LoopBundle<Vertex>, Boolean>() {
+ *
+ * @Override
+ * public Boolean compute(LoopPipe.LoopBundle<Vertex> argument) {
+ * return true;
+ * }
+ *
+ * });
+ *
+ * List<Vertex> results = pipe.toList();
+ * results.add(0, start);
+ * return results;
+ * }
+ *
+ * @Override
+ * public List<Vertex> findDeletable(Vertex start) {
+ * Set<Vertex> seen = new HashSet<>();
+ * seen.add(start);
+ * GremlinPipeline<Vertex, Vertex> pipe = new GremlinPipeline<Vertex, Vertex>(start).as("x").outE().or(
+ * new GremlinPipeline(new IdentityPipe()).has("isParent", true),
+ * new GremlinPipeline(new IdentityPipe()).has("hasDelTarget", true)).inV()
+ * .except(seen).store(seen).loop("x", new PipeFunction<LoopPipe.LoopBundle<Vertex>, Boolean>() {
+ *
+ * @Override
+ * public Boolean compute(LoopPipe.LoopBundle<Vertex> argument) {
+ * GremlinPipeline<Vertex, Long> pipe = new GremlinPipeline<>(argument.getObject());
+ * return pipe.outE().or(
+ * new GremlinPipeline(new IdentityPipe()).has("isParent", true),
+ * new GremlinPipeline(new IdentityPipe()).has("hasDelTarget", true)).count() >= 1 || argument.getLoops() < 100;
+ * }
+ *
+ * }, new PipeFunction<LoopPipe.LoopBundle<Vertex>, Boolean>() {
+ *
+ * @Override
+ * public Boolean compute(LoopPipe.LoopBundle<Vertex> argument) {
+ * return true;
+ * }
+ *
+ * });
+ * List<Vertex> results = pipe.toList();
+ * results.add(0, start);
+ *
+ * return results;
+ * }
+ *
+ * private List<Vertex> process(GremlinPipeline start, GremlinPipeline pipe) {
+ *
+ *
+ * return start.add(pipe).cast(Vertex.class).toList();
+ * }
+ *
+ * @Override
+ * public List<Vertex> findRelatedVertices(Vertex start, Direction direction, String label, String nodeType) {
+ * GremlinPipeline<Vertex, Vertex> pipe = new GremlinPipeline<Vertex, Vertex>(start);
+ * switch (direction) {
+ * case OUT:
+ * pipe.out(label);
+ * break;
+ * case IN:
+ * pipe.in(label);
+ * break;
+ * case BOTH:
+ * pipe.both(label);
+ * break;
+ * default:
+ * break;
+ * }
+ *
+ * pipe.has(AAIProperties.NODE_TYPE, nodeType).dedup();
+ * List<Vertex> result = pipe.toList();
+ * return result;
+ * }
+ *
+ * }
*/
-
-/*
-package org.onap.aai.serialization.engines.query;
-
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-import org.onap.aai.db.AAIProperties;
-import org.onap.aai.query.builder.QueryBuilder;
-import org.onap.aai.serialization.engines.TransactionalGraphEngine;
-import com.tinkerpop.blueprints.Direction;
-import com.tinkerpop.blueprints.TransactionalGraph;
-import com.tinkerpop.blueprints.Vertex;
-import com.tinkerpop.gremlin.java.GremlinPipeline;
-import com.tinkerpop.pipes.IdentityPipe;
-import com.tinkerpop.pipes.PipeFunction;
-import com.tinkerpop.pipes.branch.LoopPipe;
-
-public class GremlinPipelineQueryEngine extends QueryEngine {
-
- public GremlinPipelineQueryEngine(TransactionalGraphEngine graphEngine) {
- super(graphEngine);
- }
-
- @Override
- public List<Vertex> executeQuery(TransactionalGraph g, QueryBuilder query) {
- List<Vertex> results = null;
- Vertex start = query.getStart();
- if (start != null) {
- results = ((GremlinPipeline)query.getQuery()).cast(Vertex.class).toList();
- } else {
- GremlinPipeline pipe = new GremlinPipeline(g);
- results = process(pipe, (GremlinPipeline)query.getQuery());
-
- }
- return results;
- }
-
- @Override
- public List<Vertex> executeParentQuery(TransactionalGraph g, QueryBuilder query) {
- List<Vertex> results = null;
- Vertex start = query.getStart();
- if (start != null) {
- results = ((GremlinPipeline)query.getParentQuery()).cast(Vertex.class).toList();
- } else {
- GremlinPipeline pipe = new GremlinPipeline(g);
- results = process(pipe, (GremlinPipeline)query.getParentQuery());
-
- }
- return results;
- }
-
- @Override
- public List<Vertex> findParents(Vertex start) {
- GremlinPipeline<Vertex, Vertex> pipe = new GremlinPipeline(start).as("x").inE()
- .has("isParent", true).outV().loop("x", new PipeFunction<LoopPipe.LoopBundle<Vertex>, Boolean>() {
-
- @Override
- public Boolean compute(LoopPipe.LoopBundle<Vertex> argument) {
- GremlinPipeline<Vertex, Long> pipe = new GremlinPipeline<>(argument.getObject());
- return pipe.inE().has("isParent", true).count() == 1 || argument.getLoops() < 100;
- }
-
- }, new PipeFunction<LoopPipe.LoopBundle<Vertex>, Boolean>() {
-
- @Override
- public Boolean compute(LoopPipe.LoopBundle<Vertex> argument) {
- return true;
- }
-
- });
-
- List<Vertex> results = pipe.toList();
- results.add(0, start);
- return results;
- }
-
- @Override
- public List<Vertex> findChildren(Vertex start) {
- Set<Vertex> seen = new HashSet<>();
- seen.add(start);
- GremlinPipeline<Vertex, Vertex> pipe = new GremlinPipeline(start).as("x").outE().has("isParent", true).inV()
- .except(seen).store(seen).loop("x", new PipeFunction<LoopPipe.LoopBundle<Vertex>, Boolean>() {
-
- @Override
- public Boolean compute(LoopPipe.LoopBundle<Vertex> argument) {
- GremlinPipeline<Vertex, Long> pipe = new GremlinPipeline<>(argument.getObject());
- return pipe.outE().has("isParent", true).count() >= 1 || argument.getLoops() < 100;
- }
-
- }, new PipeFunction<LoopPipe.LoopBundle<Vertex>, Boolean>() {
-
- @Override
- public Boolean compute(LoopPipe.LoopBundle<Vertex> argument) {
- return true;
- }
-
- });
-
- List<Vertex> results = pipe.toList();
- results.add(0, start);
- return results;
- }
-
- @Override
- public List<Vertex> findDeletable(Vertex start) {
- Set<Vertex> seen = new HashSet<>();
- seen.add(start);
- GremlinPipeline<Vertex, Vertex> pipe = new GremlinPipeline<Vertex, Vertex>(start).as("x").outE().or(
- new GremlinPipeline(new IdentityPipe()).has("isParent", true),
- new GremlinPipeline(new IdentityPipe()).has("hasDelTarget", true)).inV()
- .except(seen).store(seen).loop("x", new PipeFunction<LoopPipe.LoopBundle<Vertex>, Boolean>() {
-
- @Override
- public Boolean compute(LoopPipe.LoopBundle<Vertex> argument) {
- GremlinPipeline<Vertex, Long> pipe = new GremlinPipeline<>(argument.getObject());
- return pipe.outE().or(
- new GremlinPipeline(new IdentityPipe()).has("isParent", true),
- new GremlinPipeline(new IdentityPipe()).has("hasDelTarget", true)).count() >= 1 || argument.getLoops() < 100;
- }
-
- }, new PipeFunction<LoopPipe.LoopBundle<Vertex>, Boolean>() {
-
- @Override
- public Boolean compute(LoopPipe.LoopBundle<Vertex> argument) {
- return true;
- }
-
- });
- List<Vertex> results = pipe.toList();
- results.add(0, start);
-
- return results;
- }
-
- private List<Vertex> process(GremlinPipeline start, GremlinPipeline pipe) {
-
-
- return start.add(pipe).cast(Vertex.class).toList();
- }
-
- @Override
- public List<Vertex> findRelatedVertices(Vertex start, Direction direction, String label, String nodeType) {
- GremlinPipeline<Vertex, Vertex> pipe = new GremlinPipeline<Vertex, Vertex>(start);
- switch (direction) {
- case OUT:
- pipe.out(label);
- break;
- case IN:
- pipe.in(label);
- break;
- case BOTH:
- pipe.both(label);
- break;
- default:
- break;
- }
-
- pipe.has(AAIProperties.NODE_TYPE, nodeType).dedup();
- List<Vertex> result = pipe.toList();
- return result;
- }
-
-}
-*/
diff --git a/aai-core/src/main/java/org/onap/aai/serialization/engines/query/GremlinQueryEngine.java b/aai-core/src/main/java/org/onap/aai/serialization/engines/query/GremlinQueryEngine.java
index 18394ddc..568ff839 100644
--- a/aai-core/src/main/java/org/onap/aai/serialization/engines/query/GremlinQueryEngine.java
+++ b/aai-core/src/main/java/org/onap/aai/serialization/engines/query/GremlinQueryEngine.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,
@@ -17,178 +17,179 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.serialization.engines.query;/*-
- * ============LICENSE_START=======================================================
- * org.onap.aai
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
+ * ============LICENSE_START=======================================================
+ * org.onap.aai
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
//
-//package org.onap.aai.serialization.engines.query;
-//
-//import java.util.List;
-//import java.util.regex.Matcher;
-//import java.util.regex.Pattern;
-//
-//import org.apache.commons.collections.IteratorUtils;
-//
-//import org.onap.aai.db.AAIProperties;
-//import org.onap.aai.query.builder.QueryBuilder;
-//import org.onap.aai.serialization.engines.TransactionalGraphEngine;
-//import com.tinkerpop.blueprints.Direction;
-//import com.tinkerpop.blueprints.Graph;
-//import com.tinkerpop.blueprints.TransactionalGraph;
-//import com.tinkerpop.blueprints.Vertex;
-//import com.tinkerpop.gremlin.groovy.Gremlin;
-//import com.tinkerpop.gremlin.java.GremlinPipeline;
-//import com.tinkerpop.pipes.Pipe;
-//import com.tinkerpop.pipes.util.iterators.SingleIterator;
-//
-//public class GremlinQueryEngine extends QueryEngine {
-//
-// public GremlinQueryEngine (TransactionalGraphEngine engine) {
-// super(engine);
-//
-// }
-//
-//
-// @Override
-// public List<Vertex> executeQuery(TransactionalGraph g, QueryBuilder query) {
-// List<Vertex> result = null;
-// Vertex start = query.getStart();
-// if (start != null) {
-// result = this.executeQuery(start, (String)query.getQuery());
-// } else {
-// result = this.processGremlinQuery((String)query.getQuery());
-// }
-// return result;
-//
-// }
-//
-// @Override
-// public List<Vertex> executeParentQuery(TransactionalGraph g, QueryBuilder query) {
-//
-// List<Vertex> result = null;
-// Vertex start = query.getStart();
-// if (start != null) {
-// result = this.executeQuery(start, (String)query.getParentQuery());
-// } else {
-// result = this.processGremlinQuery((String)query.getParentQuery());
-// }
-// return result;
-// }
-//
-// private List<Vertex> executeQuery(Vertex startVertex, String query) {
-//
-// return this.processGremlinQuery(startVertex, "_()" + query);
-//
-// }
-//
-// @Override
-// public List<Vertex> findParents(Vertex start) {
-//
-// String findAllParents = ".as('x').inE.has('isParent', true).outV"
-// + ".loop('x'){it.object.inE.has('isParent',true).count()==1}{true}";
-//
-// List<Vertex> results = this.executeQuery(start, findAllParents);
-// results.add(0, start);
-// return results;
-//
-// }
-//
-// @Override
-// public List<Vertex> findChildren(Vertex start) {
-// String findAllChildren = ".as('x').outE.has('isParent', true).inV"
-// + ".loop('x'){it.object.outE.has('isParent', true).count() >= 1}{true}";
-//
-// List<Vertex> results = this.executeQuery(start, findAllChildren);
-// results.add(0, start);
-// return results;
-//
-// }
-//
-// @Override
-// public List<Vertex> findDeletable(Vertex start) {
-// String findAllChildren = ".as('x').outE.or(_().has('isParent', true), _().has('hasDelTarget', true)).inV"
-// + ".loop('x'){it.object.outE.or(_().has('isParent', true), _().has('hasDelTarget', true)).count() >= 1}{true}";
-//
-// List<Vertex> results = this.executeQuery(start, findAllChildren);
-// results.add(0, start);
-// return results;
-// }
-// private List<Vertex> processGremlinQuery(String query) {
-//
-// Pattern firstHasSet = Pattern.compile("^(\\.has\\(.*?\\))(\\.has\\(.*?\\))*(?!\\.has)");
-// Pattern p = Pattern.compile("\\.has\\('(.*?)',\\s?'(.*?)'\\)");
-// Matcher m = firstHasSet.matcher(query);
-// List<Vertex> results = null;
-// GremlinPipeline<Graph, Vertex> pipe = new GremlinPipeline<>(dbEngine.getGraph());
-// if (m.find()) {
-// String hasSet = m.group();
-// query = query.replace(m.group(0), "");
-// m = p.matcher(hasSet);
-// pipe.V();
-// while (m.find()) {
-// pipe.has(m.group(1), m.group(2));
-// }
-// results = processGremlinQuery(pipe.toList(), "_()" + query);
-// }
-//
-// return results;
-//
-// }
-// private List<Vertex> processGremlinQuery(Vertex startVertex, String query) {
-//
-// Pipe pipe = Gremlin.compile(query);
-// pipe.setStarts(new SingleIterator<Vertex>(startVertex));
-//
-// return (List<Vertex>)IteratorUtils.toList(pipe.iterator());
-// }
-// private List<Vertex> processGremlinQuery(List<Vertex> list, String query) {
-//
-// Pipe pipe = Gremlin.compile(query);
-//
-// pipe.setStarts(list);
-//
-// return (List<Vertex>)IteratorUtils.toList(pipe.iterator());
-// }
-//
-//
-// @Override
-// public List<Vertex> findRelatedVertices(Vertex start, Direction direction, String label, String nodeType) {
-// String findRelatedVertices = "_()";
-// switch (direction) {
-// case OUT:
-// findRelatedVertices += ".out('" + label + "')";
-// break;
-// case IN:
-// findRelatedVertices += ".in('" + label + "')";
-// break;
-// case BOTH:
-// findRelatedVertices += ".both('" + label + "')";
-// break;
-// default:
-// break;
-// }
-// findRelatedVertices += ".has('" + AAIProperties.NODE_TYPE + "', '" + nodeType + "').dedup()";
-// List<Vertex> results = this.executeQuery(start, findRelatedVertices);
-// results.add(0, start);
-// return results;
-// }
-//
-//}
+// package org.onap.aai.serialization.engines.query;
+//
+// import java.util.List;
+// import java.util.regex.Matcher;
+// import java.util.regex.Pattern;
+//
+// import org.apache.commons.collections.IteratorUtils;
+//
+// import org.onap.aai.db.AAIProperties;
+// import org.onap.aai.query.builder.QueryBuilder;
+// import org.onap.aai.serialization.engines.TransactionalGraphEngine;
+// import com.tinkerpop.blueprints.Direction;
+// import com.tinkerpop.blueprints.Graph;
+// import com.tinkerpop.blueprints.TransactionalGraph;
+// import com.tinkerpop.blueprints.Vertex;
+// import com.tinkerpop.gremlin.groovy.Gremlin;
+// import com.tinkerpop.gremlin.java.GremlinPipeline;
+// import com.tinkerpop.pipes.Pipe;
+// import com.tinkerpop.pipes.util.iterators.SingleIterator;
+//
+// public class GremlinQueryEngine extends QueryEngine {
+//
+// public GremlinQueryEngine (TransactionalGraphEngine engine) {
+// super(engine);
+//
+// }
+//
+//
+// @Override
+// public List<Vertex> executeQuery(TransactionalGraph g, QueryBuilder query) {
+// List<Vertex> result = null;
+// Vertex start = query.getStart();
+// if (start != null) {
+// result = this.executeQuery(start, (String)query.getQuery());
+// } else {
+// result = this.processGremlinQuery((String)query.getQuery());
+// }
+// return result;
+//
+// }
+//
+// @Override
+// public List<Vertex> executeParentQuery(TransactionalGraph g, QueryBuilder query) {
+//
+// List<Vertex> result = null;
+// Vertex start = query.getStart();
+// if (start != null) {
+// result = this.executeQuery(start, (String)query.getParentQuery());
+// } else {
+// result = this.processGremlinQuery((String)query.getParentQuery());
+// }
+// return result;
+// }
+//
+// private List<Vertex> executeQuery(Vertex startVertex, String query) {
+//
+// return this.processGremlinQuery(startVertex, "_()" + query);
+//
+// }
+//
+// @Override
+// public List<Vertex> findParents(Vertex start) {
+//
+// String findAllParents = ".as('x').inE.has('isParent', true).outV"
+// + ".loop('x'){it.object.inE.has('isParent',true).count()==1}{true}";
+//
+// List<Vertex> results = this.executeQuery(start, findAllParents);
+// results.add(0, start);
+// return results;
+//
+// }
+//
+// @Override
+// public List<Vertex> findChildren(Vertex start) {
+// String findAllChildren = ".as('x').outE.has('isParent', true).inV"
+// + ".loop('x'){it.object.outE.has('isParent', true).count() >= 1}{true}";
+//
+// List<Vertex> results = this.executeQuery(start, findAllChildren);
+// results.add(0, start);
+// return results;
+//
+// }
+//
+// @Override
+// public List<Vertex> findDeletable(Vertex start) {
+// String findAllChildren = ".as('x').outE.or(_().has('isParent', true), _().has('hasDelTarget', true)).inV"
+// + ".loop('x'){it.object.outE.or(_().has('isParent', true), _().has('hasDelTarget', true)).count() >= 1}{true}";
+//
+// List<Vertex> results = this.executeQuery(start, findAllChildren);
+// results.add(0, start);
+// return results;
+// }
+// private List<Vertex> processGremlinQuery(String query) {
+//
+// Pattern firstHasSet = Pattern.compile("^(\\.has\\(.*?\\))(\\.has\\(.*?\\))*(?!\\.has)");
+// Pattern p = Pattern.compile("\\.has\\('(.*?)',\\s?'(.*?)'\\)");
+// Matcher m = firstHasSet.matcher(query);
+// List<Vertex> results = null;
+// GremlinPipeline<Graph, Vertex> pipe = new GremlinPipeline<>(dbEngine.getGraph());
+// if (m.find()) {
+// String hasSet = m.group();
+// query = query.replace(m.group(0), "");
+// m = p.matcher(hasSet);
+// pipe.V();
+// while (m.find()) {
+// pipe.has(m.group(1), m.group(2));
+// }
+// results = processGremlinQuery(pipe.toList(), "_()" + query);
+// }
+//
+// return results;
+//
+// }
+// private List<Vertex> processGremlinQuery(Vertex startVertex, String query) {
+//
+// Pipe pipe = Gremlin.compile(query);
+// pipe.setStarts(new SingleIterator<Vertex>(startVertex));
+//
+// return (List<Vertex>)IteratorUtils.toList(pipe.iterator());
+// }
+// private List<Vertex> processGremlinQuery(List<Vertex> list, String query) {
+//
+// Pipe pipe = Gremlin.compile(query);
+//
+// pipe.setStarts(list);
+//
+// return (List<Vertex>)IteratorUtils.toList(pipe.iterator());
+// }
+//
+//
+// @Override
+// public List<Vertex> findRelatedVertices(Vertex start, Direction direction, String label, String nodeType) {
+// String findRelatedVertices = "_()";
+// switch (direction) {
+// case OUT:
+// findRelatedVertices += ".out('" + label + "')";
+// break;
+// case IN:
+// findRelatedVertices += ".in('" + label + "')";
+// break;
+// case BOTH:
+// findRelatedVertices += ".both('" + label + "')";
+// break;
+// default:
+// break;
+// }
+// findRelatedVertices += ".has('" + AAIProperties.NODE_TYPE + "', '" + nodeType + "').dedup()";
+// List<Vertex> results = this.executeQuery(start, findRelatedVertices);
+// results.add(0, start);
+// return results;
+// }
+//
+// }
//
diff --git a/aai-core/src/main/java/org/onap/aai/serialization/engines/query/QueryEngine.java b/aai-core/src/main/java/org/onap/aai/serialization/engines/query/QueryEngine.java
index 1e2da4b8..4f30b564 100644
--- a/aai-core/src/main/java/org/onap/aai/serialization/engines/query/QueryEngine.java
+++ b/aai-core/src/main/java/org/onap/aai/serialization/engines/query/QueryEngine.java
@@ -17,8 +17,11 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.serialization.engines.query;
+import java.util.List;
+
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.process.traversal.step.util.Tree;
import org.apache.tinkerpop.gremlin.structure.Direction;
@@ -28,29 +31,28 @@ import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.onap.aai.db.props.AAIProperties;
import org.onap.aai.introspection.Loader;
-import java.util.List;
-
public abstract class QueryEngine {
- final protected GraphTraversalSource g;
- protected double dbTimeMsecs = 0;
- /**
- * Instantiates a new query engine.
- *
- * @param g graph traversal source to traverse the graph
- */
- public QueryEngine (GraphTraversalSource g) {
- this.g = g;
- }
-
- /**
- * Finds all the parents/grandparents/etc of the given start node.
- *
- * @param start - the start vertex whose parent chain you want
- * @return the list of start and start's parent, grandparent, etc, in
- * order (ie {start, parent, grandparent, etc}
- */
- public abstract List<Vertex> findParents(Vertex start);
+ final protected GraphTraversalSource g;
+ protected double dbTimeMsecs = 0;
+
+ /**
+ * Instantiates a new query engine.
+ *
+ * @param g graph traversal source to traverse the graph
+ */
+ public QueryEngine(GraphTraversalSource g) {
+ this.g = g;
+ }
+
+ /**
+ * Finds all the parents/grandparents/etc of the given start node.
+ *
+ * @param start - the start vertex whose parent chain you want
+ * @return the list of start and start's parent, grandparent, etc, in
+ * order (ie {start, parent, grandparent, etc}
+ */
+ public abstract List<Vertex> findParents(Vertex start);
/**
* Finds all the parents/grandparents/etc of the given start node.
@@ -62,113 +64,115 @@ public abstract class QueryEngine {
* as the number of different type of edges keeps growing that call
* will be more expensive than using the aai-uri's as they are fast lookup
*
- * @param uris - list of the uris representing the aai-uris of
- * parent, grandparent, etc
+ * @param uris - list of the uris representing the aai-uris of
+ * parent, grandparent, etc
* @return the list of start and start's parent, grandparent, etc, in
- * order (ie {start, parent, grandparent, etc}
+ * order (ie {start, parent, grandparent, etc}
+ */
+ public abstract List<Vertex> findParents(String[] uris);
+
+ /**
+ * Finds all children, grandchildren, etc of start
+ *
+ * @param start the start vertex
+ * @return the list of child/grandchild/etc vertices
+ */
+ public abstract List<Vertex> findAllChildren(Vertex start);
+
+ /**
+ * Finds all immediate children of start (no grandchildren or so forth) of the given type
+ *
+ * @param start - the start vertex
+ * @param type - the desired aai-node-type
+ * @return the list of immediate child vertices of given type
+ */
+ public abstract List<Vertex> findChildrenOfType(Vertex start, String type);
+
+ /**
+ * Finds all immediate children of start (no grandchildren or so forth)
+ *
+ * @param start - the start vertex
+ * @return the list of immediate child vertices
*/
- public abstract List<Vertex> findParents(String [] uris);
-
- /**
- * Finds all children, grandchildren, etc of start
- *
- * @param start the start vertex
- * @return the list of child/grandchild/etc vertices
- */
- public abstract List<Vertex> findAllChildren(Vertex start);
-
- /**
- * Finds all immediate children of start (no grandchildren or so forth) of the given type
- * @param start - the start vertex
- * @param type - the desired aai-node-type
- * @return the list of immediate child vertices of given type
- */
- public abstract List<Vertex> findChildrenOfType(Vertex start, String type);
-
- /**
- * Finds all immediate children of start (no grandchildren or so forth)
- * @param start - the start vertex
- * @return the list of immediate child vertices
- */
- public abstract List<Vertex> findChildren(Vertex start);
-
- /**
- * Find all vertices that should be deleted in a cascade from a delete of start
- *
- * @param start - the start vertex
- * @return the list of vertices to be deleted when start is deleted
- */
- public abstract List<Vertex> findDeletable(Vertex start);
+ public abstract List<Vertex> findChildren(Vertex start);
+
+ /**
+ * Find all vertices that should be deleted in a cascade from a delete of start
+ *
+ * @param start - the start vertex
+ * @return the list of vertices to be deleted when start is deleted
+ */
+ public abstract List<Vertex> findDeletable(Vertex start);
/**
* Find all vertices that should be deleted in a cascade from a delete of start vertexes
*
- * @param startVertexes Specifies the list of start vertexes
+ * @param startVertexes Specifies the list of start vertexes
*
- * @return the list of vertices to be deleted when start list of vertexes is deleted
+ * @return the list of vertices to be deleted when start list of vertexes is deleted
*/
public abstract List<Vertex> findDeletable(List<Vertex> startVertexes);
- /**
- * Finds the subgraph under start, including cousins as well as start's children/grandchildren/etc.
- * More specifically, this includes start, all its descendants, start's cousins, and start's
- * descendants' cousins (but not any of the cousins' cousins or descendants), and the edges
- * connecting them.
- *
- * @param start - the start vertex
- * @return - Tree containing nodes and edges of the subgraph
- */
- public Tree<Element> findSubGraph(Vertex start) {
- return findSubGraph(start, AAIProperties.MAXIMUM_DEPTH, false);
- }
-
- /**
- * Finds the subgraph under start, including cousins as well as start's children/grandchildren/etc.
- * More specifically, this includes start, all its descendants, start's cousins, and start's
- * descendants' cousins (but not any of the cousins' cousins or descendants), and the edges
- * connecting them.
- *
- * @param start - the start vertex
- * @param iterations - depth of the subgraph, this limits how many generations of
- * descendants are included
- * @param nodeOnly - if true the subgraph will NOT include the cousins
- * @return Tree containing nodes and edges of the subgraph
- */
- public abstract Tree<Element> findSubGraph(Vertex start, int iterations, boolean nodeOnly);
-
- /**
- * Find vertices of type nodeType related to start by edges of the given
- * direction and label.
- *
- * @param start - the start vertex
- * @param direction - the direction of edges to traverse from start
- * @param label - the label of edges to traverse from start
- * @param nodeType - the node type the results should be
- * @return the list of related vertices
- */
- public abstract List<Vertex> findRelatedVertices(Vertex start, Direction direction, String label, String nodeType);
-
- /**
- * Finds cousin edges connecting start to other vertices only of types defined in an old version.
- * The idea is that if a user is using an old version, they won't understand any new node types in
- * subsequent versions. Thus, revealing edges to new types will cause problems. This methods
- * filters any such edges out.
- *
- * @param start - the start vertex
- * @param loader - loader for retrieving the list of allowed node types for the desired version
- * (version is set when the loader was instantiated)
- * @return list of cousin edges between start and any node types understood by the version specified in loader
- */
- public abstract List<Edge> findEdgesForVersion(Vertex start, Loader loader);
-
- /**
- * Finds all cousins of start.
- *
- * @param start - the start vertex
- * @return list of start's cousin vertices
- */
- public abstract List<Vertex> findCousinVertices(Vertex start, String... labels);
-
- public abstract double getDBTimeMsecs();
+ /**
+ * Finds the subgraph under start, including cousins as well as start's children/grandchildren/etc.
+ * More specifically, this includes start, all its descendants, start's cousins, and start's
+ * descendants' cousins (but not any of the cousins' cousins or descendants), and the edges
+ * connecting them.
+ *
+ * @param start - the start vertex
+ * @return - Tree containing nodes and edges of the subgraph
+ */
+ public Tree<Element> findSubGraph(Vertex start) {
+ return findSubGraph(start, AAIProperties.MAXIMUM_DEPTH, false);
+ }
+
+ /**
+ * Finds the subgraph under start, including cousins as well as start's children/grandchildren/etc.
+ * More specifically, this includes start, all its descendants, start's cousins, and start's
+ * descendants' cousins (but not any of the cousins' cousins or descendants), and the edges
+ * connecting them.
+ *
+ * @param start - the start vertex
+ * @param iterations - depth of the subgraph, this limits how many generations of
+ * descendants are included
+ * @param nodeOnly - if true the subgraph will NOT include the cousins
+ * @return Tree containing nodes and edges of the subgraph
+ */
+ public abstract Tree<Element> findSubGraph(Vertex start, int iterations, boolean nodeOnly);
+
+ /**
+ * Find vertices of type nodeType related to start by edges of the given
+ * direction and label.
+ *
+ * @param start - the start vertex
+ * @param direction - the direction of edges to traverse from start
+ * @param label - the label of edges to traverse from start
+ * @param nodeType - the node type the results should be
+ * @return the list of related vertices
+ */
+ public abstract List<Vertex> findRelatedVertices(Vertex start, Direction direction, String label, String nodeType);
+
+ /**
+ * Finds cousin edges connecting start to other vertices only of types defined in an old version.
+ * The idea is that if a user is using an old version, they won't understand any new node types in
+ * subsequent versions. Thus, revealing edges to new types will cause problems. This methods
+ * filters any such edges out.
+ *
+ * @param start - the start vertex
+ * @param loader - loader for retrieving the list of allowed node types for the desired version
+ * (version is set when the loader was instantiated)
+ * @return list of cousin edges between start and any node types understood by the version specified in loader
+ */
+ public abstract List<Edge> findEdgesForVersion(Vertex start, Loader loader);
+
+ /**
+ * Finds all cousins of start.
+ *
+ * @param start - the start vertex
+ * @return list of start's cousin vertices
+ */
+ public abstract List<Vertex> findCousinVertices(Vertex start, String... labels);
+
+ public abstract double getDBTimeMsecs();
}
diff --git a/aai-core/src/main/java/org/onap/aai/serialization/queryformats/Console.java b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/Console.java
index d42f33f1..ba20c652 100644
--- a/aai-core/src/main/java/org/onap/aai/serialization/queryformats/Console.java
+++ b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/Console.java
@@ -17,27 +17,29 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.serialization.queryformats;
import com.google.gson.JsonObject;
-import org.onap.aai.serialization.queryformats.exceptions.AAIFormatVertexException;
import java.util.Optional;
+import org.onap.aai.serialization.queryformats.exceptions.AAIFormatVertexException;
+
public class Console implements FormatMapper {
- @Override
- public Optional<JsonObject> formatObject(Object v) throws AAIFormatVertexException {
-
- JsonObject json = new JsonObject();
- json.addProperty("result", v.toString());
-
- return Optional.of(json);
- }
-
- @Override
- public int parallelThreshold() {
- return 100;
- }
+ @Override
+ public Optional<JsonObject> formatObject(Object v) throws AAIFormatVertexException {
+
+ JsonObject json = new JsonObject();
+ json.addProperty("result", v.toString());
+
+ return Optional.of(json);
+ }
+
+ @Override
+ public int parallelThreshold() {
+ return 100;
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/serialization/queryformats/Count.java b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/Count.java
index 053c8def..8ee4e3a4 100644
--- a/aai-core/src/main/java/org/onap/aai/serialization/queryformats/Count.java
+++ b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/Count.java
@@ -17,9 +17,15 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.serialization.queryformats;
import com.google.gson.JsonObject;
+
+import java.util.List;
+import java.util.Optional;
+import java.util.stream.Collectors;
+
import org.apache.tinkerpop.gremlin.process.traversal.Path;
import org.apache.tinkerpop.gremlin.process.traversal.step.util.Tree;
import org.apache.tinkerpop.gremlin.structure.Vertex;
@@ -28,53 +34,48 @@ import org.onap.aai.db.props.AAIProperties;
import org.onap.aai.serialization.queryformats.exceptions.AAIFormatQueryResultFormatNotSupported;
import org.onap.aai.serialization.queryformats.exceptions.AAIFormatVertexException;
-import java.util.List;
-import java.util.Optional;
-import java.util.stream.Collectors;
-
public class Count implements FormatMapper {
- @Override
- public Optional<JsonObject> formatObject(Object o) throws AAIFormatVertexException, AAIFormatQueryResultFormatNotSupported {
- @SuppressWarnings("unchecked")
- List<Object> list = (List<Object>) o;
-
- final JsonObject countResult = new JsonObject();
-
- list.stream().map(this::getCount)
- .filter( Optional::isPresent )
- .map(Optional::get)
- .collect( Collectors.toConcurrentMap( Pair::getValue0, Pair::getValue1, Long::sum ) )
- .forEach( (k,v) -> countResult.addProperty(k, v) );
-
- return Optional.of(countResult);
- }
-
- @Override
- public int parallelThreshold() {
- return 20;
- }
-
- private Optional<Pair<String, Long>> getCount(Object o){
-
- Pair<String, Long> pair = null;
-
- if (o instanceof Vertex) {
- Vertex v = (Vertex) o;
- pair = Pair.with(v.property(AAIProperties.NODE_TYPE).value().toString(), 1L);
- } else if (o instanceof Tree) {
- pair = Pair.with("trees", 1L);
- } else if (o instanceof Path) {
- pair = Pair.with("paths", 1L);
- } else if (o instanceof Long) {
- pair = Pair.with("count", (Long)o);
- }
-
- if (pair == null) {
- return Optional.<Pair<String, Long>>empty();
- }
-
- return Optional.<Pair<String, Long>>of(pair);
- }
+ @Override
+ public Optional<JsonObject> formatObject(Object o)
+ throws AAIFormatVertexException, AAIFormatQueryResultFormatNotSupported {
+ @SuppressWarnings("unchecked")
+ List<Object> list = (List<Object>) o;
+
+ final JsonObject countResult = new JsonObject();
+
+ list.stream().map(this::getCount).filter(Optional::isPresent).map(Optional::get)
+ .collect(Collectors.toConcurrentMap(Pair::getValue0, Pair::getValue1, Long::sum))
+ .forEach((k, v) -> countResult.addProperty(k, v));
+
+ return Optional.of(countResult);
+ }
+
+ @Override
+ public int parallelThreshold() {
+ return 20;
+ }
+
+ private Optional<Pair<String, Long>> getCount(Object o) {
+
+ Pair<String, Long> pair = null;
+
+ if (o instanceof Vertex) {
+ Vertex v = (Vertex) o;
+ pair = Pair.with(v.property(AAIProperties.NODE_TYPE).value().toString(), 1L);
+ } else if (o instanceof Tree) {
+ pair = Pair.with("trees", 1L);
+ } else if (o instanceof Path) {
+ pair = Pair.with("paths", 1L);
+ } else if (o instanceof Long) {
+ pair = Pair.with("count", (Long) o);
+ }
+
+ if (pair == null) {
+ return Optional.<Pair<String, Long>>empty();
+ }
+
+ return Optional.<Pair<String, Long>>of(pair);
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/serialization/queryformats/Format.java b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/Format.java
index 7e7356fe..8de38117 100644
--- a/aai-core/src/main/java/org/onap/aai/serialization/queryformats/Format.java
+++ b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/Format.java
@@ -17,28 +17,19 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.serialization.queryformats;
import org.onap.aai.exceptions.AAIException;
public enum Format {
- graphson,
- pathed,
- pathed_resourceversion,
- id,
- resource,
- simple,
- resource_and_url,
- console,
- raw,
- count,
- resource_with_sot;
+ graphson, pathed, pathed_resourceversion, id, resource, simple, resource_and_url, console, raw, count, resource_with_sot;
- public static Format getFormat(String format) throws AAIException {
- try {
- return Format.valueOf(format);
- } catch (IllegalArgumentException e) {
- throw new AAIException("AAI_6120", "Unsupported format query parameter " + format + " in request.");
- }
- }
+ public static Format getFormat(String format) throws AAIException {
+ try {
+ return Format.valueOf(format);
+ } catch (IllegalArgumentException e) {
+ throw new AAIException("AAI_6120", "Unsupported format query parameter " + format + " in request.");
+ }
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/serialization/queryformats/FormatFactory.java b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/FormatFactory.java
index f36941f8..854a20f4 100644
--- a/aai-core/src/main/java/org/onap/aai/serialization/queryformats/FormatFactory.java
+++ b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/FormatFactory.java
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.serialization.queryformats;
import javax.ws.rs.core.MultivaluedHashMap;
@@ -32,72 +33,78 @@ import org.onap.aai.setup.SchemaVersions;
public class FormatFactory {
- private final Loader loader;
- private final DBSerializer serializer;
- private final UrlBuilder urlBuilder;
- private final QueryParamInjector injector;
+ private final Loader loader;
+ private final DBSerializer serializer;
+ private final UrlBuilder urlBuilder;
+ private final QueryParamInjector injector;
+
+ public FormatFactory(Loader loader, DBSerializer serializer, SchemaVersions schemaVersions, String basePath)
+ throws AAIException {
+ this.loader = loader;
+ this.serializer = serializer;
+ this.urlBuilder = new UrlBuilder(loader.getVersion(), serializer, schemaVersions, basePath);
+ this.injector = QueryParamInjector.getInstance();
+ }
+
+ public Formatter get(Format format) throws AAIException {
+ return get(format, new MultivaluedHashMap<String, String>());
+ }
- public FormatFactory (Loader loader, DBSerializer serializer, SchemaVersions schemaVersions, String basePath) throws AAIException {
- this.loader = loader;
- this.serializer = serializer;
- this.urlBuilder = new UrlBuilder(loader.getVersion(), serializer, schemaVersions, basePath);
- this.injector = QueryParamInjector.getInstance();
- }
-
- public Formatter get(Format format) throws AAIException {
- return get(format, new MultivaluedHashMap<String, String>());
- }
-
- public Formatter get(Format format, MultivaluedMap<String, String> params) throws AAIException {
-
- Formatter formatter = null;
+ public Formatter get(Format format, MultivaluedMap<String, String> params) throws AAIException {
- switch (format) {
- case graphson :
- formatter = new Formatter(inject(new GraphSON(), params));
- break;
- case pathed :
- formatter = new Formatter(inject(new PathedURL(loader, urlBuilder), params));
- break;
- case pathed_resourceversion :
+ Formatter formatter = null;
+
+ switch (format) {
+ case graphson:
+ formatter = new Formatter(inject(new GraphSON(), params));
+ break;
+ case pathed:
+ formatter = new Formatter(inject(new PathedURL(loader, urlBuilder), params));
+ break;
+ case pathed_resourceversion:
formatter = new Formatter(inject(new PathedURL(loader, urlBuilder).includeUrl(), params));
break;
- case id :
- formatter = new Formatter(inject(new IdURL(loader, urlBuilder), params));
- break;
- case resource :
- formatter = new Formatter(inject(new Resource.Builder(loader, serializer, urlBuilder), params).build());
- break;
- case resource_and_url :
- formatter = new Formatter(inject(new Resource.Builder(loader, serializer, urlBuilder).includeUrl(), params).build());
- break;
- case raw :
- formatter = new Formatter(inject(new RawFormat.Builder(loader, serializer, urlBuilder), params).build());
- break;
- case simple :
- formatter = new Formatter(inject(new RawFormat.Builder(loader, serializer, urlBuilder).depth(0).modelDriven(), params).build());
- break;
- case console :
- formatter = new Formatter(inject(new Console(), params));
- break;
- case count :
- formatter = new Formatter(inject(new Count(), params));
- break;
- case resource_with_sot :
- formatter = new Formatter(inject(new ResourceWithSoT.Builder(loader, serializer, urlBuilder), params).build());
+ case id:
+ formatter = new Formatter(inject(new IdURL(loader, urlBuilder), params));
+ break;
+ case resource:
+ formatter = new Formatter(inject(new Resource.Builder(loader, serializer, urlBuilder), params).build());
+ break;
+ case resource_and_url:
+ formatter = new Formatter(
+ inject(new Resource.Builder(loader, serializer, urlBuilder).includeUrl(), params).build());
+ break;
+ case raw:
+ formatter =
+ new Formatter(inject(new RawFormat.Builder(loader, serializer, urlBuilder), params).build());
break;
- default :
- break;
+ case simple:
+ formatter = new Formatter(
+ inject(new RawFormat.Builder(loader, serializer, urlBuilder).depth(0).modelDriven(), params)
+ .build());
+ break;
+ case console:
+ formatter = new Formatter(inject(new Console(), params));
+ break;
+ case count:
+ formatter = new Formatter(inject(new Count(), params));
+ break;
+ case resource_with_sot:
+ formatter = new Formatter(
+ inject(new ResourceWithSoT.Builder(loader, serializer, urlBuilder), params).build());
+ break;
+ default:
+ break;
+
+ }
+
+ return formatter;
+ }
+
+ private <T> T inject(T obj, MultivaluedMap<String, String> params) throws QueryParamInjectionException {
+
+ injector.injectParams(obj, params);
+ return obj;
+ }
- }
-
- return formatter;
- }
-
- private <T> T inject (T obj, MultivaluedMap<String, String> params) throws QueryParamInjectionException {
-
- injector.injectParams(obj, params);
- return obj;
- }
-
}
diff --git a/aai-core/src/main/java/org/onap/aai/serialization/queryformats/FormatMapper.java b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/FormatMapper.java
index 287170d0..26af2e31 100644
--- a/aai-core/src/main/java/org/onap/aai/serialization/queryformats/FormatMapper.java
+++ b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/FormatMapper.java
@@ -17,17 +17,19 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.serialization.queryformats;
import com.google.gson.JsonObject;
-import org.onap.aai.serialization.queryformats.exceptions.AAIFormatQueryResultFormatNotSupported;
-import org.onap.aai.serialization.queryformats.exceptions.AAIFormatVertexException;
import java.util.Optional;
+import org.onap.aai.serialization.queryformats.exceptions.AAIFormatQueryResultFormatNotSupported;
+import org.onap.aai.serialization.queryformats.exceptions.AAIFormatVertexException;
+
public interface FormatMapper {
- Optional<JsonObject> formatObject(Object o) throws AAIFormatVertexException, AAIFormatQueryResultFormatNotSupported;
-
- int parallelThreshold();
+ Optional<JsonObject> formatObject(Object o) throws AAIFormatVertexException, AAIFormatQueryResultFormatNotSupported;
+
+ int parallelThreshold();
}
diff --git a/aai-core/src/main/java/org/onap/aai/serialization/queryformats/Formatter.java b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/Formatter.java
index 72847149..a19bd3f6 100644
--- a/aai-core/src/main/java/org/onap/aai/serialization/queryformats/Formatter.java
+++ b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/Formatter.java
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.serialization.queryformats;
import com.att.eelf.configuration.EELFLogger;
@@ -24,74 +25,72 @@ import com.att.eelf.configuration.EELFManager;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
-import org.onap.aai.logging.LogFormatTools;
-import org.onap.aai.serialization.queryformats.exceptions.AAIFormatQueryResultFormatNotSupported;
-import org.onap.aai.serialization.queryformats.exceptions.AAIFormatVertexException;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;
+import org.onap.aai.logging.LogFormatTools;
+import org.onap.aai.serialization.queryformats.exceptions.AAIFormatQueryResultFormatNotSupported;
+import org.onap.aai.serialization.queryformats.exceptions.AAIFormatVertexException;
+
public class Formatter {
- private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(Formatter.class);
-
- protected JsonParser parser = new JsonParser();
- protected final FormatMapper format;
-
- public Formatter(FormatMapper format) {
- this.format = format;
- }
-
- public JsonObject output(List<Object> queryResults) {
-
- Stream<Object> stream;
- JsonObject result = new JsonObject();
- JsonArray body = new JsonArray();
-
- if (this.format instanceof Count) {
- JsonObject countResult;
- try {
- countResult = format.formatObject(queryResults).orElseThrow(() -> new AAIFormatVertexException(""));
- body.add(countResult);
- } catch (Exception e) {
- LOGGER.warn("Failed to format result type of the query " + LogFormatTools.getStackTop(e));
- }
- } else {
- if (queryResults.size() >= format.parallelThreshold()) {
- stream = queryResults.parallelStream();
- } else {
- stream = queryResults.stream();
- }
-
- final boolean isParallel = stream.isParallel();
-
- stream.map(o -> {
- try {
- return format.formatObject(o);
- } catch (AAIFormatVertexException e) {
- LOGGER.warn("Failed to format vertex, returning a partial list " + LogFormatTools.getStackTop(e));
- } catch (AAIFormatQueryResultFormatNotSupported e) {
- LOGGER.warn("Failed to format result type of the query " + LogFormatTools.getStackTop(e));
- }
-
- return Optional.<JsonObject>empty();
- })
- .filter(Optional::isPresent)
- .map(Optional::get)
- .forEach(json -> {
- if (isParallel) {
- synchronized (body) {
- body.add(json);
- }
- } else {
- body.add(json);
- }
- });
-
- }
- result.add("results", body);
- return result.getAsJsonObject();
- }
+ private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(Formatter.class);
+
+ protected JsonParser parser = new JsonParser();
+ protected final FormatMapper format;
+
+ public Formatter(FormatMapper format) {
+ this.format = format;
+ }
+
+ public JsonObject output(List<Object> queryResults) {
+
+ Stream<Object> stream;
+ JsonObject result = new JsonObject();
+ JsonArray body = new JsonArray();
+
+ if (this.format instanceof Count) {
+ JsonObject countResult;
+ try {
+ countResult = format.formatObject(queryResults).orElseThrow(() -> new AAIFormatVertexException(""));
+ body.add(countResult);
+ } catch (Exception e) {
+ LOGGER.warn("Failed to format result type of the query " + LogFormatTools.getStackTop(e));
+ }
+ } else {
+ if (queryResults.size() >= format.parallelThreshold()) {
+ stream = queryResults.parallelStream();
+ } else {
+ stream = queryResults.stream();
+ }
+
+ final boolean isParallel = stream.isParallel();
+
+ stream.map(o -> {
+ try {
+ return format.formatObject(o);
+ } catch (AAIFormatVertexException e) {
+ LOGGER.warn("Failed to format vertex, returning a partial list " + LogFormatTools.getStackTop(e));
+ } catch (AAIFormatQueryResultFormatNotSupported e) {
+ LOGGER.warn("Failed to format result type of the query " + LogFormatTools.getStackTop(e));
+ }
+
+ return Optional.<JsonObject>empty();
+ }).filter(Optional::isPresent).map(Optional::get).forEach(json -> {
+ if (isParallel) {
+ synchronized (body) {
+ body.add(json);
+ }
+ } else {
+ body.add(json);
+ }
+ });
+
+ }
+ result.add("results", body);
+ return result.getAsJsonObject();
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/serialization/queryformats/GraphSON.java b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/GraphSON.java
index 7e0f3f6c..eeac2195 100644
--- a/aai-core/src/main/java/org/onap/aai/serialization/queryformats/GraphSON.java
+++ b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/GraphSON.java
@@ -17,17 +17,13 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.serialization.queryformats;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
-import org.apache.tinkerpop.gremlin.structure.Direction;
-import org.apache.tinkerpop.gremlin.structure.Vertex;
-import org.apache.tinkerpop.gremlin.structure.io.graphson.GraphSONMapper;
-import org.apache.tinkerpop.gremlin.structure.io.graphson.GraphSONWriter;
-import org.janusgraph.graphdb.tinkerpop.JanusGraphIoRegistry;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@@ -37,93 +33,100 @@ import java.util.Iterator;
import java.util.Map;
import java.util.Optional;
+import org.apache.tinkerpop.gremlin.structure.Direction;
+import org.apache.tinkerpop.gremlin.structure.Vertex;
+import org.apache.tinkerpop.gremlin.structure.io.graphson.GraphSONMapper;
+import org.apache.tinkerpop.gremlin.structure.io.graphson.GraphSONWriter;
+import org.janusgraph.graphdb.tinkerpop.JanusGraphIoRegistry;
+
public class GraphSON implements FormatMapper {
- private final GraphSONMapper mapper = GraphSONMapper.build().addRegistry(JanusGraphIoRegistry.getInstance()).create();
- private final GraphSONWriter writer = GraphSONWriter.build().mapper(mapper).create();
- protected JsonParser parser = new JsonParser();
-
- @Override
- public Optional<JsonObject> formatObject(Object v) {
- OutputStream os = new ByteArrayOutputStream();
- String result = "";
- try {
- writer.writeVertex(os, (Vertex)v, Direction.BOTH);
-
- result = os.toString();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
-
- JsonObject jsonObject = parser.parse(result).getAsJsonObject();
-
- if(jsonObject != null){
-
- if(jsonObject.has("outE")){
- JsonObject outEdges = jsonObject.get("outE").getAsJsonObject();
- removePrivateEdges(jsonObject, outEdges, "outE");
- }
-
- if(jsonObject.has("inE")){
- JsonObject inEdges = jsonObject.get("inE").getAsJsonObject();
- removePrivateEdges(jsonObject, inEdges, "inE");
- }
-
- }
-
- return Optional.of(jsonObject);
-
- }
-
- /**
- * Removes the private edges from the json object
- *
- * Please note that the reason to choose to remove the private
- * edges from the json object instead of removing it from the vertex
- * itself is the fact that even though the transaction will be rolled back
- * is because of the possible incosistent behavior where the actual edge
- * might actually be removed in a long running transaction and is not worth the risk
- *
- * @param jsonObject - JSON Object from which we are removing the private edges for
- * @param edges - JSONObject HashMap representing all of the edges
- * @param edgeDirection - a string indicating the direction of the edge
- */
- private void removePrivateEdges(JsonObject jsonObject, JsonObject edges, String edgeDirection) {
-
- Iterator it = edges.entrySet().iterator();
- while(it.hasNext()){
- Map.Entry<String, JsonElement> outEntry = (Map.Entry<String, JsonElement>) it.next();
- JsonArray edgePropertiesArray = outEntry.getValue().getAsJsonArray();
- for(int index = 0; index < edgePropertiesArray.size(); ++index){
- JsonElement jsonElement = edgePropertiesArray.get(index);
- JsonObject obj = jsonElement.getAsJsonObject();
- if (obj.has("properties")) {
- JsonObject objProperties = obj.get("properties").getAsJsonObject();
- if (objProperties.has("private")) {
- boolean isPrivate = objProperties.get("private").getAsBoolean();
- if (isPrivate) {
- if (edges.size() == 1) {
- if (edgePropertiesArray.size() == 1) {
- jsonObject.remove(edgeDirection);
- } else {
- edgePropertiesArray.remove(jsonElement);
- }
- } else {
- edgePropertiesArray.remove(jsonElement);
- }
- }
- }
- }
- }
- if(edgePropertiesArray.size() == 0){
- it.remove();
- }
- }
- }
-
- @Override
- public int parallelThreshold() {
- return 50;
- }
+ private final GraphSONMapper mapper =
+ GraphSONMapper.build().addRegistry(JanusGraphIoRegistry.getInstance()).create();
+ private final GraphSONWriter writer = GraphSONWriter.build().mapper(mapper).create();
+ protected JsonParser parser = new JsonParser();
+
+ @Override
+ public Optional<JsonObject> formatObject(Object v) {
+ OutputStream os = new ByteArrayOutputStream();
+ String result = "";
+ try {
+ writer.writeVertex(os, (Vertex) v, Direction.BOTH);
+
+ result = os.toString();
+ } catch (IOException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+
+ JsonObject jsonObject = parser.parse(result).getAsJsonObject();
+
+ if (jsonObject != null) {
+
+ if (jsonObject.has("outE")) {
+ JsonObject outEdges = jsonObject.get("outE").getAsJsonObject();
+ removePrivateEdges(jsonObject, outEdges, "outE");
+ }
+
+ if (jsonObject.has("inE")) {
+ JsonObject inEdges = jsonObject.get("inE").getAsJsonObject();
+ removePrivateEdges(jsonObject, inEdges, "inE");
+ }
+
+ }
+
+ return Optional.of(jsonObject);
+
+ }
+
+ /**
+ * Removes the private edges from the json object
+ *
+ * Please note that the reason to choose to remove the private
+ * edges from the json object instead of removing it from the vertex
+ * itself is the fact that even though the transaction will be rolled back
+ * is because of the possible incosistent behavior where the actual edge
+ * might actually be removed in a long running transaction and is not worth the risk
+ *
+ * @param jsonObject - JSON Object from which we are removing the private edges for
+ * @param edges - JSONObject HashMap representing all of the edges
+ * @param edgeDirection - a string indicating the direction of the edge
+ */
+ private void removePrivateEdges(JsonObject jsonObject, JsonObject edges, String edgeDirection) {
+
+ Iterator it = edges.entrySet().iterator();
+ while (it.hasNext()) {
+ Map.Entry<String, JsonElement> outEntry = (Map.Entry<String, JsonElement>) it.next();
+ JsonArray edgePropertiesArray = outEntry.getValue().getAsJsonArray();
+ for (int index = 0; index < edgePropertiesArray.size(); ++index) {
+ JsonElement jsonElement = edgePropertiesArray.get(index);
+ JsonObject obj = jsonElement.getAsJsonObject();
+ if (obj.has("properties")) {
+ JsonObject objProperties = obj.get("properties").getAsJsonObject();
+ if (objProperties.has("private")) {
+ boolean isPrivate = objProperties.get("private").getAsBoolean();
+ if (isPrivate) {
+ if (edges.size() == 1) {
+ if (edgePropertiesArray.size() == 1) {
+ jsonObject.remove(edgeDirection);
+ } else {
+ edgePropertiesArray.remove(jsonElement);
+ }
+ } else {
+ edgePropertiesArray.remove(jsonElement);
+ }
+ }
+ }
+ }
+ }
+ if (edgePropertiesArray.size() == 0) {
+ it.remove();
+ }
+ }
+ }
+
+ @Override
+ public int parallelThreshold() {
+ return 50;
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/serialization/queryformats/IdURL.java b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/IdURL.java
index 6d344780..c5cb9254 100644
--- a/aai-core/src/main/java/org/onap/aai/serialization/queryformats/IdURL.java
+++ b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/IdURL.java
@@ -17,10 +17,14 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.serialization.queryformats;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
+
+import java.util.Optional;
+
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.onap.aai.db.props.AAIProperties;
import org.onap.aai.exceptions.AAIException;
@@ -30,42 +34,39 @@ import org.onap.aai.introspection.exceptions.AAIUnknownObjectException;
import org.onap.aai.serialization.queryformats.exceptions.AAIFormatVertexException;
import org.onap.aai.serialization.queryformats.utils.UrlBuilder;
-import java.util.Optional;
-
public class IdURL extends MultiFormatMapper {
- private final UrlBuilder urlBuilder;
- private final JsonParser parser;
- private final Loader loader;
+ private final UrlBuilder urlBuilder;
+ private final JsonParser parser;
+ private final Loader loader;
+
+ public IdURL(Loader loader, UrlBuilder urlBuilder) throws AAIException {
+ this.urlBuilder = urlBuilder;
+ this.parser = new JsonParser();
+ this.loader = loader;
+ }
+
+ @Override
+ public int parallelThreshold() {
+ return 2500;
+ }
+
+ @Override
+ protected Optional<JsonObject> getJsonFromVertex(Vertex v) throws AAIFormatVertexException {
- public IdURL (Loader loader, UrlBuilder urlBuilder) throws AAIException {
- this.urlBuilder = urlBuilder;
- this.parser = new JsonParser();
- this.loader = loader;
- }
-
- @Override
- public int parallelThreshold() {
- return 2500;
- }
+ try {
+ final Introspector searchResult = this.loader.introspectorFromName("result-data");
- @Override
- protected Optional<JsonObject> getJsonFromVertex(Vertex v) throws AAIFormatVertexException {
+ searchResult.setValue("resource-type", v.value(AAIProperties.NODE_TYPE));
+ searchResult.setValue("resource-link", this.urlBuilder.id(v));
- try {
- final Introspector searchResult = this.loader.introspectorFromName("result-data");
+ final String json = searchResult.marshal(false);
- searchResult.setValue("resource-type", v.value(AAIProperties.NODE_TYPE));
- searchResult.setValue("resource-link", this.urlBuilder.id(v));
+ return Optional.of(parser.parse(json).getAsJsonObject());
- final String json = searchResult.marshal(false);
+ } catch (AAIUnknownObjectException e) {
+ throw new RuntimeException("Fatal error - result-data object does not exist!");
+ }
- return Optional.of(parser.parse(json).getAsJsonObject());
-
- } catch (AAIUnknownObjectException e) {
- throw new RuntimeException("Fatal error - result-data object does not exist!");
- }
-
-
- }
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/serialization/queryformats/MultiFormatMapper.java b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/MultiFormatMapper.java
index 944c14c4..21b666f2 100644
--- a/aai-core/src/main/java/org/onap/aai/serialization/queryformats/MultiFormatMapper.java
+++ b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/MultiFormatMapper.java
@@ -17,92 +17,94 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.serialization.queryformats;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
+
+import java.util.Iterator;
+import java.util.List;
+import java.util.Optional;
+
import org.apache.tinkerpop.gremlin.process.traversal.Path;
import org.apache.tinkerpop.gremlin.process.traversal.step.util.Tree;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.onap.aai.serialization.queryformats.exceptions.AAIFormatQueryResultFormatNotSupported;
import org.onap.aai.serialization.queryformats.exceptions.AAIFormatVertexException;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Optional;
-
public abstract class MultiFormatMapper implements FormatMapper {
- @Override
- public Optional<JsonObject> formatObject(Object input) throws AAIFormatVertexException, AAIFormatQueryResultFormatNotSupported {
- if (input instanceof Vertex) {
- return this.getJsonFromVertex((Vertex) input);
- } else if (input instanceof Tree) {
- return this.getJsonFomTree((Tree<?>) input);
- } else if (input instanceof Path) {
- return this.getJsonFromPath((Path) input);
- } else {
- throw new AAIFormatQueryResultFormatNotSupported();
- }
- }
-
- protected abstract Optional<JsonObject> getJsonFromVertex(Vertex input) throws AAIFormatVertexException;
-
- protected Optional<JsonObject> getJsonFromPath(Path input) throws AAIFormatVertexException {
- List<Object> path = input.objects();
-
- JsonObject jo = new JsonObject();
- JsonArray ja = new JsonArray();
-
- for (Object o : path) {
- if (o instanceof Vertex) {
- ja.add(this.getJsonFromVertex((Vertex)o).get());
- }
- }
-
- jo.add("path", ja);
- return Optional.of(jo);
- }
-
- protected Optional<JsonObject> getJsonFomTree(Tree<?> tree) throws AAIFormatVertexException {
-
- if (tree.isEmpty()) {
- return Optional.of(new JsonObject());
- }
-
- JsonObject t = new JsonObject();
- JsonArray ja = this.getNodesArray(tree);
- if (ja.size() > 0) {
- t.add("nodes", ja);
- }
-
- return Optional.of(t);
- }
-
- private JsonArray getNodesArray (Tree<?> tree) throws AAIFormatVertexException {
-
- JsonArray nodes = new JsonArray();
- Iterator<?> it = tree.keySet().iterator();
-
- while (it.hasNext()) {
- Object o = it.next();
- JsonObject me = new JsonObject();
- if (o instanceof Vertex) {
- me = this.getJsonFromVertex((Vertex) o).get();
- }
- JsonArray ja = this.getNodesArray((Tree<?>) tree.get(o));
- if (ja.size() > 0) {
- me.add("nodes", ja);
- }
- nodes.add(me);
- }
- return nodes;
- }
-
-
- @Override
- public int parallelThreshold() {
- return 100;
- }
+ @Override
+ public Optional<JsonObject> formatObject(Object input)
+ throws AAIFormatVertexException, AAIFormatQueryResultFormatNotSupported {
+ if (input instanceof Vertex) {
+ return this.getJsonFromVertex((Vertex) input);
+ } else if (input instanceof Tree) {
+ return this.getJsonFomTree((Tree<?>) input);
+ } else if (input instanceof Path) {
+ return this.getJsonFromPath((Path) input);
+ } else {
+ throw new AAIFormatQueryResultFormatNotSupported();
+ }
+ }
+
+ protected abstract Optional<JsonObject> getJsonFromVertex(Vertex input) throws AAIFormatVertexException;
+
+ protected Optional<JsonObject> getJsonFromPath(Path input) throws AAIFormatVertexException {
+ List<Object> path = input.objects();
+
+ JsonObject jo = new JsonObject();
+ JsonArray ja = new JsonArray();
+
+ for (Object o : path) {
+ if (o instanceof Vertex) {
+ ja.add(this.getJsonFromVertex((Vertex) o).get());
+ }
+ }
+
+ jo.add("path", ja);
+ return Optional.of(jo);
+ }
+
+ protected Optional<JsonObject> getJsonFomTree(Tree<?> tree) throws AAIFormatVertexException {
+
+ if (tree.isEmpty()) {
+ return Optional.of(new JsonObject());
+ }
+
+ JsonObject t = new JsonObject();
+ JsonArray ja = this.getNodesArray(tree);
+ if (ja.size() > 0) {
+ t.add("nodes", ja);
+ }
+
+ return Optional.of(t);
+ }
+
+ private JsonArray getNodesArray(Tree<?> tree) throws AAIFormatVertexException {
+
+ JsonArray nodes = new JsonArray();
+ Iterator<?> it = tree.keySet().iterator();
+
+ while (it.hasNext()) {
+ Object o = it.next();
+ JsonObject me = new JsonObject();
+ if (o instanceof Vertex) {
+ me = this.getJsonFromVertex((Vertex) o).get();
+ }
+ JsonArray ja = this.getNodesArray((Tree<?>) tree.get(o));
+ if (ja.size() > 0) {
+ me.add("nodes", ja);
+ }
+ nodes.add(me);
+ }
+ return nodes;
+ }
+
+ @Override
+ public int parallelThreshold() {
+ return 100;
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/serialization/queryformats/PathedURL.java b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/PathedURL.java
index d2180e38..a99ba7f4 100644
--- a/aai-core/src/main/java/org/onap/aai/serialization/queryformats/PathedURL.java
+++ b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/PathedURL.java
@@ -17,10 +17,14 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.serialization.queryformats;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
+
+import java.util.Optional;
+
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.onap.aai.db.props.AAIProperties;
import org.onap.aai.exceptions.AAIException;
@@ -30,53 +34,49 @@ import org.onap.aai.introspection.exceptions.AAIUnknownObjectException;
import org.onap.aai.serialization.queryformats.exceptions.AAIFormatVertexException;
import org.onap.aai.serialization.queryformats.utils.UrlBuilder;
-import java.util.Optional;
-
public final class PathedURL extends MultiFormatMapper {
- private final UrlBuilder urlBuilder;
- private final JsonParser parser;
- private final Loader loader;
+ private final UrlBuilder urlBuilder;
+ private final JsonParser parser;
+ private final Loader loader;
private boolean includeUrl = false;
-
- public PathedURL (Loader loader, UrlBuilder urlBuilder) throws AAIException {
- this.urlBuilder = urlBuilder;
- this.parser = new JsonParser();
- this.loader = loader;
- }
+ public PathedURL(Loader loader, UrlBuilder urlBuilder) throws AAIException {
+ this.urlBuilder = urlBuilder;
+ this.parser = new JsonParser();
+ this.loader = loader;
+ }
- @Override
- public int parallelThreshold() {
- return 20;
- }
+ @Override
+ public int parallelThreshold() {
+ return 20;
+ }
public PathedURL includeUrl() {
this.includeUrl = true;
return this;
}
-
- @Override
- protected Optional<JsonObject> getJsonFromVertex(Vertex v) throws AAIFormatVertexException {
+ @Override
+ protected Optional<JsonObject> getJsonFromVertex(Vertex v) throws AAIFormatVertexException {
- try {
- final Introspector searchResult = this.loader.introspectorFromName("result-data");
+ try {
+ final Introspector searchResult = this.loader.introspectorFromName("result-data");
- searchResult.setValue("resource-type", v.value(AAIProperties.NODE_TYPE));
+ searchResult.setValue("resource-type", v.value(AAIProperties.NODE_TYPE));
- searchResult.setValue("resource-link", this.urlBuilder.pathed(v));
+ searchResult.setValue("resource-link", this.urlBuilder.pathed(v));
- if(includeUrl)
+ if (includeUrl)
searchResult.setValue("resource-version", v.value(AAIProperties.RESOURCE_VERSION));
-
- final String json = searchResult.marshal(false);
- return Optional.of(this.parser.parse(json).getAsJsonObject());
- } catch (AAIUnknownObjectException e) {
- throw new RuntimeException("Fatal error - result-data does not exist!", e);
- }
+ final String json = searchResult.marshal(false);
+ return Optional.of(this.parser.parse(json).getAsJsonObject());
- }
+ } catch (AAIUnknownObjectException e) {
+ throw new RuntimeException("Fatal error - result-data does not exist!", e);
+ }
+
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/serialization/queryformats/RawFormat.java b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/RawFormat.java
index e90ee6b1..8636ebfa 100644
--- a/aai-core/src/main/java/org/onap/aai/serialization/queryformats/RawFormat.java
+++ b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/RawFormat.java
@@ -17,12 +17,18 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.serialization.queryformats;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
+
+import java.util.Iterator;
+import java.util.List;
+import java.util.Optional;
+
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Vertex;
@@ -35,178 +41,176 @@ import org.onap.aai.serialization.queryformats.params.Depth;
import org.onap.aai.serialization.queryformats.params.NodesOnly;
import org.onap.aai.serialization.queryformats.utils.UrlBuilder;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Optional;
+public class RawFormat extends MultiFormatMapper {
+ protected JsonParser parser = new JsonParser();
+ protected final DBSerializer serializer;
+ protected final Loader loader;
+ protected final UrlBuilder urlBuilder;
+ protected final int depth;
+ protected final boolean nodesOnly;
+ protected RawFormat(Builder builder) {
+ this.urlBuilder = builder.getUrlBuilder();
+ this.loader = builder.getLoader();
+ this.serializer = builder.getSerializer();
+ this.depth = builder.getDepth();
+ this.nodesOnly = builder.isNodesOnly();
+ }
-public class RawFormat extends MultiFormatMapper {
- protected JsonParser parser = new JsonParser();
- protected final DBSerializer serializer;
- protected final Loader loader;
- protected final UrlBuilder urlBuilder;
- protected final int depth;
- protected final boolean nodesOnly;
- protected RawFormat(Builder builder) {
- this.urlBuilder = builder.getUrlBuilder();
- this.loader = builder.getLoader();
- this.serializer = builder.getSerializer();
- this.depth = builder.getDepth();
- this.nodesOnly = builder.isNodesOnly();
- }
-
- @Override
- public int parallelThreshold() {
- return 100;
- }
-
-
- public Optional<JsonObject> createPropertiesObject(Vertex v) throws AAIFormatVertexException {
- JsonObject json = new JsonObject();
- Iterator<VertexProperty<Object>> iter = v.properties();
-
- while (iter.hasNext()) {
- VertexProperty<Object> prop = iter.next();
- if (prop.value() instanceof String) {
- json.addProperty(prop.key(), (String)prop.value());
- } else if (prop.value() instanceof Boolean) {
- json.addProperty(prop.key(), (Boolean)prop.value());
- } else if (prop.value() instanceof Number) {
- json.addProperty(prop.key(), (Number)prop.value());
- } else if (prop.value() instanceof List) {
- Gson gson = new Gson();
- String list = gson.toJson(prop.value());
-
- json.addProperty(prop.key(), list);
- } else {
- //throw exception?
- return null;
- }
- }
-
- return Optional.of(json);
- }
-
- protected JsonArray createRelationshipObject(Vertex v) throws AAIFormatVertexException {
- JsonArray jarray = new JsonArray();
- Iterator<Edge> inIter = v.edges(Direction.IN);
- Iterator<Edge> outIter = v.edges(Direction.OUT);
-
- while (inIter.hasNext()) {
- Edge e = inIter.next();
- Vertex outVertex = e.outVertex();
- this.addEdge(e, outVertex, jarray);
- }
-
- while (outIter.hasNext()) {
- Edge e = outIter.next();
- Vertex inVertex = e.inVertex();
- this.addEdge(e, inVertex, jarray);
- }
-
- return jarray;
- }
-
- protected void addEdge(Edge e, Vertex vertex, JsonArray array) throws AAIFormatVertexException {
- array.add(this.getRelatedObject(e.label(), vertex));
- }
-
- protected JsonObject getRelatedObject(String label, Vertex related) throws AAIFormatVertexException {
- JsonObject json = new JsonObject();
- json.addProperty("id", related.id().toString());
- json.addProperty("relationship-label", label);
- json.addProperty("node-type", related.<String>value(AAIProperties.NODE_TYPE));
- json.addProperty("url", this.urlBuilder.pathed(related));
-
- return json;
- }
-
- public static class Builder implements NodesOnly<Builder>, Depth<Builder> {
-
- protected final Loader loader;
- protected final DBSerializer serializer;
- protected final UrlBuilder urlBuilder;
- protected boolean includeUrl = false;
- protected boolean nodesOnly = false;
- protected int depth = 1;
- protected boolean modelDriven = false;
- public Builder(Loader loader, DBSerializer serializer, UrlBuilder urlBuilder) {
- this.loader = loader;
- this.serializer = serializer;
- this.urlBuilder = urlBuilder;
- }
-
- protected Loader getLoader() {
- return this.loader;
- }
-
- protected DBSerializer getSerializer() {
- return this.serializer;
- }
-
- protected UrlBuilder getUrlBuilder() {
- return this.urlBuilder;
- }
-
- public Builder includeUrl() {
- this.includeUrl = true;
- return this;
- }
-
- public Builder nodesOnly(Boolean nodesOnly) {
- this.nodesOnly = nodesOnly;
- return this;
- }
- public boolean isNodesOnly() {
- return this.nodesOnly;
- }
-
- public Builder depth(Integer depth) {
- this.depth = depth;
- return this;
- }
-
- public int getDepth() {
- return this.depth;
- }
-
- public boolean isIncludeUrl() {
- return this.includeUrl;
- }
-
- public Builder modelDriven() {
- this.modelDriven = true;
- return this;
- }
-
- public boolean getModelDriven() {
- return this.modelDriven;
- }
- public RawFormat build() {
- if (modelDriven) {
- return new SimpleFormat(this);
- } else {
- return new RawFormat(this);
- }
- }
- }
-
- @Override
- protected Optional<JsonObject> getJsonFromVertex(Vertex v) throws AAIFormatVertexException {
-
- JsonObject json = new JsonObject();
- json.addProperty("id", v.id().toString());
- json.addProperty("node-type", v.<String>value(AAIProperties.NODE_TYPE));
- json.addProperty("url", this.urlBuilder.pathed(v));
- Optional<JsonObject> properties = this.createPropertiesObject(v);
- if (properties.isPresent()) {
- json.add("properties", properties.get());
- } else {
- return Optional.empty();
- }
- if (!nodesOnly) {
- json.add("related-to", this.createRelationshipObject(v));
- }
- return Optional.of(json);
- }
+ @Override
+ public int parallelThreshold() {
+ return 100;
+ }
+
+ public Optional<JsonObject> createPropertiesObject(Vertex v) throws AAIFormatVertexException {
+ JsonObject json = new JsonObject();
+ Iterator<VertexProperty<Object>> iter = v.properties();
+
+ while (iter.hasNext()) {
+ VertexProperty<Object> prop = iter.next();
+ if (prop.value() instanceof String) {
+ json.addProperty(prop.key(), (String) prop.value());
+ } else if (prop.value() instanceof Boolean) {
+ json.addProperty(prop.key(), (Boolean) prop.value());
+ } else if (prop.value() instanceof Number) {
+ json.addProperty(prop.key(), (Number) prop.value());
+ } else if (prop.value() instanceof List) {
+ Gson gson = new Gson();
+ String list = gson.toJson(prop.value());
+
+ json.addProperty(prop.key(), list);
+ } else {
+ // throw exception?
+ return null;
+ }
+ }
+
+ return Optional.of(json);
+ }
+
+ protected JsonArray createRelationshipObject(Vertex v) throws AAIFormatVertexException {
+ JsonArray jarray = new JsonArray();
+ Iterator<Edge> inIter = v.edges(Direction.IN);
+ Iterator<Edge> outIter = v.edges(Direction.OUT);
+
+ while (inIter.hasNext()) {
+ Edge e = inIter.next();
+ Vertex outVertex = e.outVertex();
+ this.addEdge(e, outVertex, jarray);
+ }
+
+ while (outIter.hasNext()) {
+ Edge e = outIter.next();
+ Vertex inVertex = e.inVertex();
+ this.addEdge(e, inVertex, jarray);
+ }
+
+ return jarray;
+ }
+
+ protected void addEdge(Edge e, Vertex vertex, JsonArray array) throws AAIFormatVertexException {
+ array.add(this.getRelatedObject(e.label(), vertex));
+ }
+
+ protected JsonObject getRelatedObject(String label, Vertex related) throws AAIFormatVertexException {
+ JsonObject json = new JsonObject();
+ json.addProperty("id", related.id().toString());
+ json.addProperty("relationship-label", label);
+ json.addProperty("node-type", related.<String>value(AAIProperties.NODE_TYPE));
+ json.addProperty("url", this.urlBuilder.pathed(related));
+
+ return json;
+ }
+
+ public static class Builder implements NodesOnly<Builder>, Depth<Builder> {
+
+ protected final Loader loader;
+ protected final DBSerializer serializer;
+ protected final UrlBuilder urlBuilder;
+ protected boolean includeUrl = false;
+ protected boolean nodesOnly = false;
+ protected int depth = 1;
+ protected boolean modelDriven = false;
+
+ public Builder(Loader loader, DBSerializer serializer, UrlBuilder urlBuilder) {
+ this.loader = loader;
+ this.serializer = serializer;
+ this.urlBuilder = urlBuilder;
+ }
+
+ protected Loader getLoader() {
+ return this.loader;
+ }
+
+ protected DBSerializer getSerializer() {
+ return this.serializer;
+ }
+
+ protected UrlBuilder getUrlBuilder() {
+ return this.urlBuilder;
+ }
+
+ public Builder includeUrl() {
+ this.includeUrl = true;
+ return this;
+ }
+
+ public Builder nodesOnly(Boolean nodesOnly) {
+ this.nodesOnly = nodesOnly;
+ return this;
+ }
+
+ public boolean isNodesOnly() {
+ return this.nodesOnly;
+ }
+
+ public Builder depth(Integer depth) {
+ this.depth = depth;
+ return this;
+ }
+
+ public int getDepth() {
+ return this.depth;
+ }
+
+ public boolean isIncludeUrl() {
+ return this.includeUrl;
+ }
+
+ public Builder modelDriven() {
+ this.modelDriven = true;
+ return this;
+ }
+
+ public boolean getModelDriven() {
+ return this.modelDriven;
+ }
+
+ public RawFormat build() {
+ if (modelDriven) {
+ return new SimpleFormat(this);
+ } else {
+ return new RawFormat(this);
+ }
+ }
+ }
+
+ @Override
+ protected Optional<JsonObject> getJsonFromVertex(Vertex v) throws AAIFormatVertexException {
+
+ JsonObject json = new JsonObject();
+ json.addProperty("id", v.id().toString());
+ json.addProperty("node-type", v.<String>value(AAIProperties.NODE_TYPE));
+ json.addProperty("url", this.urlBuilder.pathed(v));
+ Optional<JsonObject> properties = this.createPropertiesObject(v);
+ if (properties.isPresent()) {
+ json.add("properties", properties.get());
+ } else {
+ return Optional.empty();
+ }
+ if (!nodesOnly) {
+ json.add("related-to", this.createRelationshipObject(v));
+ }
+ return Optional.of(json);
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/serialization/queryformats/Resource.java b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/Resource.java
index 3a4fdf89..b92f5858 100644
--- a/aai-core/src/main/java/org/onap/aai/serialization/queryformats/Resource.java
+++ b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/Resource.java
@@ -17,10 +17,17 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.serialization.queryformats;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
+
+import java.io.UnsupportedEncodingException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Optional;
+
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.onap.aai.db.props.AAIProperties;
import org.onap.aai.exceptions.AAIException;
@@ -33,132 +40,140 @@ import org.onap.aai.serialization.queryformats.params.Depth;
import org.onap.aai.serialization.queryformats.params.NodesOnly;
import org.onap.aai.serialization.queryformats.utils.UrlBuilder;
-import java.io.UnsupportedEncodingException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Optional;
-
public class Resource extends MultiFormatMapper {
- private final Loader loader;
- private final DBSerializer serializer;
- private final JsonParser parser;
- private final UrlBuilder urlBuilder;
- private final boolean includeUrl;
- private final boolean nodesOnly;
- private final int depth;
- private Resource (Builder builder) {
- this.parser = new JsonParser();
- this.loader = builder.getLoader();
- this.serializer = builder.getSerializer();
- this.urlBuilder = builder.getUrlBuilder();
- this.includeUrl = builder.isIncludeUrl();
- this.nodesOnly = builder.isNodesOnly();
- this.depth = builder.getDepth();
- }
-
- @Override
- protected Optional<JsonObject> getJsonFromVertex(Vertex v) throws AAIFormatVertexException {
-
- JsonObject json = new JsonObject();
-
- if (this.includeUrl) {
- json.addProperty("url", this.urlBuilder.pathed(v));
- }
- Optional<JsonObject> jsonObject = this.vertexToJsonObject(v);
- if (jsonObject.isPresent()) {
- json.add(v.<String>property(AAIProperties.NODE_TYPE).orElse(null), jsonObject.get());
- } else {
- return Optional.empty();
- }
- return Optional.of(json);
- }
-
- protected Optional<JsonObject> vertexToJsonObject(Vertex v) throws AAIFormatVertexException {
- try {
- final Introspector obj = getLoader().introspectorFromName(
- v.<String>property(AAIProperties.NODE_TYPE)
- .orElse(null)
- );
-
- final List<Vertex> wrapper = new ArrayList<>();
-
- wrapper.add(v);
-
- try {
- getSerializer().dbToObject(wrapper, obj, this.depth, this.nodesOnly, "false");
- } catch (AAIException | UnsupportedEncodingException e) {
- throw new AAIFormatVertexException("Failed to format vertex - error while serializing: " + e.getMessage(), e);
- }
-
- final String json = obj.marshal(false);
-
- return Optional.of(getParser().parse(json).getAsJsonObject());
- } catch (AAIUnknownObjectException e) {
- return Optional.empty();
- }
- }
-
- @Override
- public int parallelThreshold() {
- return 20;
- }
-
- private Loader getLoader() { return loader; }
- private DBSerializer getSerializer() { return serializer; }
- private JsonParser getParser() { return parser; }
-
- public static class Builder implements NodesOnly<Builder>, Depth<Builder> {
-
- private final Loader loader;
- private final DBSerializer serializer;
- private final UrlBuilder urlBuilder;
- private boolean includeUrl = false;
- private boolean nodesOnly = false;
- private int depth = 1;
- public Builder(Loader loader, DBSerializer serializer, UrlBuilder urlBuilder) {
- this.loader = loader;
- this.serializer = serializer;
- this.urlBuilder = urlBuilder;
- }
-
- protected Loader getLoader() {
- return this.loader;
- }
-
- protected DBSerializer getSerializer() {
- return this.serializer;
- }
-
- protected UrlBuilder getUrlBuilder() {
- return this.urlBuilder;
- }
-
- public Builder includeUrl() {
- this.includeUrl = true;
- return this;
- }
-
- public Builder nodesOnly(Boolean nodesOnly) {
- this.nodesOnly = nodesOnly;
- return this;
- }
- public boolean isNodesOnly() {
- return this.nodesOnly;
- }
- public Builder depth(Integer depth) {
- this.depth = depth;
- return this;
- }
- public int getDepth() {
- return this.depth;
- }
- public boolean isIncludeUrl() {
- return this.includeUrl;
- }
-
- public Resource build() {
- return new Resource(this);
- }
- }
+ private final Loader loader;
+ private final DBSerializer serializer;
+ private final JsonParser parser;
+ private final UrlBuilder urlBuilder;
+ private final boolean includeUrl;
+ private final boolean nodesOnly;
+ private final int depth;
+
+ private Resource(Builder builder) {
+ this.parser = new JsonParser();
+ this.loader = builder.getLoader();
+ this.serializer = builder.getSerializer();
+ this.urlBuilder = builder.getUrlBuilder();
+ this.includeUrl = builder.isIncludeUrl();
+ this.nodesOnly = builder.isNodesOnly();
+ this.depth = builder.getDepth();
+ }
+
+ @Override
+ protected Optional<JsonObject> getJsonFromVertex(Vertex v) throws AAIFormatVertexException {
+
+ JsonObject json = new JsonObject();
+
+ if (this.includeUrl) {
+ json.addProperty("url", this.urlBuilder.pathed(v));
+ }
+ Optional<JsonObject> jsonObject = this.vertexToJsonObject(v);
+ if (jsonObject.isPresent()) {
+ json.add(v.<String>property(AAIProperties.NODE_TYPE).orElse(null), jsonObject.get());
+ } else {
+ return Optional.empty();
+ }
+ return Optional.of(json);
+ }
+
+ protected Optional<JsonObject> vertexToJsonObject(Vertex v) throws AAIFormatVertexException {
+ try {
+ final Introspector obj =
+ getLoader().introspectorFromName(v.<String>property(AAIProperties.NODE_TYPE).orElse(null));
+
+ final List<Vertex> wrapper = new ArrayList<>();
+
+ wrapper.add(v);
+
+ try {
+ getSerializer().dbToObject(wrapper, obj, this.depth, this.nodesOnly, "false");
+ } catch (AAIException | UnsupportedEncodingException e) {
+ throw new AAIFormatVertexException(
+ "Failed to format vertex - error while serializing: " + e.getMessage(), e);
+ }
+
+ final String json = obj.marshal(false);
+
+ return Optional.of(getParser().parse(json).getAsJsonObject());
+ } catch (AAIUnknownObjectException e) {
+ return Optional.empty();
+ }
+ }
+
+ @Override
+ public int parallelThreshold() {
+ return 20;
+ }
+
+ private Loader getLoader() {
+ return loader;
+ }
+
+ private DBSerializer getSerializer() {
+ return serializer;
+ }
+
+ private JsonParser getParser() {
+ return parser;
+ }
+
+ public static class Builder implements NodesOnly<Builder>, Depth<Builder> {
+
+ private final Loader loader;
+ private final DBSerializer serializer;
+ private final UrlBuilder urlBuilder;
+ private boolean includeUrl = false;
+ private boolean nodesOnly = false;
+ private int depth = 1;
+
+ public Builder(Loader loader, DBSerializer serializer, UrlBuilder urlBuilder) {
+ this.loader = loader;
+ this.serializer = serializer;
+ this.urlBuilder = urlBuilder;
+ }
+
+ protected Loader getLoader() {
+ return this.loader;
+ }
+
+ protected DBSerializer getSerializer() {
+ return this.serializer;
+ }
+
+ protected UrlBuilder getUrlBuilder() {
+ return this.urlBuilder;
+ }
+
+ public Builder includeUrl() {
+ this.includeUrl = true;
+ return this;
+ }
+
+ public Builder nodesOnly(Boolean nodesOnly) {
+ this.nodesOnly = nodesOnly;
+ return this;
+ }
+
+ public boolean isNodesOnly() {
+ return this.nodesOnly;
+ }
+
+ public Builder depth(Integer depth) {
+ this.depth = depth;
+ return this;
+ }
+
+ public int getDepth() {
+ return this.depth;
+ }
+
+ public boolean isIncludeUrl() {
+ return this.includeUrl;
+ }
+
+ public Resource build() {
+ return new Resource(this);
+ }
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/serialization/queryformats/ResourceWithSoT.java b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/ResourceWithSoT.java
index 503f3a58..e4107aa9 100644
--- a/aai-core/src/main/java/org/onap/aai/serialization/queryformats/ResourceWithSoT.java
+++ b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/ResourceWithSoT.java
@@ -17,10 +17,14 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.serialization.queryformats;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
+
+import java.util.Optional;
+
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.onap.aai.db.props.AAIProperties;
import org.onap.aai.introspection.Loader;
@@ -31,8 +35,6 @@ import org.onap.aai.serialization.queryformats.params.NodesOnly;
import org.onap.aai.serialization.queryformats.utils.UrlBuilder;
import org.onap.aai.util.AAIConfig;
-import java.util.Optional;
-
public class ResourceWithSoT extends MultiFormatMapper {
protected JsonParser parser = new JsonParser();
protected final DBSerializer serializer;
@@ -40,6 +42,7 @@ public class ResourceWithSoT extends MultiFormatMapper {
protected final UrlBuilder urlBuilder;
protected final int depth;
protected final boolean nodesOnly;
+
protected ResourceWithSoT(Builder builder) {
this.urlBuilder = builder.getUrlBuilder();
this.loader = builder.getLoader();
@@ -62,6 +65,7 @@ public class ResourceWithSoT extends MultiFormatMapper {
protected boolean nodesOnly = false;
protected int depth = 1;
protected boolean modelDriven = false;
+
public Builder(Loader loader, DBSerializer serializer, UrlBuilder urlBuilder) {
this.loader = loader;
this.serializer = serializer;
@@ -89,6 +93,7 @@ public class ResourceWithSoT extends MultiFormatMapper {
this.nodesOnly = nodesOnly;
return this;
}
+
public boolean isNodesOnly() {
return this.nodesOnly;
}
@@ -114,6 +119,7 @@ public class ResourceWithSoT extends MultiFormatMapper {
public boolean getModelDriven() {
return this.modelDriven;
}
+
public ResourceWithSoT build() {
return new ResourceWithSoT(this);
}
@@ -122,7 +128,8 @@ public class ResourceWithSoT extends MultiFormatMapper {
/**
*
* Returns an Optional<JsonObject> to convert the contents from the given Vertex object into a JsonObject.
- * The fields returned are to record the time stamp of the creation/modification of the object, the user responsible for
+ * The fields returned are to record the time stamp of the creation/modification of the object, the user responsible
+ * for
* the change, and the last http method performed on the object.
*
* @param v
@@ -151,8 +158,10 @@ public class ResourceWithSoT extends MultiFormatMapper {
json.addProperty("source-of-truth", sotObj.toString());
json.addProperty("last-mod-source-of-truth", lastModSotObj.toString());
- // Check if the timestamp difference between creation and last modification are greater than a certain threshold, and if the source of truth differs
- // If the timestamp difference is marginal and the SoT (creator/modifier) is the same, the last action performed is likely to be a creation.
+ // Check if the timestamp difference between creation and last modification are greater than a certain
+ // threshold, and if the source of truth differs
+ // If the timestamp difference is marginal and the SoT (creator/modifier) is the same, the last action performed
+ // is likely to be a creation.
long timestampDiff = lastModifiedTimestamp - createdTimestamp;
boolean isSameSoT = sotObj.toString().equals(lastModSotObj.toString());
diff --git a/aai-core/src/main/java/org/onap/aai/serialization/queryformats/SimpleFormat.java b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/SimpleFormat.java
index c9d3a026..f1d1c26e 100644
--- a/aai-core/src/main/java/org/onap/aai/serialization/queryformats/SimpleFormat.java
+++ b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/SimpleFormat.java
@@ -17,10 +17,17 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.serialization.queryformats;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
+
+import java.io.UnsupportedEncodingException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Optional;
+
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Property;
import org.apache.tinkerpop.gremlin.structure.Vertex;
@@ -30,62 +37,54 @@ import org.onap.aai.introspection.Introspector;
import org.onap.aai.introspection.exceptions.AAIUnknownObjectException;
import org.onap.aai.serialization.queryformats.exceptions.AAIFormatVertexException;
-import java.io.UnsupportedEncodingException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Optional;
-
public class SimpleFormat extends RawFormat {
+ protected SimpleFormat(Builder builder) {
+ super(builder);
+
+ }
+
+ @Override
+ public int parallelThreshold() {
+ return 20;
+ }
+
+ @Override
+ public Optional<JsonObject> createPropertiesObject(Vertex v) throws AAIFormatVertexException {
+ try {
+ final Introspector obj =
+ loader.introspectorFromName(v.<String>property(AAIProperties.NODE_TYPE).orElse(null));
+
+ final List<Vertex> wrapper = new ArrayList<>();
+
+ wrapper.add(v);
+
+ try {
+ serializer.dbToObject(wrapper, obj, this.depth, true, "false");
+ } catch (AAIException | UnsupportedEncodingException e) {
+ throw new AAIFormatVertexException(
+ "Failed to format vertex - error while serializing: " + e.getMessage(), e);
+ }
+
+ final String json = obj.marshal(false);
+ return Optional.of(parser.parse(json).getAsJsonObject());
+ } catch (AAIUnknownObjectException e) {
+ return Optional.empty();
+ }
+
+ }
+
+ @Override
+ protected void addEdge(Edge e, Vertex v, JsonArray array) throws AAIFormatVertexException {
+
+ Property property = e.property("private");
+
+ if (property.isPresent()) {
+ if ("true".equals(e.property("private").value().toString())) {
+ return;
+ }
+ }
- protected SimpleFormat(Builder builder) {
- super(builder);
-
- }
-
- @Override
- public int parallelThreshold() {
- return 20;
- }
-
- @Override
- public Optional<JsonObject> createPropertiesObject(Vertex v) throws AAIFormatVertexException {
- try {
- final Introspector obj = loader.introspectorFromName(
- v.<String>property(AAIProperties.NODE_TYPE)
- .orElse(null)
- );
-
- final List<Vertex> wrapper = new ArrayList<>();
-
- wrapper.add(v);
-
- try {
- serializer.dbToObject(wrapper, obj, this.depth, true, "false");
- } catch (AAIException | UnsupportedEncodingException e) {
- throw new AAIFormatVertexException("Failed to format vertex - error while serializing: " + e.getMessage(), e);
- }
-
- final String json = obj.marshal(false);
- return Optional.of(parser.parse(json).getAsJsonObject());
- } catch (AAIUnknownObjectException e) {
- return Optional.empty();
- }
-
-
- }
-
- @Override
- protected void addEdge(Edge e, Vertex v, JsonArray array) throws AAIFormatVertexException {
-
- Property property = e.property("private");
-
- if(property.isPresent()){
- if("true".equals(e.property("private").value().toString())){
- return;
- }
- }
-
- super.addEdge(e, v, array);
- }
+ super.addEdge(e, v, array);
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/serialization/queryformats/SubGraphStyle.java b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/SubGraphStyle.java
index 95cbbf43..fb2e624c 100644
--- a/aai-core/src/main/java/org/onap/aai/serialization/queryformats/SubGraphStyle.java
+++ b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/SubGraphStyle.java
@@ -17,10 +17,9 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.serialization.queryformats;
public enum SubGraphStyle {
- star,
- prune,
- no_op
+ star, prune, no_op
}
diff --git a/aai-core/src/main/java/org/onap/aai/serialization/queryformats/exceptions/AAIFormatQueryResultFormatNotSupported.java b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/exceptions/AAIFormatQueryResultFormatNotSupported.java
index 9d79330f..add62644 100644
--- a/aai-core/src/main/java/org/onap/aai/serialization/queryformats/exceptions/AAIFormatQueryResultFormatNotSupported.java
+++ b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/exceptions/AAIFormatQueryResultFormatNotSupported.java
@@ -17,23 +17,25 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.serialization.queryformats.exceptions;
public class AAIFormatQueryResultFormatNotSupported extends Exception {
- private static final long serialVersionUID = -5814240842844624097L;
+ private static final long serialVersionUID = -5814240842844624097L;
- public AAIFormatQueryResultFormatNotSupported() {}
+ public AAIFormatQueryResultFormatNotSupported() {
+ }
- public AAIFormatQueryResultFormatNotSupported(String message) {
- super(message);
- }
+ public AAIFormatQueryResultFormatNotSupported(String message) {
+ super(message);
+ }
- public AAIFormatQueryResultFormatNotSupported(Throwable cause) {
- super(cause);
- }
+ public AAIFormatQueryResultFormatNotSupported(Throwable cause) {
+ super(cause);
+ }
- public AAIFormatQueryResultFormatNotSupported(String message, Throwable cause) {
- super(message, cause);
- }
+ public AAIFormatQueryResultFormatNotSupported(String message, Throwable cause) {
+ super(message, cause);
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/serialization/queryformats/exceptions/AAIFormatVertexException.java b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/exceptions/AAIFormatVertexException.java
index 108a9c8d..9c5f92a6 100644
--- a/aai-core/src/main/java/org/onap/aai/serialization/queryformats/exceptions/AAIFormatVertexException.java
+++ b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/exceptions/AAIFormatVertexException.java
@@ -17,23 +17,25 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.serialization.queryformats.exceptions;
public class AAIFormatVertexException extends Exception {
- private static final long serialVersionUID = -5814240841844624097L;
+ private static final long serialVersionUID = -5814240841844624097L;
- public AAIFormatVertexException() {}
+ public AAIFormatVertexException() {
+ }
- public AAIFormatVertexException(String message) {
- super(message);
- }
+ public AAIFormatVertexException(String message) {
+ super(message);
+ }
- public AAIFormatVertexException(Throwable cause) {
- super(cause);
- }
+ public AAIFormatVertexException(Throwable cause) {
+ super(cause);
+ }
- public AAIFormatVertexException(String message, Throwable cause) {
- super(message, cause);
- }
+ public AAIFormatVertexException(String message, Throwable cause) {
+ super(message, cause);
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/serialization/queryformats/exceptions/QueryParamInjectionException.java b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/exceptions/QueryParamInjectionException.java
index 31b0a573..58e60e61 100644
--- a/aai-core/src/main/java/org/onap/aai/serialization/queryformats/exceptions/QueryParamInjectionException.java
+++ b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/exceptions/QueryParamInjectionException.java
@@ -17,23 +17,24 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.serialization.queryformats.exceptions;
import org.onap.aai.exceptions.AAIException;
public class QueryParamInjectionException extends AAIException {
- private static final long serialVersionUID = -5575661036426538012L;
+ private static final long serialVersionUID = -5575661036426538012L;
- public QueryParamInjectionException(String message) {
- super("AAI_4017", message);
- }
+ public QueryParamInjectionException(String message) {
+ super("AAI_4017", message);
+ }
- public QueryParamInjectionException(Throwable cause) {
- super("AAI_4017",cause);
- }
+ public QueryParamInjectionException(Throwable cause) {
+ super("AAI_4017", cause);
+ }
- public QueryParamInjectionException(String message, Throwable cause) {
- super("AAI_4017", cause, message);
- }
+ public QueryParamInjectionException(String message, Throwable cause) {
+ super("AAI_4017", cause, message);
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/serialization/queryformats/params/Depth.java b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/params/Depth.java
index de485fe3..c8dea517 100644
--- a/aai-core/src/main/java/org/onap/aai/serialization/queryformats/params/Depth.java
+++ b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/params/Depth.java
@@ -17,11 +17,12 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.serialization.queryformats.params;
@Inject(name = "depth")
public interface Depth<T> {
- @Setter
- public T depth(Integer depth);
+ @Setter
+ public T depth(Integer depth);
}
diff --git a/aai-core/src/main/java/org/onap/aai/serialization/queryformats/params/Inject.java b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/params/Inject.java
index 6a1ff42e..bccbd11a 100644
--- a/aai-core/src/main/java/org/onap/aai/serialization/queryformats/params/Inject.java
+++ b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/params/Inject.java
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.serialization.queryformats.params;
import java.lang.annotation.Retention;
@@ -25,9 +26,10 @@ import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface Inject {
- /**
- * The way the query parameter appears in the URI
- * @return
- */
- String name();
+ /**
+ * The way the query parameter appears in the URI
+ *
+ * @return
+ */
+ String name();
}
diff --git a/aai-core/src/main/java/org/onap/aai/serialization/queryformats/params/NodesOnly.java b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/params/NodesOnly.java
index f0fa5da0..f909cd2b 100644
--- a/aai-core/src/main/java/org/onap/aai/serialization/queryformats/params/NodesOnly.java
+++ b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/params/NodesOnly.java
@@ -17,11 +17,12 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.serialization.queryformats.params;
@Inject(name = "nodesOnly")
public interface NodesOnly<T> {
- @Setter
- public T nodesOnly(Boolean nodesOnly);
+ @Setter
+ public T nodesOnly(Boolean nodesOnly);
}
diff --git a/aai-core/src/main/java/org/onap/aai/serialization/queryformats/params/Setter.java b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/params/Setter.java
index f760391d..327b2c11 100644
--- a/aai-core/src/main/java/org/onap/aai/serialization/queryformats/params/Setter.java
+++ b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/params/Setter.java
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.serialization.queryformats.params;
import java.lang.annotation.ElementType;
diff --git a/aai-core/src/main/java/org/onap/aai/serialization/queryformats/utils/QueryParamInjector.java b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/utils/QueryParamInjector.java
index e3976133..1b51088e 100644
--- a/aai-core/src/main/java/org/onap/aai/serialization/queryformats/utils/QueryParamInjector.java
+++ b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/utils/QueryParamInjector.java
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.serialization.queryformats.utils;
import java.lang.reflect.InvocationTargetException;
@@ -32,52 +33,49 @@ import org.reflections.Reflections;
public class QueryParamInjector {
- private final Set<Class<?>> results;
-
-
- private QueryParamInjector () {
- Reflections reflections = new Reflections("org.onap.aai.serialization.queryformats.params");
- results = reflections.getTypesAnnotatedWith(Inject.class);
- }
-
- private static class Helper {
- private static final QueryParamInjector INSTANCE = new QueryParamInjector();
- }
-
- public static QueryParamInjector getInstance() {
- return Helper.INSTANCE;
- }
-
- public <T> T injectParams(T obj, MultivaluedMap<String, String> params) throws QueryParamInjectionException{
- try {
- for (Class<?> item : results) {
- if (item.isAssignableFrom(obj.getClass())) {
- String name = item.getAnnotation(Inject.class).name();
-
- if (params.containsKey(name)) {
- String value = params.getFirst(name);
-
- for (Method method : item.getMethods()) {
- if (method.isAnnotationPresent(Setter.class)) {
- Class<?>[] args = method.getParameterTypes();
- if (args.length == 1) {
- Object o = args[0].getConstructor(String.class).newInstance(value);
- method.invoke(obj, o);
- } else {
- method.invoke(obj);
- }
- }
- }
- }
- }
- }
- } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
- | InvocationTargetException | NoSuchMethodException
- | SecurityException e) {
- throw new QueryParamInjectionException("issue with query params", e);
- }
-
-
- return obj;
- }
+ private final Set<Class<?>> results;
+
+ private QueryParamInjector() {
+ Reflections reflections = new Reflections("org.onap.aai.serialization.queryformats.params");
+ results = reflections.getTypesAnnotatedWith(Inject.class);
+ }
+
+ private static class Helper {
+ private static final QueryParamInjector INSTANCE = new QueryParamInjector();
+ }
+
+ public static QueryParamInjector getInstance() {
+ return Helper.INSTANCE;
+ }
+
+ public <T> T injectParams(T obj, MultivaluedMap<String, String> params) throws QueryParamInjectionException {
+ try {
+ for (Class<?> item : results) {
+ if (item.isAssignableFrom(obj.getClass())) {
+ String name = item.getAnnotation(Inject.class).name();
+
+ if (params.containsKey(name)) {
+ String value = params.getFirst(name);
+
+ for (Method method : item.getMethods()) {
+ if (method.isAnnotationPresent(Setter.class)) {
+ Class<?>[] args = method.getParameterTypes();
+ if (args.length == 1) {
+ Object o = args[0].getConstructor(String.class).newInstance(value);
+ method.invoke(obj, o);
+ } else {
+ method.invoke(obj);
+ }
+ }
+ }
+ }
+ }
+ }
+ } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException
+ | NoSuchMethodException | SecurityException e) {
+ throw new QueryParamInjectionException("issue with query params", e);
+ }
+
+ return obj;
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/serialization/queryformats/utils/UrlBuilder.java b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/utils/UrlBuilder.java
index 30459364..9da82fe0 100644
--- a/aai-core/src/main/java/org/onap/aai/serialization/queryformats/utils/UrlBuilder.java
+++ b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/utils/UrlBuilder.java
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.serialization.queryformats.utils;
import java.io.UnsupportedEncodingException;
@@ -24,80 +25,82 @@ import java.net.URI;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.onap.aai.exceptions.AAIException;
-import org.onap.aai.setup.SchemaVersion;
import org.onap.aai.serialization.db.DBSerializer;
import org.onap.aai.serialization.queryformats.exceptions.AAIFormatVertexException;
+import org.onap.aai.setup.SchemaVersion;
import org.onap.aai.setup.SchemaVersions;
import org.onap.aai.util.AAIConfig;
import org.onap.aai.util.AAIConstants;
public class UrlBuilder {
- private final DBSerializer serializer;
- private final SchemaVersion version;
- private final String serverBase;
- private final SchemaVersions schemaVersions;
- private final String basePath;
+ private final DBSerializer serializer;
+ private final SchemaVersion version;
+ private final String serverBase;
+ private final SchemaVersions schemaVersions;
+ private final String basePath;
+
+ public UrlBuilder(SchemaVersion version, DBSerializer serializer, SchemaVersions schemaVersions, String basePath)
+ throws AAIException {
+ this.serializer = serializer;
+ this.version = version;
+ this.serverBase = this.getServerBase();
+ this.schemaVersions = schemaVersions;
+ if (!basePath.endsWith("/")) {
+ this.basePath = basePath + "/";
+ } else {
+ this.basePath = basePath;
+ }
+ }
+
+ public UrlBuilder(SchemaVersion version, DBSerializer serializer, String serverBase, SchemaVersions schemaVersions,
+ String basePath) {
+ this.serializer = serializer;
+ this.version = version;
+ this.serverBase = serverBase;
+ this.schemaVersions = schemaVersions;
+ if (!basePath.endsWith("/")) {
+ this.basePath = basePath + "/";
+ } else {
+ this.basePath = basePath;
+ }
+ }
+
+ public String pathed(Vertex v) throws AAIFormatVertexException {
+
+ try {
+ final StringBuilder result = new StringBuilder();
+ final URI uri = this.serializer.getURIForVertex(v);
+
+ if (this.version.compareTo(schemaVersions.getAppRootVersion()) >= 0) {
+ result.append(basePath);
+ } else {
+ result.append(this.serverBase);
+ }
+ result.append(this.version);
+ result.append(uri.getRawPath());
- public UrlBuilder (SchemaVersion version, DBSerializer serializer, SchemaVersions schemaVersions, String basePath) throws AAIException {
- this.serializer = serializer;
- this.version = version;
- this.serverBase = this.getServerBase();
- this.schemaVersions = schemaVersions;
- if(!basePath.endsWith("/")){
- this.basePath = basePath + "/";
- } else {
- this.basePath = basePath;
- }
- }
-
- public UrlBuilder (SchemaVersion version, DBSerializer serializer, String serverBase, SchemaVersions schemaVersions, String basePath) {
- this.serializer = serializer;
- this.version = version;
- this.serverBase = serverBase;
- this.schemaVersions = schemaVersions;
- if(!basePath.endsWith("/")){
- this.basePath = basePath + "/";
- } else {
- this.basePath = basePath;
- }
- }
-
- public String pathed(Vertex v) throws AAIFormatVertexException {
+ return result.toString();
+ } catch (UnsupportedEncodingException | IllegalArgumentException | SecurityException e) {
+ throw new AAIFormatVertexException(e);
+ }
+ }
- try {
- final StringBuilder result = new StringBuilder();
- final URI uri = this.serializer.getURIForVertex(v);
+ public String id(Vertex v) {
+ final StringBuilder result = new StringBuilder();
- if (this.version.compareTo(schemaVersions.getAppRootVersion()) >= 0) {
- result.append(basePath);
- } else {
- result.append(this.serverBase);
- }
- result.append(this.version);
- result.append(uri.getRawPath());
-
- return result.toString();
- } catch (UnsupportedEncodingException | IllegalArgumentException | SecurityException e) {
- throw new AAIFormatVertexException(e);
- }
- }
-
- public String id(Vertex v) {
- final StringBuilder result = new StringBuilder();
+ result.append("/resources/id/" + v.id());
+ result.insert(0, this.version);
+ if (this.version.compareTo(schemaVersions.getAppRootVersion()) >= 0) {
+ result.insert(0, basePath);
+ } else {
+ result.insert(0, this.serverBase);
+ }
- result.append("/resources/id/" + v.id());
- result.insert(0, this.version);
- if (this.version.compareTo(schemaVersions.getAppRootVersion()) >= 0) {
- result.insert(0, basePath);
- } else {
- result.insert(0, this.serverBase);
- }
+ return result.toString();
+ }
- return result.toString();
- }
-
- protected String getServerBase() throws AAIException {
- return AAIConfig.get(AAIConstants.AAI_SERVER_URL_BASE);
- }
+ protected String getServerBase() throws AAIException {
+ return AAIConfig.get(AAIConstants.AAI_SERVER_URL_BASE);
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/serialization/tinkerpop/TreeBackedEdge.java b/aai-core/src/main/java/org/onap/aai/serialization/tinkerpop/TreeBackedEdge.java
index 09abfb11..50174d03 100644
--- a/aai-core/src/main/java/org/onap/aai/serialization/tinkerpop/TreeBackedEdge.java
+++ b/aai-core/src/main/java/org/onap/aai/serialization/tinkerpop/TreeBackedEdge.java
@@ -17,8 +17,11 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.serialization.tinkerpop;
+import java.util.Iterator;
+
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Graph;
@@ -26,54 +29,49 @@ import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.util.detached.DetachedEdge;
import org.apache.tinkerpop.gremlin.util.iterator.IteratorUtils;
-import java.util.Iterator;
-
-
/**
- * Represents a {@link Edge} that is disconnected from a {@link Graph} however,
+ * Represents a {@link Edge} that is disconnected from a {@link Graph} however,
* traversals are supported as they are backed by a Tree with saturated {@link Vertex} and {@link Edge} objects.
* These objects are not mutable and can only be used to read information out.
*
*/
public class TreeBackedEdge extends DetachedEdge implements Edge {
- private static final long serialVersionUID = 5419650145562077538L;
- private TreeBackedVertex inVertex;
- private TreeBackedVertex outVertex;
- public TreeBackedEdge(Edge edge, TreeBackedVertex inVertex, TreeBackedVertex outVertex) {
- super(edge, true);
- this.inVertex = inVertex;
- this.outVertex = outVertex;
- }
-
- @Override
- public Vertex inVertex() {
- return this.inVertex;
- }
-
- @Override
- public Vertex outVertex() {
- return this.outVertex;
- }
-
- @Override
- public Iterator<Vertex> bothVertices() {
- return this.vertices(Direction.BOTH);
- }
-
- @Override
- public Iterator<Vertex> vertices(Direction direction) {
- switch (direction) {
- case OUT:
- return IteratorUtils.of(this.outVertex);
- case IN:
- return IteratorUtils.of(this.inVertex);
- default:
- return IteratorUtils.of(this.outVertex, this.inVertex);
- }
- }
+ private static final long serialVersionUID = 5419650145562077538L;
+ private TreeBackedVertex inVertex;
+ private TreeBackedVertex outVertex;
+
+ public TreeBackedEdge(Edge edge, TreeBackedVertex inVertex, TreeBackedVertex outVertex) {
+ super(edge, true);
+ this.inVertex = inVertex;
+ this.outVertex = outVertex;
+ }
+
+ @Override
+ public Vertex inVertex() {
+ return this.inVertex;
+ }
+
+ @Override
+ public Vertex outVertex() {
+ return this.outVertex;
+ }
+ @Override
+ public Iterator<Vertex> bothVertices() {
+ return this.vertices(Direction.BOTH);
+ }
-
+ @Override
+ public Iterator<Vertex> vertices(Direction direction) {
+ switch (direction) {
+ case OUT:
+ return IteratorUtils.of(this.outVertex);
+ case IN:
+ return IteratorUtils.of(this.inVertex);
+ default:
+ return IteratorUtils.of(this.outVertex, this.inVertex);
+ }
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/serialization/tinkerpop/TreeBackedVertex.java b/aai-core/src/main/java/org/onap/aai/serialization/tinkerpop/TreeBackedVertex.java
index 62a45894..c2856a77 100644
--- a/aai-core/src/main/java/org/onap/aai/serialization/tinkerpop/TreeBackedVertex.java
+++ b/aai-core/src/main/java/org/onap/aai/serialization/tinkerpop/TreeBackedVertex.java
@@ -17,19 +17,20 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-package org.onap.aai.serialization.tinkerpop;
-import org.apache.tinkerpop.gremlin.process.traversal.step.util.Tree;
-import org.apache.tinkerpop.gremlin.structure.*;
-import org.apache.tinkerpop.gremlin.structure.util.detached.DetachedVertex;
+package org.onap.aai.serialization.tinkerpop;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
+import org.apache.tinkerpop.gremlin.process.traversal.step.util.Tree;
+import org.apache.tinkerpop.gremlin.structure.*;
+import org.apache.tinkerpop.gremlin.structure.util.detached.DetachedVertex;
+
/**
- * Represents a {@link Vertex} that is disconnected from a {@link Graph} however,
+ * Represents a {@link Vertex} that is disconnected from a {@link Graph} however,
* traversals are supported as they are backed by a Tree with saturated {@link Vertex} and {@link Edge} objects.
* These objects are not mutable and can only be used to read information out.
*
@@ -37,125 +38,127 @@ import java.util.List;
public class TreeBackedVertex extends DetachedVertex implements Vertex {
- private static final long serialVersionUID = -976854460992756953L;
- private final Tree<Element> tree;
- private final Vertex self;
- public TreeBackedVertex (Vertex v, Tree<Element> tree) {
- super(v, true);
- this.self = v;
- this.tree = tree;
- }
-
- @Override
+ private static final long serialVersionUID = -976854460992756953L;
+ private final Tree<Element> tree;
+ private final Vertex self;
+
+ public TreeBackedVertex(Vertex v, Tree<Element> tree) {
+ super(v, true);
+ this.self = v;
+ this.tree = tree;
+ }
+
+ @Override
public Iterator<Edge> edges(final Direction direction, final String... edgeLabels) {
- final List<Element> edges = tree.getObjectsAtDepth(2);
- final List<Tree<Element>> trees = tree.getTreesAtDepth(2);
- final List<Tree<Element>> vTrees = tree.getTreesAtDepth(3);
- return edges.stream().map( ele -> (Edge)ele).filter(e -> {
- if (Direction.IN.equals(direction)) {
- return e.inVertex().equals(self);
- } else if (Direction.OUT.equals(direction)) {
- return e.outVertex().equals(self);
- } else {
- return true;
- }
- }).filter(e -> {
- boolean result = false;
- if (edgeLabels.length == 0) {
- return true;
- }
- for (String label : edgeLabels) {
- if (label.equals(e.label())) {
- result = true;
- break;
- }
- }
- return result;
- }).map(e -> {
- Tree<Element> eTree = new Tree<>();
- for (Tree<Element> tree : trees) {
- if (tree.keySet().contains(e)) {
- eTree = tree;
- break;
- }
- }
- TreeBackedVertex in = null;
- TreeBackedVertex out = null;
- if (e.inVertex().equals(self)) {
- in = this;
- out = this.createForVertex(e.outVertex(), vTrees);
- } else if (e.outVertex().equals(self)) {
- out = this;
- in = this.createForVertex(e.inVertex(), vTrees);
- }
- return (Edge)new TreeBackedEdge(e, in, out);
- }).iterator();
+ final List<Element> edges = tree.getObjectsAtDepth(2);
+ final List<Tree<Element>> trees = tree.getTreesAtDepth(2);
+ final List<Tree<Element>> vTrees = tree.getTreesAtDepth(3);
+ return edges.stream().map(ele -> (Edge) ele).filter(e -> {
+ if (Direction.IN.equals(direction)) {
+ return e.inVertex().equals(self);
+ } else if (Direction.OUT.equals(direction)) {
+ return e.outVertex().equals(self);
+ } else {
+ return true;
+ }
+ }).filter(e -> {
+ boolean result = false;
+ if (edgeLabels.length == 0) {
+ return true;
+ }
+ for (String label : edgeLabels) {
+ if (label.equals(e.label())) {
+ result = true;
+ break;
+ }
+ }
+ return result;
+ }).map(e -> {
+ Tree<Element> eTree = new Tree<>();
+ for (Tree<Element> tree : trees) {
+ if (tree.keySet().contains(e)) {
+ eTree = tree;
+ break;
+ }
+ }
+ TreeBackedVertex in = null;
+ TreeBackedVertex out = null;
+ if (e.inVertex().equals(self)) {
+ in = this;
+ out = this.createForVertex(e.outVertex(), vTrees);
+ } else if (e.outVertex().equals(self)) {
+ out = this;
+ in = this.createForVertex(e.inVertex(), vTrees);
+ }
+ return (Edge) new TreeBackedEdge(e, in, out);
+ }).iterator();
+
+ }
+
+ private TreeBackedVertex createForVertex(Vertex v, List<Tree<Element>> trees) {
+ Tree<Element> vTree = new Tree<>();
+ for (Tree<Element> tree : trees) {
+ if (tree.keySet().contains(v)) {
+ vTree = tree;
+ break;
+ }
+ }
+ return new TreeBackedVertex((Vertex) vTree.keySet().iterator().next(), vTree);
}
-
- private TreeBackedVertex createForVertex(Vertex v, List<Tree<Element>> trees) {
- Tree<Element> vTree = new Tree<>();
- for (Tree<Element> tree : trees) {
- if (tree.keySet().contains(v)) {
- vTree = tree;
- break;
- }
- }
-
- return new TreeBackedVertex((Vertex)vTree.keySet().iterator().next(), vTree);
- }
+
@Override
public Iterator<Vertex> vertices(final Direction direction, final String... labels) {
- final List<Tree<Element>> vertexElements = tree.getTreesAtDepth(3);
- final List<Element> edgeElements = tree.getObjectsAtDepth(2);
- return edgeElements.stream().map( ele -> (Edge)ele).filter(e -> {
- boolean result = false;
- if (labels.length == 0) {
- return true;
- }
- for (String label : labels) {
- if (label.equals(e.label())) {
- result = true;
- break;
- }
- }
- return result;
- }).filter(e -> {
- if (Direction.IN.equals(direction) && e.inVertex().equals(self)) {
- return true;
- } else if (Direction.OUT.equals(direction) && e.outVertex().equals(self)) {
- return true;
- } else if (Direction.BOTH.equals(direction)){
- return true;
- } else {
- return false;
- }
- }).map(e -> {
- final List<Vertex> list;
- if (Direction.IN.equals(direction)) {
- list = Collections.singletonList(e.outVertex());
- } else if (Direction.OUT.equals(direction)){
- list = Collections.singletonList(e.inVertex());
- } else {
- list = new ArrayList<>();
- Iterator<Vertex> itr = e.bothVertices();
- while (itr.hasNext()) {
- list.add(itr.next());
- }
- }
- return list;
-
- }).flatMap(list -> list.stream()).map(v -> {
- Tree<Element> vTree = new Tree<Element>();
- for (Tree<Element> tree : vertexElements) {
- if (tree.keySet().contains(v)) {
- vTree = tree;
- break;
- }
- }
-
- return (Vertex)new TreeBackedVertex(v, vTree);
- }).iterator();
- }
-
+ final List<Tree<Element>> vertexElements = tree.getTreesAtDepth(3);
+ final List<Element> edgeElements = tree.getObjectsAtDepth(2);
+ return edgeElements.stream().map(ele -> (Edge) ele).filter(e -> {
+ boolean result = false;
+ if (labels.length == 0) {
+ return true;
+ }
+ for (String label : labels) {
+ if (label.equals(e.label())) {
+ result = true;
+ break;
+ }
+ }
+ return result;
+ }).filter(e -> {
+ if (Direction.IN.equals(direction) && e.inVertex().equals(self)) {
+ return true;
+ } else if (Direction.OUT.equals(direction) && e.outVertex().equals(self)) {
+ return true;
+ } else if (Direction.BOTH.equals(direction)) {
+ return true;
+ } else {
+ return false;
+ }
+ }).map(e -> {
+ final List<Vertex> list;
+ if (Direction.IN.equals(direction)) {
+ list = Collections.singletonList(e.outVertex());
+ } else if (Direction.OUT.equals(direction)) {
+ list = Collections.singletonList(e.inVertex());
+ } else {
+ list = new ArrayList<>();
+ Iterator<Vertex> itr = e.bothVertices();
+ while (itr.hasNext()) {
+ list.add(itr.next());
+ }
+ }
+ return list;
+
+ }).flatMap(list -> list.stream()).map(v -> {
+ Tree<Element> vTree = new Tree<Element>();
+ for (Tree<Element> tree : vertexElements) {
+ if (tree.keySet().contains(v)) {
+ vTree = tree;
+ break;
+ }
+ }
+
+ return (Vertex) new TreeBackedVertex(v, vTree);
+ }).iterator();
+ }
+
}
diff --git a/aai-core/src/main/java/org/onap/aai/service/NodeValidationService.java b/aai-core/src/main/java/org/onap/aai/service/NodeValidationService.java
index c7ef769b..316e3017 100644
--- a/aai-core/src/main/java/org/onap/aai/service/NodeValidationService.java
+++ b/aai-core/src/main/java/org/onap/aai/service/NodeValidationService.java
@@ -17,18 +17,20 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.service;
import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
+
+import javax.annotation.PostConstruct;
+
import org.onap.aai.validation.nodes.NodeValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
-import javax.annotation.PostConstruct;
-
@Service
@ConditionalOnProperty(name = "schema.translator.list", havingValue = "config", matchIfMissing = true)
@PropertySource(value = "classpath:schema-ingest.properties", ignoreResourceNotFound = true)
@@ -37,20 +39,19 @@ public class NodeValidationService {
private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(NodeValidationService.class);
- @Autowired(required=false)
+ @Autowired(required = false)
private NodeValidator nodeValidator;
- public NodeValidationService(NodeValidator nodeValidator){
+ public NodeValidationService(NodeValidator nodeValidator) {
this.nodeValidator = nodeValidator;
}
@PostConstruct
- public void initialize(){
- if(!nodeValidator.validate()){
+ public void initialize() {
+ if (!nodeValidator.validate()) {
LOGGER.warn(nodeValidator.getErrorMsg());
} else {
LOGGER.info("Node validation check passed");
}
}
}
-
diff --git a/aai-core/src/main/java/org/onap/aai/tasks/ScheduledTasks.java b/aai-core/src/main/java/org/onap/aai/tasks/ScheduledTasks.java
index 81c81f55..911603d2 100644
--- a/aai-core/src/main/java/org/onap/aai/tasks/ScheduledTasks.java
+++ b/aai-core/src/main/java/org/onap/aai/tasks/ScheduledTasks.java
@@ -17,8 +17,12 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.tasks;
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
+
import java.io.File;
import java.util.Arrays;
import java.util.Date;
@@ -26,73 +30,70 @@ import java.util.UUID;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.comparator.LastModifiedFileComparator;
-import org.springframework.scheduling.annotation.Scheduled;
-import org.springframework.stereotype.Component;
-
import org.onap.aai.logging.LoggingContext;
import org.onap.aai.logging.LoggingContext.StatusCode;
import org.onap.aai.util.AAIConfig;
import org.onap.aai.util.AAIConstants;
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
+import org.springframework.scheduling.annotation.Scheduled;
+import org.springframework.stereotype.Component;
@Component
public class ScheduledTasks {
- private static EELFLogger LOGGER = EELFManager.getInstance().getLogger(ScheduledTasks.class);
+ private static EELFLogger LOGGER = EELFManager.getInstance().getLogger(ScheduledTasks.class);
- private static final String COMPONENT = "Scheduler";
- private static final String FROM_APP_ID = "CronApp";
- private static final long PROPERTY_READ_INTERVAL = 60000; // every minute
+ private static final String COMPONENT = "Scheduler";
+ private static final String FROM_APP_ID = "CronApp";
+ private static final long PROPERTY_READ_INTERVAL = 60000; // every minute
- private String GlobalPropFileName = AAIConstants.AAI_CONFIG_FILENAME;
+ private String GlobalPropFileName = AAIConstants.AAI_CONFIG_FILENAME;
- // for read and possibly reloading aaiconfig.properties and other
- /**
- * Load AAI properties.
- */
- // configuration properties files
- @Scheduled(fixedRate = PROPERTY_READ_INTERVAL)
- public void loadAAIProperties() {
- final UUID transId = UUID.randomUUID();
+ // for read and possibly reloading aaiconfig.properties and other
+ /**
+ * Load AAI properties.
+ */
+ // configuration properties files
+ @Scheduled(fixedRate = PROPERTY_READ_INTERVAL)
+ public void loadAAIProperties() {
+ final UUID transId = UUID.randomUUID();
- //LoggingContext.init();
- LoggingContext.save();
- LoggingContext.requestId(transId);
- LoggingContext.partnerName(FROM_APP_ID);
- LoggingContext.component(COMPONENT);
- LoggingContext.targetEntity("AAI");
- LoggingContext.targetServiceName("loadAAIProperties");
- LoggingContext.serviceName("AAI");
- LoggingContext.statusCode(StatusCode.COMPLETE);
- LoggingContext.responseCode(LoggingContext.SUCCESS);
+ // LoggingContext.init();
+ LoggingContext.save();
+ LoggingContext.requestId(transId);
+ LoggingContext.partnerName(FROM_APP_ID);
+ LoggingContext.component(COMPONENT);
+ LoggingContext.targetEntity("AAI");
+ LoggingContext.targetServiceName("loadAAIProperties");
+ LoggingContext.serviceName("AAI");
+ LoggingContext.statusCode(StatusCode.COMPLETE);
+ LoggingContext.responseCode(LoggingContext.SUCCESS);
- String dir = FilenameUtils.getFullPathNoEndSeparator(GlobalPropFileName);
- if (dir == null || dir.length() < 3) {
- dir = "/opt/aai/etc";
- }
+ String dir = FilenameUtils.getFullPathNoEndSeparator(GlobalPropFileName);
+ if (dir == null || dir.length() < 3) {
+ dir = "/opt/aai/etc";
+ }
- File pdir = new File(dir);
- File[] files = pdir.listFiles();
- Arrays.sort(files, LastModifiedFileComparator.LASTMODIFIED_REVERSE);
- String fn;
+ File pdir = new File(dir);
+ File[] files = pdir.listFiles();
+ Arrays.sort(files, LastModifiedFileComparator.LASTMODIFIED_REVERSE);
+ String fn;
- // leave this loop here since we may want to check other configurable
- // property files in the SAME directory
- for (File file : files) {
- fn = file.getName();
- if (fn.equals("aaiconfig.properties")) {
- Date lastMod = new Date(file.lastModified());
- long lastModTm = lastMod.getTime();
- Date curTS = new Date();
- long curTSTm = curTS.getTime();
- if (curTSTm - lastModTm < PROPERTY_READ_INTERVAL + 1000) {
- AAIConfig.reloadConfig();
- LOGGER.debug("reloaded from aaiconfig.properties");
- }
- break;
- }
- }
- LoggingContext.restoreIfPossible();
- }
+ // leave this loop here since we may want to check other configurable
+ // property files in the SAME directory
+ for (File file : files) {
+ fn = file.getName();
+ if (fn.equals("aaiconfig.properties")) {
+ Date lastMod = new Date(file.lastModified());
+ long lastModTm = lastMod.getTime();
+ Date curTS = new Date();
+ long curTSTm = curTS.getTime();
+ if (curTSTm - lastModTm < PROPERTY_READ_INTERVAL + 1000) {
+ AAIConfig.reloadConfig();
+ LOGGER.debug("reloaded from aaiconfig.properties");
+ }
+ break;
+ }
+ }
+ LoggingContext.restoreIfPossible();
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/util/AAIConfig.java b/aai-core/src/main/java/org/onap/aai/util/AAIConfig.java
index 86cb635e..c2103071 100644
--- a/aai-core/src/main/java/org/onap/aai/util/AAIConfig.java
+++ b/aai-core/src/main/java/org/onap/aai/util/AAIConfig.java
@@ -17,57 +17,57 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.util;
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
+
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.util.Properties;
-import org.onap.aai.logging.LoggingContext;
-import org.onap.aai.logging.LoggingContext.StatusCode;
-
import java.util.UUID;
import org.eclipse.jetty.util.security.Password;
-
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.logging.ErrorLogHelper;
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
-
+import org.onap.aai.logging.LoggingContext;
+import org.onap.aai.logging.LoggingContext.StatusCode;
public class AAIConfig {
- private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(AAIConfig.class);
- private static final String GLOBAL_PROP_FILE_NAME = AAIConstants.AAI_CONFIG_FILENAME;
- private static Properties serverProps;
+ private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(AAIConfig.class);
+ private static final String GLOBAL_PROP_FILE_NAME = AAIConstants.AAI_CONFIG_FILENAME;
+ private static Properties serverProps;
private static boolean propsInitialized = false;
/**
* Instantiates a new AAI config.
*/
// Don't instantiate
- private AAIConfig() {}
+ private AAIConfig() {
+ }
/**
* Inits the.
*
* @throws AAIException the AAI exception
*/
- public synchronized static void init() throws AAIException{
+ public synchronized static void init() throws AAIException {
- LoggingContext.save();
- LoggingContext.component("config");
- LoggingContext.partnerName("NA");
- LoggingContext.targetEntity("AAI");
- LoggingContext.requestId(UUID.randomUUID().toString());
- LoggingContext.serviceName("AAI");
- LoggingContext.targetServiceName("init");
- LoggingContext.statusCode(StatusCode.COMPLETE);
+ LoggingContext.save();
+ LoggingContext.component("config");
+ LoggingContext.partnerName("NA");
+ LoggingContext.targetEntity("AAI");
+ LoggingContext.requestId(UUID.randomUUID().toString());
+ LoggingContext.serviceName("AAI");
+ LoggingContext.targetServiceName("init");
+ LoggingContext.statusCode(StatusCode.COMPLETE);
- LOGGER.info("Initializing AAIConfig");
+ LOGGER.info("Initializing AAIConfig");
AAIConfig.getConfigFile();
AAIConfig.reloadConfig();
@@ -99,15 +99,15 @@ public class AAIConfig {
LOGGER.debug("Reloading config from " + propFileName);
- try(InputStream is = new FileInputStream(propFileName)) {
+ try (InputStream is = new FileInputStream(propFileName)) {
newServerProps = new Properties();
newServerProps.load(is);
propsInitialized = true;
serverProps = newServerProps;
} catch (FileNotFoundException fnfe) {
- ErrorLogHelper.logError("AAI_4001", " " + propFileName + ". Exception: "+fnfe.getMessage());
+ ErrorLogHelper.logError("AAI_4001", " " + propFileName + ". Exception: " + fnfe.getMessage());
} catch (IOException e) {
- ErrorLogHelper.logError("AAI_4002", " " + propFileName + ". IOException: "+e.getMessage());
+ ErrorLogHelper.logError("AAI_4002", " " + propFileName + ". IOException: " + e.getMessage());
}
}
@@ -119,15 +119,15 @@ public class AAIConfig {
* @return the string
*/
public static String get(String key, String defaultValue) {
- String result = defaultValue;
- try {
- result = get (key);
- } catch ( AAIException a ) {
- }
- if (result == null || result.isEmpty()) {
- result = defaultValue;
- }
- return ( result );
+ String result = defaultValue;
+ try {
+ result = get(key);
+ } catch (AAIException a) {
+ }
+ if (result == null || result.isEmpty()) {
+ result = defaultValue;
+ }
+ return (result);
}
/**
@@ -138,36 +138,37 @@ public class AAIConfig {
* @throws AAIException the AAI exception
*/
public static String get(String key) throws AAIException {
- String response = null;
-
- if (key.equals(AAIConstants.AAI_NODENAME)) {
- // Get this from InetAddress rather than the properties file
- String nodeName = getNodeName();
- if (nodeName != null) {
- return nodeName;
- }
- // else get from property file
- }
-
- if (!propsInitialized || (serverProps == null)) {
- reloadConfig();
- }
-
- if ((key.endsWith("password") || key.endsWith("passwd") || key.endsWith("apisecret")) && serverProps.containsKey(key+".x")) {
- String valx = serverProps.getProperty(key+".x");
- return Password.deobfuscate(valx);
- }
-
- if (!serverProps.containsKey(key)) {
- throw new AAIException("AAI_4005", "Property key "+key+" cannot be found");
- } else {
- response = serverProps.getProperty(key);
- if (response == null || response.isEmpty()) {
- throw new AAIException("AAI_4005", "Property key "+key+" is null or empty");
- }
- }
- return response;
- }
+ String response = null;
+
+ if (key.equals(AAIConstants.AAI_NODENAME)) {
+ // Get this from InetAddress rather than the properties file
+ String nodeName = getNodeName();
+ if (nodeName != null) {
+ return nodeName;
+ }
+ // else get from property file
+ }
+
+ if (!propsInitialized || (serverProps == null)) {
+ reloadConfig();
+ }
+
+ if ((key.endsWith("password") || key.endsWith("passwd") || key.endsWith("apisecret"))
+ && serverProps.containsKey(key + ".x")) {
+ String valx = serverProps.getProperty(key + ".x");
+ return Password.deobfuscate(valx);
+ }
+
+ if (!serverProps.containsKey(key)) {
+ throw new AAIException("AAI_4005", "Property key " + key + " cannot be found");
+ } else {
+ response = serverProps.getProperty(key);
+ if (response == null || response.isEmpty()) {
+ throw new AAIException("AAI_4005", "Property key " + key + " is null or empty");
+ }
+ }
+ return response;
+ }
/**
* Gets the int.
@@ -176,9 +177,9 @@ public class AAIConfig {
* @return the int
* @throws AAIException the AAI exception
*/
- public static int getInt(String key) throws AAIException{
- return Integer.parseInt(AAIConfig.get(key));
- }
+ public static int getInt(String key) throws AAIException {
+ return Integer.parseInt(AAIConfig.get(key));
+ }
/**
* Gets the int.
@@ -190,44 +191,42 @@ public class AAIConfig {
return Integer.parseInt(AAIConfig.get(key, value));
}
- /**
- * Gets the server props.
- *
- * @return the server props
- */
- public static Properties getServerProps() {
- return serverProps;
- }
-
- /**
- * Gets the node name.
- *
- * @return the node name
- */
- public static String getNodeName() {
- try {
+ /**
+ * Gets the server props.
+ *
+ * @return the server props
+ */
+ public static Properties getServerProps() {
+ return serverProps;
+ }
+
+ /**
+ * Gets the node name.
+ *
+ * @return the node name
+ */
+ public static String getNodeName() {
+ try {
InetAddress ip = InetAddress.getLocalHost();
if (ip != null) {
- String hostname = ip.getHostName();
- if (hostname != null) {
- return hostname;
- }
+ String hostname = ip.getHostName();
+ if (hostname != null) {
+ return hostname;
+ }
}
- } catch (Exception e) {
- return null;
- }
- return null;
- }
-
-
- /**
- * Check if a null or an Empty string is passed in.
- *
- * @param s the s
- * @return boolean
- */
- public static boolean isEmpty(String s)
- {
- return (s == null || s.length() == 0);
- }
+ } catch (Exception e) {
+ return null;
+ }
+ return null;
+ }
+
+ /**
+ * Check if a null or an Empty string is passed in.
+ *
+ * @param s the s
+ * @return boolean
+ */
+ public static boolean isEmpty(String s) {
+ return (s == null || s.length() == 0);
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/util/AAIConfigCommandLinePropGetter.java b/aai-core/src/main/java/org/onap/aai/util/AAIConfigCommandLinePropGetter.java
index 8f4b1105..0d894e74 100644
--- a/aai-core/src/main/java/org/onap/aai/util/AAIConfigCommandLinePropGetter.java
+++ b/aai-core/src/main/java/org/onap/aai/util/AAIConfigCommandLinePropGetter.java
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.util;
import org.onap.aai.exceptions.AAIException;
@@ -32,34 +33,35 @@ import org.onap.aai.exceptions.AAIException;
*/
public class AAIConfigCommandLinePropGetter {
- /**
- * The main method.
- *
- * @param args the arguments
- */
- /*
- * usage:
- * AAIConfigCommandLinePropGetter propertyname
- */
- public static void main(String[] args) {
- if (args.length != 1) {
- // System.out.println("only one property may be requested at a time");
- // System.out.println("usage: AAIConfigCommandLinePropGetter propertyname");
- }
- try {
- AAIConfig.init();
- String value = AAIConfig.get(args[0]);
- if (value != null) {
- System.out.println(value); //bc this utility used by a shell script so it needs the result sent to stdout
- } else {
- System.out.println("requested property could not be found");
- }
- } catch(AAIException e) {
- //System.out.println("exception:" + e.toString()); //TODO is this reasonable?
- } finally {
- System.exit(0);
- }
+ /**
+ * The main method.
+ *
+ * @param args the arguments
+ */
+ /*
+ * usage:
+ * AAIConfigCommandLinePropGetter propertyname
+ */
+ public static void main(String[] args) {
+ if (args.length != 1) {
+ // System.out.println("only one property may be requested at a time");
+ // System.out.println("usage: AAIConfigCommandLinePropGetter propertyname");
+ }
+ try {
+ AAIConfig.init();
+ String value = AAIConfig.get(args[0]);
+ if (value != null) {
+ System.out.println(value); // bc this utility used by a shell script so it needs the result sent to
+ // stdout
+ } else {
+ System.out.println("requested property could not be found");
+ }
+ } catch (AAIException e) {
+ // System.out.println("exception:" + e.toString()); //TODO is this reasonable?
+ } finally {
+ System.exit(0);
+ }
- }
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/util/AAIConstants.java b/aai-core/src/main/java/org/onap/aai/util/AAIConstants.java
index 59e676f8..e906c280 100644
--- a/aai-core/src/main/java/org/onap/aai/util/AAIConstants.java
+++ b/aai-core/src/main/java/org/onap/aai/util/AAIConstants.java
@@ -19,6 +19,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.util;
public final class AAIConstants {
@@ -26,12 +27,18 @@ public final class AAIConstants {
//
//
/** Default to unix file separator if system property file.separator is null */
- public static final String AAI_FILESEP = (System.getProperty("file.separator") == null) ? "/" : System.getProperty("file.separator");
+ public static final String AAI_FILESEP =
+ (System.getProperty("file.separator") == null) ? "/" : System.getProperty("file.separator");
//
/** Default to opt aai if system property aai.home is null, using file.separator */
- public static final String AAI_HOME = (System.getProperty(AJSC_HOME) == null) ? AAI_FILESEP + "opt" + AAI_FILESEP + "app" + AAI_FILESEP +"aai" : System.getProperty(AJSC_HOME);
- public static final String AAI_BUNDLECONFIG_NAME = (System.getProperty("BUNDLECONFIG_DIR") == null) ? "bundleconfig" : System.getProperty("BUNDLECONFIG_DIR");
- public static final String AAI_HOME_BUNDLECONFIG = (System.getProperty(AJSC_HOME) == null) ? AAI_FILESEP + "opt" + AAI_FILESEP + "app" + AAI_FILESEP + "aai" + AAI_FILESEP + AAI_BUNDLECONFIG_NAME : System.getProperty(AJSC_HOME)+ AAI_FILESEP + AAI_BUNDLECONFIG_NAME;
+ public static final String AAI_HOME =
+ (System.getProperty(AJSC_HOME) == null) ? AAI_FILESEP + "opt" + AAI_FILESEP + "app" + AAI_FILESEP + "aai"
+ : System.getProperty(AJSC_HOME);
+ public static final String AAI_BUNDLECONFIG_NAME =
+ (System.getProperty("BUNDLECONFIG_DIR") == null) ? "bundleconfig" : System.getProperty("BUNDLECONFIG_DIR");
+ public static final String AAI_HOME_BUNDLECONFIG = (System.getProperty(AJSC_HOME) == null)
+ ? AAI_FILESEP + "opt" + AAI_FILESEP + "app" + AAI_FILESEP + "aai" + AAI_FILESEP + AAI_BUNDLECONFIG_NAME
+ : System.getProperty(AJSC_HOME) + AAI_FILESEP + AAI_BUNDLECONFIG_NAME;
/** etc directory, relative to AAI_HOME */
public static final String AAI_HOME_ETC = AAI_HOME_BUNDLECONFIG + AAI_FILESEP + "etc" + AAI_FILESEP;
@@ -42,7 +49,8 @@ public final class AAIConstants {
public static final String REALTIME_DB_CONFIG = AAI_HOME_ETC_APP_PROPERTIES + "janusgraph-realtime.properties";
public static final String CACHED_DB_CONFIG = AAI_HOME_ETC_APP_PROPERTIES + "janusgraph-cached.properties";
public static final String AAI_HOME_ETC_OXM = AAI_HOME_ETC + "oxm" + AAI_FILESEP;
- public static final String AAI_EVENT_DMAAP_PROPS = AAI_HOME_ETC_APP_PROPERTIES + "aaiEventDMaaPPublisher.properties";
+ public static final String AAI_EVENT_DMAAP_PROPS =
+ AAI_HOME_ETC_APP_PROPERTIES + "aaiEventDMaaPPublisher.properties";
public static final String AAI_HOME_ETC_SCRIPT = AAI_HOME_ETC + AAI_FILESEP + "scriptdata" + AAI_FILESEP;
public static final String AAI_LOGBACK_PROPS = "logback.xml";
@@ -100,7 +108,6 @@ public final class AAIConstants {
public static final String AAI_RESVERSION_DISABLED_UUID = "aai.resourceversion.disabled.uuid";
public static final String AAI_RESVERSION_DISABLED_UUID_DEFAULT = "38cf3090-6a0c-4e9d-8142-4332a7352846";
-
public static final long HISTORY_MAX_HOURS = 192;
public static final String LOGGING_MAX_STACK_TRACE_ENTRIES = "aai.logging.maxStackTraceEntries";
@@ -111,6 +118,7 @@ public final class AAIConstants {
/** Micro-service Names */
public static final String AAI_TRAVERSAL_MS = "aai-traversal";
public static final String AAI_RESOURCES_MS = "aai-resources";
+
/**
* Instantiates a new AAI constants.
*/
diff --git a/aai-core/src/main/java/org/onap/aai/util/AAISystemExitUtil.java b/aai-core/src/main/java/org/onap/aai/util/AAISystemExitUtil.java
index 1d275784..ff5ee63e 100644
--- a/aai-core/src/main/java/org/onap/aai/util/AAISystemExitUtil.java
+++ b/aai-core/src/main/java/org/onap/aai/util/AAISystemExitUtil.java
@@ -17,20 +17,21 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.util;
import org.onap.aai.dbmap.AAIGraph;
public class AAISystemExitUtil {
- public static void systemExitCloseAAIGraph(int code) {
- if ("true".equals(System.getProperty("org.onap.aai.graphadmin.started"))) {
- return;
- }
- if (AAIGraph.isInit()) {
- AAIGraph.getInstance().graphShutdown();
- }
- System.exit(code);
+ public static void systemExitCloseAAIGraph(int code) {
+ if ("true".equals(System.getProperty("org.onap.aai.graphadmin.started"))) {
+ return;
+ }
+ if (AAIGraph.isInit()) {
+ AAIGraph.getInstance().graphShutdown();
+ }
+ System.exit(code);
- }
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/util/AAIUtils.java b/aai-core/src/main/java/org/onap/aai/util/AAIUtils.java
index ba2cf9e2..390e6d9c 100644
--- a/aai-core/src/main/java/org/onap/aai/util/AAIUtils.java
+++ b/aai-core/src/main/java/org/onap/aai/util/AAIUtils.java
@@ -19,6 +19,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.util;
import java.text.DateFormat;
@@ -28,7 +29,7 @@ import java.util.Date;
import java.util.TimeZone;
public class AAIUtils {
-
+
/**
* Instantiates AAIUtils.
*/
@@ -57,5 +58,5 @@ public class AAIUtils {
DateFormat formatter = new SimpleDateFormat("YYMMdd-HH:mm:ss:SSS");
formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
return formatter.format(date);
- }
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/util/Entity.java b/aai-core/src/main/java/org/onap/aai/util/Entity.java
index ebb066b9..d1a3eafc 100644
--- a/aai-core/src/main/java/org/onap/aai/util/Entity.java
+++ b/aai-core/src/main/java/org/onap/aai/util/Entity.java
@@ -17,31 +17,30 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.util;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.annotation.Generated;
+
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
@JsonInclude(JsonInclude.Include.NON_NULL)
@Generated("org.jsonschema2pojo")
-@JsonPropertyOrder({
- "equipment-role",
- "action",
- "key-value-list",
- "self-link"
-})
+@JsonPropertyOrder({"equipment-role", "action", "key-value-list", "self-link"})
public class Entity {
@JsonProperty("equipment-role")
@@ -58,7 +57,7 @@ public class Entity {
/**
*
* @return
- * The equipmentRole
+ * The equipmentRole
*/
@JsonProperty("equipment-role")
public String getEquipmentRole() {
@@ -68,7 +67,7 @@ public class Entity {
/**
*
* @param equipmentRole
- * The equipment-role
+ * The equipment-role
*/
@JsonProperty("equipment-role")
public void setEquipmentRole(String equipmentRole) {
@@ -83,7 +82,7 @@ public class Entity {
/**
*
* @return
- * The action
+ * The action
*/
@JsonProperty("action")
public String getAction() {
@@ -93,7 +92,7 @@ public class Entity {
/**
*
* @param action
- * The action
+ * The action
*/
@JsonProperty("action")
public void setAction(String action) {
@@ -108,7 +107,7 @@ public class Entity {
/**
*
* @return
- * The keyValueList
+ * The keyValueList
*/
@JsonProperty("key-value-list")
public List<KeyValueList> getKeyValueList() {
@@ -118,7 +117,7 @@ public class Entity {
/**
*
* @param keyValueList
- * The key-value-list
+ * The key-value-list
*/
@JsonProperty("key-value-list")
public void setKeyValueList(List<KeyValueList> keyValueList) {
@@ -133,7 +132,7 @@ public class Entity {
/**
*
* @return
- * The selfLink
+ * The selfLink
*/
@JsonProperty("self-link")
public String getSelfLink() {
@@ -143,7 +142,7 @@ public class Entity {
/**
*
* @param selfLink
- * The self-link
+ * The self-link
*/
@JsonProperty("self-link")
public void setSelfLink(String selfLink) {
@@ -177,7 +176,8 @@ public class Entity {
@Override
public int hashCode() {
- return new HashCodeBuilder().append(equipmentRole).append(action).append(keyValueList).append(selfLink).append(additionalProperties).toHashCode();
+ return new HashCodeBuilder().append(equipmentRole).append(action).append(keyValueList).append(selfLink)
+ .append(additionalProperties).toHashCode();
}
@Override
@@ -189,7 +189,9 @@ public class Entity {
return false;
}
Entity rhs = ((Entity) other);
- return new EqualsBuilder().append(equipmentRole, rhs.equipmentRole).append(action, rhs.action).append(keyValueList, rhs.keyValueList).append(selfLink, rhs.selfLink).append(additionalProperties, rhs.additionalProperties).isEquals();
+ return new EqualsBuilder().append(equipmentRole, rhs.equipmentRole).append(action, rhs.action)
+ .append(keyValueList, rhs.keyValueList).append(selfLink, rhs.selfLink)
+ .append(additionalProperties, rhs.additionalProperties).isEquals();
}
}
diff --git a/aai-core/src/main/java/org/onap/aai/util/EntityList.java b/aai-core/src/main/java/org/onap/aai/util/EntityList.java
index 0b600418..e86c5472 100644
--- a/aai-core/src/main/java/org/onap/aai/util/EntityList.java
+++ b/aai-core/src/main/java/org/onap/aai/util/EntityList.java
@@ -17,28 +17,30 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.util;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.annotation.Generated;
+
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
@JsonInclude(JsonInclude.Include.NON_NULL)
@Generated("org.jsonschema2pojo")
-@JsonPropertyOrder({
- "entity"
-})
+@JsonPropertyOrder({"entity"})
public class EntityList {
@JsonProperty("entity")
@@ -49,7 +51,7 @@ public class EntityList {
/**
*
* @return
- * The entity
+ * The entity
*/
@JsonProperty("entity")
public List<Entity> getEntity() {
@@ -59,7 +61,7 @@ public class EntityList {
/**
*
* @param entity
- * The entity
+ * The entity
*/
@JsonProperty("entity")
public void setEntity(List<Entity> entity) {
@@ -105,7 +107,8 @@ public class EntityList {
return false;
}
EntityList rhs = ((EntityList) other);
- return new EqualsBuilder().append(entity, rhs.entity).append(additionalProperties, rhs.additionalProperties).isEquals();
+ return new EqualsBuilder().append(entity, rhs.entity).append(additionalProperties, rhs.additionalProperties)
+ .isEquals();
}
}
diff --git a/aai-core/src/main/java/org/onap/aai/util/FileWatcher.java b/aai-core/src/main/java/org/onap/aai/util/FileWatcher.java
index cb8074de..07ac2642 100644
--- a/aai-core/src/main/java/org/onap/aai/util/FileWatcher.java
+++ b/aai-core/src/main/java/org/onap/aai/util/FileWatcher.java
@@ -17,42 +17,44 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.util;
-import java.util.*;
import java.io.*;
+import java.util.*;
public abstract class FileWatcher extends TimerTask {
- private long timeStamp;
- private File file;
+ private long timeStamp;
+ private File file;
- /**
- * Instantiates a new file watcher.
- *
- * @param file the file
- */
- public FileWatcher( File file ) {
- this.file = file;
- this.timeStamp = file.lastModified();
- }
+ /**
+ * Instantiates a new file watcher.
+ *
+ * @param file the file
+ */
+ public FileWatcher(File file) {
+ this.file = file;
+ this.timeStamp = file.lastModified();
+ }
- /**
- * runs a timer task
- * @see TimerTask.run
- */
- public final void run() {
- long timeStamp = file.lastModified();
+ /**
+ * runs a timer task
+ *
+ * @see TimerTask.run
+ */
+ public final void run() {
+ long timeStamp = file.lastModified();
- if( (timeStamp - this.timeStamp) > 500 ) {
- this.timeStamp = timeStamp;
- onChange(file);
+ if ((timeStamp - this.timeStamp) > 500) {
+ this.timeStamp = timeStamp;
+ onChange(file);
+ }
}
- }
-
- /**
- * On change.
- *
- * @param file the file
- */
- protected abstract void onChange( File file );
+
+ /**
+ * On change.
+ *
+ * @param file the file
+ */
+ protected abstract void onChange(File file);
}
diff --git a/aai-core/src/main/java/org/onap/aai/util/FormatDate.java b/aai-core/src/main/java/org/onap/aai/util/FormatDate.java
index 77e39f77..9ee2b71d 100644
--- a/aai-core/src/main/java/org/onap/aai/util/FormatDate.java
+++ b/aai-core/src/main/java/org/onap/aai/util/FormatDate.java
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.util;
import java.time.ZoneId;
@@ -25,21 +26,22 @@ import java.time.format.DateTimeFormatter;
public class FormatDate {
- private final String timeZone;
- private final String pattern;
- public FormatDate(String pattern) {
- this.pattern = pattern;
- this.timeZone = "GMT";
- }
- public FormatDate(String pattern, String timeZone) {
- this.pattern = pattern;
- this.timeZone = timeZone;
- }
-
- public String getDateTime() {
-
- final DateTimeFormatter formatter =
- DateTimeFormatter.ofPattern(pattern);
- return formatter.format(ZonedDateTime.now(ZoneId.of(timeZone)));
- }
+ private final String timeZone;
+ private final String pattern;
+
+ public FormatDate(String pattern) {
+ this.pattern = pattern;
+ this.timeZone = "GMT";
+ }
+
+ public FormatDate(String pattern, String timeZone) {
+ this.pattern = pattern;
+ this.timeZone = timeZone;
+ }
+
+ public String getDateTime() {
+
+ final DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
+ return formatter.format(ZonedDateTime.now(ZoneId.of(timeZone)));
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/util/HbaseSaltPrefixer.java b/aai-core/src/main/java/org/onap/aai/util/HbaseSaltPrefixer.java
index b687ee41..fef10a77 100644
--- a/aai-core/src/main/java/org/onap/aai/util/HbaseSaltPrefixer.java
+++ b/aai-core/src/main/java/org/onap/aai/util/HbaseSaltPrefixer.java
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.util;
/*
@@ -26,34 +27,35 @@ package org.onap.aai.util;
* as these keys are generated in a couple places, I made a class to contain that logic
*/
public class HbaseSaltPrefixer {
- private int NUM_REGION_BUCKETS = 3; //the number of hbase region servers per cluster
+ private int NUM_REGION_BUCKETS = 3; // the number of hbase region servers per cluster
+
+ private static class SingletonHolder {
+ private static final HbaseSaltPrefixer INSTANCE = new HbaseSaltPrefixer();
+ }
+
+ /**
+ * Instantiates a new hbase salt prefixer.
+ */
+ private HbaseSaltPrefixer() {
+ }
+
+ /**
+ * Gets the single instance of HbaseSaltPrefixer.
+ *
+ * @return single instance of HbaseSaltPrefixer
+ */
+ public static HbaseSaltPrefixer getInstance() {
+ return SingletonHolder.INSTANCE;
+ }
- private static class SingletonHolder{
- private static final HbaseSaltPrefixer INSTANCE = new HbaseSaltPrefixer();
- }
-
- /**
- * Instantiates a new hbase salt prefixer.
- */
- private HbaseSaltPrefixer(){}
-
- /**
- * Gets the single instance of HbaseSaltPrefixer.
- *
- * @return single instance of HbaseSaltPrefixer
- */
- public static HbaseSaltPrefixer getInstance() {
- return SingletonHolder.INSTANCE;
- }
-
- /**
- * Prepend salt.
- *
- * @param key the key
- * @return the string
- */
- public String prependSalt(String key) {
- int salt = Math.abs(key.hashCode()) % NUM_REGION_BUCKETS;
- return salt + "-" + key;
- }
+ /**
+ * Prepend salt.
+ *
+ * @param key the key
+ * @return the string
+ */
+ public String prependSalt(String key) {
+ int salt = Math.abs(key.hashCode()) % NUM_REGION_BUCKETS;
+ return salt + "-" + key;
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/util/HttpsAuthClient.java b/aai-core/src/main/java/org/onap/aai/util/HttpsAuthClient.java
index f092eac2..133c26a7 100644
--- a/aai-core/src/main/java/org/onap/aai/util/HttpsAuthClient.java
+++ b/aai-core/src/main/java/org/onap/aai/util/HttpsAuthClient.java
@@ -17,8 +17,17 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.util;
+import com.sun.jersey.api.client.Client;
+import com.sun.jersey.api.client.ClientResponse;
+import com.sun.jersey.api.client.config.ClientConfig;
+import com.sun.jersey.api.client.config.DefaultClientConfig;
+import com.sun.jersey.api.client.filter.LoggingFilter;
+import com.sun.jersey.api.json.JSONConfiguration;
+import com.sun.jersey.client.urlconnection.HTTPSProperties;
+
import java.io.FileInputStream;
import java.security.KeyManagementException;
import java.security.KeyStore;
@@ -29,106 +38,94 @@ import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
-import com.sun.jersey.api.client.Client;
-import com.sun.jersey.api.client.ClientResponse;
-import com.sun.jersey.api.client.config.ClientConfig;
-import com.sun.jersey.api.client.config.DefaultClientConfig;
-import com.sun.jersey.api.client.filter.LoggingFilter;
-import com.sun.jersey.api.json.JSONConfiguration;
-import com.sun.jersey.client.urlconnection.HTTPSProperties;
+public class HttpsAuthClient {
+
+ /**
+ * The main method.
+ *
+ * @param args the arguments
+ */
+ public static void main(String[] args) {
+ try {
+ String url = AAIConfig.get(AAIConstants.AAI_SERVER_URL) + "business/customers";
+ System.out.println("Making Jersey https call...");
+ Client client = HttpsAuthClient.getClient();
+
+ ClientResponse res = client.resource(url).accept("application/json").header("X-TransactionId", "PROV001")
+ .header("X-FromAppId", "AAI").type("application/json").get(ClientResponse.class);
+
+ // System.out.println("Jersey result: ");
+ // System.out.println(res.getEntity(String.class).toString());
+
+ } catch (KeyManagementException e) {
+ e.printStackTrace();
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ /**
+ * Gets the client.
+ *
+ * @return the client
+ * @throws KeyManagementException the key management exception
+ */
+ public static Client getClient() throws KeyManagementException {
+
+ ClientConfig config = new DefaultClientConfig();
+ config.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
+ config.getClasses().add(org.onap.aai.restcore.CustomJacksonJaxBJsonProvider.class);
+
+ SSLContext ctx = null;
+ try {
+ String truststore_path =
+ AAIConstants.AAI_HOME_ETC_AUTH + AAIConfig.get(AAIConstants.AAI_TRUSTSTORE_FILENAME);
+ String truststore_password = AAIConfig.get(AAIConstants.AAI_TRUSTSTORE_PASSWD);
+ String keystore_path = AAIConstants.AAI_HOME_ETC_AUTH + AAIConfig.get(AAIConstants.AAI_KEYSTORE_FILENAME);
+ String keystore_password = AAIConfig.get(AAIConstants.AAI_KEYSTORE_PASSWD);
+
+ System.setProperty("javax.net.ssl.trustStore", truststore_path);
+ System.setProperty("javax.net.ssl.trustStorePassword", truststore_password);
+ HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
+ public boolean verify(String string, SSLSession ssls) {
+ return true;
+ }
+ });
+
+ ctx = SSLContext.getInstance("TLSv1.2");
+ KeyManagerFactory kmf = null;
+ try {
+ kmf = KeyManagerFactory.getInstance("SunX509");
+ FileInputStream fin = new FileInputStream(keystore_path);
+ KeyStore ks = KeyStore.getInstance("PKCS12");
+ char[] pwd = keystore_password.toCharArray();
+ ks.load(fin, pwd);
+ kmf.init(ks, pwd);
+ } catch (Exception e) {
+ System.out.println("Error setting up kmf: exiting");
+ e.printStackTrace();
+ System.exit(1);
+ }
+
+ ctx.init(kmf.getKeyManagers(), null, null);
+ config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
+ new HTTPSProperties(new HostnameVerifier() {
+ @Override
+ public boolean verify(String s, SSLSession sslSession) {
+ return true;
+ }
+ }, ctx));
+ } catch (Exception e) {
+ System.out.println("Error setting up config: exiting");
+ e.printStackTrace();
+ System.exit(1);
+ }
+
+ Client client = Client.create(config);
+ // uncomment this line to get more logging for the request/response
+ // client.addFilter(new LoggingFilter(System.out));
+
+ return client;
+ }
-public class HttpsAuthClient{
-
- /**
- * The main method.
- *
- * @param args the arguments
- */
- public static void main(String[] args) {
- try {
- String url = AAIConfig.get(AAIConstants.AAI_SERVER_URL) + "business/customers";
- System.out.println("Making Jersey https call...");
- Client client = HttpsAuthClient.getClient();
-
- ClientResponse res = client.resource(url)
- .accept("application/json")
- .header("X-TransactionId", "PROV001")
- .header("X-FromAppId", "AAI")
- .type("application/json")
- .get(ClientResponse.class);
-
-// System.out.println("Jersey result: ");
-// System.out.println(res.getEntity(String.class).toString());
-
- } catch (KeyManagementException e) {
- e.printStackTrace();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
-
- /**
- * Gets the client.
- *
- * @return the client
- * @throws KeyManagementException the key management exception
- */
- public static Client getClient() throws KeyManagementException {
-
- ClientConfig config = new DefaultClientConfig();
- config.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
- config.getClasses().add(org.onap.aai.restcore.CustomJacksonJaxBJsonProvider.class);
-
- SSLContext ctx = null;
- try {
- String truststore_path = AAIConstants.AAI_HOME_ETC_AUTH + AAIConfig.get(AAIConstants.AAI_TRUSTSTORE_FILENAME);
- String truststore_password = AAIConfig.get(AAIConstants.AAI_TRUSTSTORE_PASSWD);
- String keystore_path = AAIConstants.AAI_HOME_ETC_AUTH + AAIConfig.get(AAIConstants.AAI_KEYSTORE_FILENAME);
- String keystore_password = AAIConfig.get(AAIConstants.AAI_KEYSTORE_PASSWD);
-
- System.setProperty("javax.net.ssl.trustStore", truststore_path);
- System.setProperty("javax.net.ssl.trustStorePassword", truststore_password);
- HttpsURLConnection.setDefaultHostnameVerifier( new HostnameVerifier(){
- public boolean verify(String string,SSLSession ssls) {
- return true;
- }
- });
-
- ctx = SSLContext.getInstance("TLSv1.2");
- KeyManagerFactory kmf = null;
- try {
- kmf = KeyManagerFactory.getInstance("SunX509");
- FileInputStream fin = new FileInputStream(keystore_path);
- KeyStore ks = KeyStore.getInstance("PKCS12");
- char[] pwd = keystore_password.toCharArray();
- ks.load(fin, pwd);
- kmf.init(ks, pwd);
- } catch (Exception e) {
- System.out.println("Error setting up kmf: exiting");
- e.printStackTrace();
- System.exit(1);
- }
-
- ctx.init(kmf.getKeyManagers(), null, null);
- config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
- new HTTPSProperties( new HostnameVerifier() {
- @Override
- public boolean verify( String s, SSLSession sslSession ) {
- return true;
- }
- }, ctx));
- } catch (Exception e) {
- System.out.println("Error setting up config: exiting");
- e.printStackTrace();
- System.exit(1);
- }
-
- Client client = Client.create(config);
- // uncomment this line to get more logging for the request/response
- // client.addFilter(new LoggingFilter(System.out));
-
- return client;
- }
-
-}
+}
diff --git a/aai-core/src/main/java/org/onap/aai/util/HttpsAuthExternalClient.java b/aai-core/src/main/java/org/onap/aai/util/HttpsAuthExternalClient.java
index 4e673b6a..53e2d958 100644
--- a/aai-core/src/main/java/org/onap/aai/util/HttpsAuthExternalClient.java
+++ b/aai-core/src/main/java/org/onap/aai/util/HttpsAuthExternalClient.java
@@ -17,94 +17,94 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.util;
+import com.sun.jersey.api.client.Client;
+import com.sun.jersey.api.client.config.ClientConfig;
+import com.sun.jersey.api.client.config.DefaultClientConfig;
+import com.sun.jersey.api.json.JSONConfiguration;
+import com.sun.jersey.client.urlconnection.HTTPSProperties;
+
import java.io.FileInputStream;
import java.security.KeyStore;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManagerFactory;
-import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
-
-import com.sun.jersey.api.client.Client;
-import com.sun.jersey.api.client.config.ClientConfig;
-import com.sun.jersey.api.client.config.DefaultClientConfig;
-import com.sun.jersey.api.json.JSONConfiguration;
-import com.sun.jersey.client.urlconnection.HTTPSProperties;
+import javax.net.ssl.TrustManagerFactory;
public class HttpsAuthExternalClient {
+ /**
+ * Gets the client.
+ *
+ * @param keystoreFileName the keystore file name
+ * @param keystorePassword the keystore password
+ * @return the client
+ * @throws Exception the exception
+ */
+ public static Client getClient(String keystoreFileName, String keystorePassword) throws Exception {
+
+ ClientConfig config = new DefaultClientConfig();
+ config.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
+ config.getClasses().add(org.onap.aai.restcore.CustomJacksonJaxBJsonProvider.class);
+ Client client = null;
+ SSLContext ctx = null;
+ String truststore_path = AAIConstants.AAI_HOME_ETC_AUTH + AAIConfig.get(AAIConstants.AAI_TRUSTSTORE_FILENAME);
+ try (FileInputStream tin = new FileInputStream(truststore_path)) {
+ String truststore_password = AAIConfig.get(AAIConstants.AAI_TRUSTSTORE_PASSWD);
+ String keystore_path = AAIConstants.AAI_HOME_ETC_AUTH + keystoreFileName;
+ String keystore_password = keystorePassword;
+ // System.setProperty("javax.net.ssl.trustStore", truststore_path);
+ // System.setProperty("javax.net.ssl.trustStorePassword", truststore_password);
+ HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
+ public boolean verify(String string, SSLSession ssls) {
+ return true;
+ }
+ });
+
+ ctx = SSLContext.getInstance("TLS");
+ KeyManagerFactory kmf = null;
+
+ /****
+ * kmf = KeyManagerFactory.getInstance("SunX509");
+ * FileInputStream fin = new FileInputStream(keystore_path);
+ * KeyStore ks = KeyStore.getInstance("PKCS12");
+ * char[] pwd = keystore_password.toCharArray();
+ * ks.load(fin, pwd);
+ * kmf.init(ks, pwd);
+ ***/
+
+ String alg = TrustManagerFactory.getDefaultAlgorithm();
+ TrustManagerFactory tmf = TrustManagerFactory.getInstance(alg);
+
+ KeyStore ts = KeyStore.getInstance("PKCS12");
+ char[] tpwd = truststore_password.toCharArray();
+ ts.load(tin, tpwd);
+ tmf.init(ts);
+
+ // ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
+ // Updating key manager to null, to disable two way SSL
+ ctx.init(null, tmf.getTrustManagers(), null);
- /**
- * Gets the client.
- *
- * @param keystoreFileName the keystore file name
- * @param keystorePassword the keystore password
- * @return the client
- * @throws Exception the exception
- */
- public static Client getClient ( String keystoreFileName, String keystorePassword ) throws Exception {
-
- ClientConfig config = new DefaultClientConfig();
- config.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
- config.getClasses().add(org.onap.aai.restcore.CustomJacksonJaxBJsonProvider.class);
- Client client = null;
- SSLContext ctx = null;
- String truststore_path = AAIConstants.AAI_HOME_ETC_AUTH + AAIConfig.get(AAIConstants.AAI_TRUSTSTORE_FILENAME);
- try(FileInputStream tin = new FileInputStream(truststore_path)) {
- String truststore_password = AAIConfig.get(AAIConstants.AAI_TRUSTSTORE_PASSWD);
- String keystore_path = AAIConstants.AAI_HOME_ETC_AUTH + keystoreFileName;
- String keystore_password = keystorePassword;
- //System.setProperty("javax.net.ssl.trustStore", truststore_path);
- //System.setProperty("javax.net.ssl.trustStorePassword", truststore_password);
- HttpsURLConnection.setDefaultHostnameVerifier( new HostnameVerifier(){
- public boolean verify(String string,SSLSession ssls) {
- return true;
- }
- });
-
- ctx = SSLContext.getInstance("TLS");
- KeyManagerFactory kmf = null;
+ config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
+ new HTTPSProperties(new HostnameVerifier() {
+ @Override
+ public boolean verify(String s, SSLSession sslSession) {
+ return true;
+ }
+ }, ctx));
-
- /**** kmf = KeyManagerFactory.getInstance("SunX509");
- FileInputStream fin = new FileInputStream(keystore_path);
- KeyStore ks = KeyStore.getInstance("PKCS12");
- char[] pwd = keystore_password.toCharArray();
- ks.load(fin, pwd);
- kmf.init(ks, pwd);
- ***/
-
- String alg = TrustManagerFactory.getDefaultAlgorithm();
- TrustManagerFactory tmf = TrustManagerFactory.getInstance(alg);
+ client = Client.create(config);
+ // uncomment this line to get more logging for the request/response
+ // client.addFilter(new LoggingFilter(System.out));
+ } catch (Exception e) {
+ throw e;
+ }
+ return client;
+ }
- KeyStore ts = KeyStore.getInstance("PKCS12");
- char[] tpwd = truststore_password.toCharArray();
- ts.load(tin, tpwd);
- tmf.init(ts);
-
- //ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
- // Updating key manager to null, to disable two way SSL
- ctx.init(null, tmf.getTrustManagers(), null);
-
- config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
- new HTTPSProperties( new HostnameVerifier() {
- @Override
- public boolean verify( String s, SSLSession sslSession ) {
- return true;
- }
- }, ctx));
-
- client = Client.create(config);
- // uncomment this line to get more logging for the request/response
- // client.addFilter(new LoggingFilter(System.out));
- } catch (Exception e) {
- throw e;
- }
- return client;
- }
-
-}
+}
diff --git a/aai-core/src/main/java/org/onap/aai/util/JettyObfuscationConversionCommandLineUtil.java b/aai-core/src/main/java/org/onap/aai/util/JettyObfuscationConversionCommandLineUtil.java
index e8bd8af6..463a668b 100644
--- a/aai-core/src/main/java/org/onap/aai/util/JettyObfuscationConversionCommandLineUtil.java
+++ b/aai-core/src/main/java/org/onap/aai/util/JettyObfuscationConversionCommandLineUtil.java
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.util;
import org.apache.commons.cli.CommandLine;
@@ -48,49 +49,49 @@ import org.eclipse.jetty.util.security.Password;
*/
public class JettyObfuscationConversionCommandLineUtil {
- /**
- * The main method.
- *
- * @param args the arguments
- */
- public static void main(String[] args){
- Options options = new Options();
- options.addOption("e", true, "obfuscate the given string");
- options.addOption("d", true, "deobfuscate the given string");
+ /**
+ * The main method.
+ *
+ * @param args the arguments
+ */
+ public static void main(String[] args) {
+ Options options = new Options();
+ options.addOption("e", true, "obfuscate the given string");
+ options.addOption("d", true, "deobfuscate the given string");
- CommandLineParser parser = new DefaultParser();
+ CommandLineParser parser = new DefaultParser();
- try {
- CommandLine cmd = parser.parse(options, args);
- String toProcess = null;
+ try {
+ CommandLine cmd = parser.parse(options, args);
+ String toProcess = null;
- if (cmd.hasOption("e")){
- toProcess = cmd.getOptionValue("e");
- String encoded = Password.obfuscate(toProcess);
- System.out.println(encoded);
- } else if (cmd.hasOption("d")) {
- toProcess = cmd.getOptionValue("d");
- String decoded_str = Password.deobfuscate(toProcess);
- System.out.println(decoded_str);
- } else {
- usage();
- }
- } catch (ParseException e) {
- System.out.println("failed to parse input");
- System.out.println(e.toString());
- usage();
- } catch (Exception e) {
- System.out.println("exception:" + e.toString());
- }
- }
+ if (cmd.hasOption("e")) {
+ toProcess = cmd.getOptionValue("e");
+ String encoded = Password.obfuscate(toProcess);
+ System.out.println(encoded);
+ } else if (cmd.hasOption("d")) {
+ toProcess = cmd.getOptionValue("d");
+ String decoded_str = Password.deobfuscate(toProcess);
+ System.out.println(decoded_str);
+ } else {
+ usage();
+ }
+ } catch (ParseException e) {
+ System.out.println("failed to parse input");
+ System.out.println(e.toString());
+ usage();
+ } catch (Exception e) {
+ System.out.println("exception:" + e.toString());
+ }
+ }
- /**
- * Usage.
- */
- private static void usage(){
- System.out.println("usage:");;
- System.out.println("-e [string] to obfuscate");
- System.out.println("-d [string] to deobfuscate");
- System.out.println("-h help");
- }
+ /**
+ * Usage.
+ */
+ private static void usage() {
+ System.out.println("usage:");;
+ System.out.println("-e [string] to obfuscate");
+ System.out.println("-d [string] to deobfuscate");
+ System.out.println("-h help");
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/util/KeyValueList.java b/aai-core/src/main/java/org/onap/aai/util/KeyValueList.java
index cf0929db..1536d772 100644
--- a/aai-core/src/main/java/org/onap/aai/util/KeyValueList.java
+++ b/aai-core/src/main/java/org/onap/aai/util/KeyValueList.java
@@ -17,27 +17,28 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.util;
-import java.util.HashMap;
-import java.util.Map;
-import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.annotation.Generated;
+
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
@JsonInclude(JsonInclude.Include.NON_NULL)
@Generated("org.jsonschema2pojo")
-@JsonPropertyOrder({
- "key",
- "value"
-})
+@JsonPropertyOrder({"key", "value"})
public class KeyValueList {
@JsonProperty("key")
@@ -50,7 +51,7 @@ public class KeyValueList {
/**
*
* @return
- * The key
+ * The key
*/
@JsonProperty("key")
public String getKey() {
@@ -60,7 +61,7 @@ public class KeyValueList {
/**
*
* @param key
- * The key
+ * The key
*/
@JsonProperty("key")
public void setKey(String key) {
@@ -75,7 +76,7 @@ public class KeyValueList {
/**
*
* @return
- * The value
+ * The value
*/
@JsonProperty("value")
public String getValue() {
@@ -85,7 +86,7 @@ public class KeyValueList {
/**
*
* @param value
- * The value
+ * The value
*/
@JsonProperty("value")
public void setValue(String value) {
@@ -131,7 +132,8 @@ public class KeyValueList {
return false;
}
KeyValueList rhs = ((KeyValueList) other);
- return new EqualsBuilder().append(key, rhs.key).append(value, rhs.value).append(additionalProperties, rhs.additionalProperties).isEquals();
+ return new EqualsBuilder().append(key, rhs.key).append(value, rhs.value)
+ .append(additionalProperties, rhs.additionalProperties).isEquals();
}
}
diff --git a/aai-core/src/main/java/org/onap/aai/util/MapperUtil.java b/aai-core/src/main/java/org/onap/aai/util/MapperUtil.java
index 4fed0666..47a937d4 100644
--- a/aai-core/src/main/java/org/onap/aai/util/MapperUtil.java
+++ b/aai-core/src/main/java/org/onap/aai/util/MapperUtil.java
@@ -19,13 +19,15 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.util;
-import org.onap.aai.exceptions.AAIException;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule;
+import org.onap.aai.exceptions.AAIException;
+
public class MapperUtil {
/**
@@ -34,7 +36,7 @@ public class MapperUtil {
private MapperUtil() {
// prevent instantiation
}
-
+
/**
* Read as object of.
*
diff --git a/aai-core/src/main/java/org/onap/aai/util/PojoUtils.java b/aai-core/src/main/java/org/onap/aai/util/PojoUtils.java
index f3e67388..218f0dd8 100644
--- a/aai-core/src/main/java/org/onap/aai/util/PojoUtils.java
+++ b/aai-core/src/main/java/org/onap/aai/util/PojoUtils.java
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.util;
import com.fasterxml.jackson.annotation.JsonInclude;
@@ -28,16 +29,7 @@ import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule;
import com.google.common.base.CaseFormat;
import com.google.common.collect.Multimap;
-import org.apache.commons.io.output.ByteArrayOutputStream;
-import org.eclipse.persistence.dynamic.DynamicEntity;
-import org.eclipse.persistence.jaxb.JAXBMarshaller;
-import org.eclipse.persistence.jaxb.MarshallerProperties;
-import org.onap.aai.domain.model.AAIResource;
-import org.onap.aai.exceptions.AAIException;
-import javax.xml.bind.JAXBContext;
-import javax.xml.bind.JAXBException;
-import javax.xml.bind.Marshaller;
import java.io.IOException;
import java.io.StringWriter;
import java.lang.reflect.InvocationTargetException;
@@ -45,305 +37,323 @@ import java.lang.reflect.Method;
import java.security.SecureRandom;
import java.util.*;
+import javax.xml.bind.JAXBContext;
+import javax.xml.bind.JAXBException;
+import javax.xml.bind.Marshaller;
+
+import org.apache.commons.io.output.ByteArrayOutputStream;
+import org.eclipse.persistence.dynamic.DynamicEntity;
+import org.eclipse.persistence.jaxb.JAXBMarshaller;
+import org.eclipse.persistence.jaxb.MarshallerProperties;
+import org.onap.aai.domain.model.AAIResource;
+import org.onap.aai.exceptions.AAIException;
+
public class PojoUtils {
- /**
- * Gets the key value list.
- *
- * @param <T> the generic type
- * @param e the e
- * @param clazz the clazz
- * @return the key value list
- * @throws IllegalAccessException the illegal access exception
- * @throws IllegalArgumentException the illegal argument exception
- * @throws InvocationTargetException the invocation target exception
- */
- public <T> List<KeyValueList> getKeyValueList(Entity e, T clazz) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
- List<KeyValueList> kvList = e.getKeyValueList();
- Object value = null;
- Method[] methods = clazz.getClass().getDeclaredMethods();
- String propertyName = "";
-
- for (Method method : methods) {
- if (method.getName().startsWith("get")) {
- propertyName = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN,method.getName().substring(3));
- if (!(method.getReturnType().getName().contains("aai")) || method.getReturnType().getName().contains("java.util.List")) {
- value = method.invoke(clazz);
- KeyValueList kv = new KeyValueList();
- kv.setKey(propertyName);
- if (value != null) {
- kv.setValue(value.toString());
- } else {
- kv.setValue("");
- }
- kvList.add(kv);
- }
- }
- }
- return kvList;
- }
-
- /**
- * Gets the json from object.
- *
- * @param <T> the generic type
- * @param clazz the clazz
- * @return the json from object
- * @throws JsonGenerationException the json generation exception
- * @throws JsonMappingException the json mapping exception
- * @throws IOException Signals that an I/O exception has occurred.
- */
- public <T> String getJsonFromObject(T clazz) throws JsonGenerationException, JsonMappingException, IOException {
- return getJsonFromObject(clazz, false, true);
- }
-
- /**
- * Gets the json from object.
- *
- * @param <T> the generic type
- * @param clazz the clazz
- * @param wrapRoot the wrap root
- * @param indent the indent
- * @return the json from object
- * @throws JsonGenerationException the json generation exception
- * @throws JsonMappingException the json mapping exception
- * @throws IOException Signals that an I/O exception has occurred.
- */
- public <T> String getJsonFromObject(T clazz, boolean wrapRoot, boolean indent) throws JsonGenerationException, JsonMappingException, IOException {
- ObjectMapper mapper = new ObjectMapper();
-
- mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
-
- mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
- mapper.configure(SerializationFeature.INDENT_OUTPUT, indent);
- mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, wrapRoot);
-
- mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, wrapRoot);
-
- mapper.registerModule(new JaxbAnnotationModule());
-
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
-
- mapper.writeValue(baos, clazz);
-
- return baos.toString();
- }
-
- /**
- * Gets the json from dynamic object.
- *
- * @param ent the ent
- * @param jaxbContext the jaxb context
- * @param includeRoot the include root
- * @return the json from dynamic object
- * @throws JsonGenerationException the json generation exception
- * @throws JsonMappingException the json mapping exception
- * @throws IOException Signals that an I/O exception has occurred.
- * @throws JAXBException the JAXB exception
- */
- public String getJsonFromDynamicObject(DynamicEntity ent, org.eclipse.persistence.jaxb.JAXBContext jaxbContext, boolean includeRoot) throws JsonGenerationException, JsonMappingException, IOException, JAXBException {
- JAXBMarshaller marshaller = jaxbContext.createMarshaller();
-
- marshaller.setProperty(JAXBMarshaller.JAXB_FORMATTED_OUTPUT, false);
- marshaller.setProperty(MarshallerProperties.JSON_MARSHAL_EMPTY_COLLECTIONS, Boolean.FALSE) ;
- marshaller.setProperty("eclipselink.json.include-root", includeRoot);
- marshaller.setProperty("eclipselink.media-type", "application/json");
- StringWriter writer = new StringWriter();
- marshaller.marshal(ent, writer);
-
- return writer.toString();
- }
-
- /**
- * Gets the xml from object.
- *
- * @param <T> the generic type
- * @param clazz the clazz
- * @return the xml from object
- * @throws JAXBException the JAXB exception
- * @throws IOException
- */
- public <T> String getXmlFromObject(T clazz) throws JAXBException, IOException {
- try(ByteArrayOutputStream baos = new ByteArrayOutputStream()){
- JAXBContext jc = JAXBContext.newInstance(clazz.getClass().getPackage().getName());
-
- Marshaller marshaller = jc.createMarshaller();
- marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
- marshaller.marshal(clazz, baos);
- return baos.toString();
- }
- }
-
- /**
- * Gets the lookup key.
- *
- * @param baseKey the base key
- * @param lookupHash the lookup hash
- * @param keyProps the key props
- * @return the lookup key
- */
- public String getLookupKey (String baseKey, HashMap<String,Object> lookupHash, Collection<String> keyProps) {
- int baseKeyLen = baseKey.length();
- StringBuffer newKey = new StringBuffer();
- if (baseKeyLen > 0) {
- newKey.append(baseKey);
- }
-
- Iterator <String> keyPropI = keyProps.iterator();
- while( keyPropI.hasNext() ){
- String keyProp = keyPropI.next();
- if (baseKeyLen > 0) {
- newKey.append("&");
- }
- newKey.append(keyProp + "=" + lookupHash.get(keyProp));
- }
- return newKey.toString();
- }
-
- /**
- * Gets the lookup keys.
- *
- * @param lookupHashes the lookup hashes
- * @param _dbRulesNodeKeyProps the db rules node key props
- * @return the lookup keys
- */
- public String getLookupKeys (LinkedHashMap<String,HashMap<String,Object>> lookupHashes, Multimap<String, String> _dbRulesNodeKeyProps) {
- Iterator<String> it = lookupHashes.keySet().iterator();
- String lookupKeys = "";
- while (it.hasNext()) {
- String objectType = (String)it.next();
- HashMap<String,Object> lookupHash = lookupHashes.get(objectType);
-
- Collection<String> keyProps = _dbRulesNodeKeyProps.get(objectType);
- Iterator <String> keyPropI = keyProps.iterator();
- while( keyPropI.hasNext() ){
- lookupKeys += lookupHash.get(keyPropI.next());
- }
- }
- return lookupKeys;
- }
-
- /**
- * Gets the example object.
- *
- * @param <T> the generic type
- * @param clazz the clazz
- * @param singleton the singleton
- * @return the example object
- * @throws IllegalAccessException the illegal access exception
- * @throws IllegalArgumentException the illegal argument exception
- * @throws InvocationTargetException the invocation target exception
- * @throws NoSuchMethodException the no such method exception
- * @throws SecurityException the security exception
- * @throws AAIException the AAI exception
- */
- public <T> void getExampleObject(T clazz, boolean singleton) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, AAIException {
- Method[] methods = clazz.getClass().getDeclaredMethods();
- String dnHypPropertyName = "";
- String upCamPropertyName = "";
- Random rand = new SecureRandom();
- int randInt = rand.nextInt(10000000);
-
- for (Method method : methods) {
- boolean go = false;
- if (method.getName().startsWith("get")) {
- dnHypPropertyName = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN,method.getName().substring(3));
- upCamPropertyName = CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_CAMEL,method.getName().substring(3));
- go = true;
- } else if (method.getName().startsWith("is")) {
- dnHypPropertyName = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN,method.getName().substring(2));
- upCamPropertyName = CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_CAMEL,method.getName().substring(2));
- go = true;
- }
- // don't return resource-version on a singleton
- if (singleton && dnHypPropertyName.equals("resource-version")) {
- go = false;
- }
- if (go) {
- String retType = method.getReturnType().getName();
- if (!retType.contains("aai") && !retType.contains("java.util.List")) {
- // get the setter
- Method meth = clazz.getClass().getMethod("set" + upCamPropertyName, method.getReturnType());
-
- if (retType.contains("String")) {
- String val = "example-" + dnHypPropertyName + "-val-" + randInt;
- if (val != null) {
- meth.invoke(clazz, val);
- }
- } else if (retType.toLowerCase().contains("long")) {
- Integer foo = rand.nextInt(100000);
- meth.invoke(clazz, foo.longValue());
- } else if (retType.toLowerCase().contains("int")) {
- meth.invoke(clazz, rand.nextInt(100000));
- } else if (retType.toLowerCase().contains("short")) {
- Integer randShort = rand.nextInt(10000);
- meth.invoke(clazz, randShort.shortValue());
- } else if (retType.toLowerCase().contains("boolean")) {
- meth.invoke(clazz, true);
- }
- // i think max has a list in license-management
- }
- }
- }
- }
-
- /**
- * Gets the dynamic example object.
- *
- * @param childObject the child object
- * @param aaiRes the aai res
- * @param singleton the singleton
- * @return the dynamic example object
- */
- public void getDynamicExampleObject(DynamicEntity childObject, AAIResource aaiRes, boolean singleton) {
- // TODO Auto-generated method stub
-
- Random rand = new SecureRandom();
- Integer randInt = rand.nextInt(100000);
- long range = 100000000L;
- long randLong = (long)(rand.nextDouble()*range);
- Integer randShrt = rand.nextInt(20000);
- short randShort = randShrt.shortValue();
-
- for (String dnHypAttrName : aaiRes.getStringFields()) {
-
- if (singleton && ("resource-version").equals(dnHypAttrName)) {
- continue;
- }
-
- String dnCamAttrName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL,dnHypAttrName);
- childObject.set(dnCamAttrName, "example-" + dnHypAttrName + "-val-" + randInt);
-
- }
-
- for (String dnHypAttrName : aaiRes.getStringListFields()) {
- ArrayList<String> exampleList = new ArrayList<String>();
- exampleList.add("example-" + dnHypAttrName + "-val-" + randInt + "-" + 1);
- exampleList.add("example-" + dnHypAttrName + "-val-" + randInt + "-" + 2);
- String dnCamAttrName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL,dnHypAttrName);
- childObject.set(dnCamAttrName, exampleList);
- }
-
- // the attrName might need to be converted to camel case!!!
- for (String dnHypAttrName : aaiRes.getLongFields()) {
- String dnCamAttrName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL,dnHypAttrName);
- childObject.set(dnCamAttrName, randLong);
- }
-
- for (String dnHypAttrName : aaiRes.getIntFields()) {
- String dnCamAttrName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL,dnHypAttrName);
- childObject.set(dnCamAttrName, randInt);
- }
-
- for (String dnHypAttrName : aaiRes.getShortFields()) {
- String dnCamAttrName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL,dnHypAttrName);
- childObject.set(dnCamAttrName, randShort);
- }
-
- for (String dnHypAttrName : aaiRes.getBooleanFields()) {
- String dnCamAttrName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL,dnHypAttrName);
- childObject.set(dnCamAttrName, Boolean.TRUE);
- }
- }
+ /**
+ * Gets the key value list.
+ *
+ * @param <T> the generic type
+ * @param e the e
+ * @param clazz the clazz
+ * @return the key value list
+ * @throws IllegalAccessException the illegal access exception
+ * @throws IllegalArgumentException the illegal argument exception
+ * @throws InvocationTargetException the invocation target exception
+ */
+ public <T> List<KeyValueList> getKeyValueList(Entity e, T clazz)
+ throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
+ List<KeyValueList> kvList = e.getKeyValueList();
+ Object value = null;
+ Method[] methods = clazz.getClass().getDeclaredMethods();
+ String propertyName = "";
+
+ for (Method method : methods) {
+ if (method.getName().startsWith("get")) {
+ propertyName = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, method.getName().substring(3));
+ if (!(method.getReturnType().getName().contains("aai"))
+ || method.getReturnType().getName().contains("java.util.List")) {
+ value = method.invoke(clazz);
+ KeyValueList kv = new KeyValueList();
+ kv.setKey(propertyName);
+ if (value != null) {
+ kv.setValue(value.toString());
+ } else {
+ kv.setValue("");
+ }
+ kvList.add(kv);
+ }
+ }
+ }
+ return kvList;
+ }
+
+ /**
+ * Gets the json from object.
+ *
+ * @param <T> the generic type
+ * @param clazz the clazz
+ * @return the json from object
+ * @throws JsonGenerationException the json generation exception
+ * @throws JsonMappingException the json mapping exception
+ * @throws IOException Signals that an I/O exception has occurred.
+ */
+ public <T> String getJsonFromObject(T clazz) throws JsonGenerationException, JsonMappingException, IOException {
+ return getJsonFromObject(clazz, false, true);
+ }
+
+ /**
+ * Gets the json from object.
+ *
+ * @param <T> the generic type
+ * @param clazz the clazz
+ * @param wrapRoot the wrap root
+ * @param indent the indent
+ * @return the json from object
+ * @throws JsonGenerationException the json generation exception
+ * @throws JsonMappingException the json mapping exception
+ * @throws IOException Signals that an I/O exception has occurred.
+ */
+ public <T> String getJsonFromObject(T clazz, boolean wrapRoot, boolean indent)
+ throws JsonGenerationException, JsonMappingException, IOException {
+ ObjectMapper mapper = new ObjectMapper();
+
+ mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
+
+ mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
+ mapper.configure(SerializationFeature.INDENT_OUTPUT, indent);
+ mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, wrapRoot);
+
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, wrapRoot);
+
+ mapper.registerModule(new JaxbAnnotationModule());
+
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+
+ mapper.writeValue(baos, clazz);
+
+ return baos.toString();
+ }
+
+ /**
+ * Gets the json from dynamic object.
+ *
+ * @param ent the ent
+ * @param jaxbContext the jaxb context
+ * @param includeRoot the include root
+ * @return the json from dynamic object
+ * @throws JsonGenerationException the json generation exception
+ * @throws JsonMappingException the json mapping exception
+ * @throws IOException Signals that an I/O exception has occurred.
+ * @throws JAXBException the JAXB exception
+ */
+ public String getJsonFromDynamicObject(DynamicEntity ent, org.eclipse.persistence.jaxb.JAXBContext jaxbContext,
+ boolean includeRoot) throws JsonGenerationException, JsonMappingException, IOException, JAXBException {
+ JAXBMarshaller marshaller = jaxbContext.createMarshaller();
+
+ marshaller.setProperty(JAXBMarshaller.JAXB_FORMATTED_OUTPUT, false);
+ marshaller.setProperty(MarshallerProperties.JSON_MARSHAL_EMPTY_COLLECTIONS, Boolean.FALSE);
+ marshaller.setProperty("eclipselink.json.include-root", includeRoot);
+ marshaller.setProperty("eclipselink.media-type", "application/json");
+ StringWriter writer = new StringWriter();
+ marshaller.marshal(ent, writer);
+
+ return writer.toString();
+ }
+
+ /**
+ * Gets the xml from object.
+ *
+ * @param <T> the generic type
+ * @param clazz the clazz
+ * @return the xml from object
+ * @throws JAXBException the JAXB exception
+ * @throws IOException
+ */
+ public <T> String getXmlFromObject(T clazz) throws JAXBException, IOException {
+ try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
+ JAXBContext jc = JAXBContext.newInstance(clazz.getClass().getPackage().getName());
+
+ Marshaller marshaller = jc.createMarshaller();
+ marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
+ marshaller.marshal(clazz, baos);
+ return baos.toString();
+ }
+ }
+
+ /**
+ * Gets the lookup key.
+ *
+ * @param baseKey the base key
+ * @param lookupHash the lookup hash
+ * @param keyProps the key props
+ * @return the lookup key
+ */
+ public String getLookupKey(String baseKey, HashMap<String, Object> lookupHash, Collection<String> keyProps) {
+ int baseKeyLen = baseKey.length();
+ StringBuffer newKey = new StringBuffer();
+ if (baseKeyLen > 0) {
+ newKey.append(baseKey);
+ }
+
+ Iterator<String> keyPropI = keyProps.iterator();
+ while (keyPropI.hasNext()) {
+ String keyProp = keyPropI.next();
+ if (baseKeyLen > 0) {
+ newKey.append("&");
+ }
+ newKey.append(keyProp + "=" + lookupHash.get(keyProp));
+ }
+ return newKey.toString();
+ }
+
+ /**
+ * Gets the lookup keys.
+ *
+ * @param lookupHashes the lookup hashes
+ * @param _dbRulesNodeKeyProps the db rules node key props
+ * @return the lookup keys
+ */
+ public String getLookupKeys(LinkedHashMap<String, HashMap<String, Object>> lookupHashes,
+ Multimap<String, String> _dbRulesNodeKeyProps) {
+ Iterator<String> it = lookupHashes.keySet().iterator();
+ String lookupKeys = "";
+ while (it.hasNext()) {
+ String objectType = (String) it.next();
+ HashMap<String, Object> lookupHash = lookupHashes.get(objectType);
+
+ Collection<String> keyProps = _dbRulesNodeKeyProps.get(objectType);
+ Iterator<String> keyPropI = keyProps.iterator();
+ while (keyPropI.hasNext()) {
+ lookupKeys += lookupHash.get(keyPropI.next());
+ }
+ }
+ return lookupKeys;
+ }
+
+ /**
+ * Gets the example object.
+ *
+ * @param <T> the generic type
+ * @param clazz the clazz
+ * @param singleton the singleton
+ * @return the example object
+ * @throws IllegalAccessException the illegal access exception
+ * @throws IllegalArgumentException the illegal argument exception
+ * @throws InvocationTargetException the invocation target exception
+ * @throws NoSuchMethodException the no such method exception
+ * @throws SecurityException the security exception
+ * @throws AAIException the AAI exception
+ */
+ public <T> void getExampleObject(T clazz, boolean singleton)
+ throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException,
+ SecurityException, AAIException {
+ Method[] methods = clazz.getClass().getDeclaredMethods();
+ String dnHypPropertyName = "";
+ String upCamPropertyName = "";
+ Random rand = new SecureRandom();
+ int randInt = rand.nextInt(10000000);
+
+ for (Method method : methods) {
+ boolean go = false;
+ if (method.getName().startsWith("get")) {
+ dnHypPropertyName = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, method.getName().substring(3));
+ upCamPropertyName = CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_CAMEL, method.getName().substring(3));
+ go = true;
+ } else if (method.getName().startsWith("is")) {
+ dnHypPropertyName = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, method.getName().substring(2));
+ upCamPropertyName = CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_CAMEL, method.getName().substring(2));
+ go = true;
+ }
+ // don't return resource-version on a singleton
+ if (singleton && dnHypPropertyName.equals("resource-version")) {
+ go = false;
+ }
+ if (go) {
+ String retType = method.getReturnType().getName();
+ if (!retType.contains("aai") && !retType.contains("java.util.List")) {
+ // get the setter
+ Method meth = clazz.getClass().getMethod("set" + upCamPropertyName, method.getReturnType());
+
+ if (retType.contains("String")) {
+ String val = "example-" + dnHypPropertyName + "-val-" + randInt;
+ if (val != null) {
+ meth.invoke(clazz, val);
+ }
+ } else if (retType.toLowerCase().contains("long")) {
+ Integer foo = rand.nextInt(100000);
+ meth.invoke(clazz, foo.longValue());
+ } else if (retType.toLowerCase().contains("int")) {
+ meth.invoke(clazz, rand.nextInt(100000));
+ } else if (retType.toLowerCase().contains("short")) {
+ Integer randShort = rand.nextInt(10000);
+ meth.invoke(clazz, randShort.shortValue());
+ } else if (retType.toLowerCase().contains("boolean")) {
+ meth.invoke(clazz, true);
+ }
+ // i think max has a list in license-management
+ }
+ }
+ }
+ }
+
+ /**
+ * Gets the dynamic example object.
+ *
+ * @param childObject the child object
+ * @param aaiRes the aai res
+ * @param singleton the singleton
+ * @return the dynamic example object
+ */
+ public void getDynamicExampleObject(DynamicEntity childObject, AAIResource aaiRes, boolean singleton) {
+ // TODO Auto-generated method stub
+
+ Random rand = new SecureRandom();
+ Integer randInt = rand.nextInt(100000);
+ long range = 100000000L;
+ long randLong = (long) (rand.nextDouble() * range);
+ Integer randShrt = rand.nextInt(20000);
+ short randShort = randShrt.shortValue();
+
+ for (String dnHypAttrName : aaiRes.getStringFields()) {
+
+ if (singleton && ("resource-version").equals(dnHypAttrName)) {
+ continue;
+ }
+
+ String dnCamAttrName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, dnHypAttrName);
+ childObject.set(dnCamAttrName, "example-" + dnHypAttrName + "-val-" + randInt);
+
+ }
+
+ for (String dnHypAttrName : aaiRes.getStringListFields()) {
+ ArrayList<String> exampleList = new ArrayList<String>();
+ exampleList.add("example-" + dnHypAttrName + "-val-" + randInt + "-" + 1);
+ exampleList.add("example-" + dnHypAttrName + "-val-" + randInt + "-" + 2);
+ String dnCamAttrName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, dnHypAttrName);
+ childObject.set(dnCamAttrName, exampleList);
+ }
+
+ // the attrName might need to be converted to camel case!!!
+ for (String dnHypAttrName : aaiRes.getLongFields()) {
+ String dnCamAttrName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, dnHypAttrName);
+ childObject.set(dnCamAttrName, randLong);
+ }
+
+ for (String dnHypAttrName : aaiRes.getIntFields()) {
+ String dnCamAttrName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, dnHypAttrName);
+ childObject.set(dnCamAttrName, randInt);
+ }
+
+ for (String dnHypAttrName : aaiRes.getShortFields()) {
+ String dnCamAttrName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, dnHypAttrName);
+ childObject.set(dnCamAttrName, randShort);
+ }
+
+ for (String dnHypAttrName : aaiRes.getBooleanFields()) {
+ String dnCamAttrName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, dnHypAttrName);
+ childObject.set(dnCamAttrName, Boolean.TRUE);
+ }
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/util/Request.java b/aai-core/src/main/java/org/onap/aai/util/Request.java
index fb695b2f..890398d5 100644
--- a/aai-core/src/main/java/org/onap/aai/util/Request.java
+++ b/aai-core/src/main/java/org/onap/aai/util/Request.java
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.util;
import java.io.UnsupportedEncodingException;
@@ -31,126 +32,123 @@ import org.onap.aai.exceptions.AAIException;
public class Request<T> {
- public static final String V14 = "v14";
- public final String fromAppId;
- public final String transactionId;
- public final String path;
- public final RestObject<T> restObj;
- public final boolean oldServer;
- public final String apiVersion;
-
-
- /**
- * Instantiates a new request.
- *
- * @param builder the builder
- */
- public Request(RequestBuilder<T> builder) {
-
- fromAppId = builder.fromAppId;
- transactionId = builder.transactionId;
- restObj = builder.restObj;
- oldServer = builder.oldServer;
- apiVersion = builder.apiVersion;
-
- if (!oldServer) {
- path = apiVersion + "/" + builder.path;
- } else {
- path = builder.path;
- }
-
-
- }
-
- public static class RequestBuilder<T> {
- private String fromAppId;
- private String transactionId;
- private String path;
- private RestObject<T> restObj;
- private boolean oldServer;
- private String apiVersion = Request.V14;
-
-
- /**
- * Sets the from app id.
- *
- * @param fromAppId the from app id
- * @return the request builder
- */
- public RequestBuilder<T> setFromAppId(String fromAppId) {
- this.fromAppId = fromAppId;
- return this;
- }
-
- /**
- * Sets the transaction id.
- *
- * @param transactionId the transaction id
- * @return the request builder
- */
- public RequestBuilder<T> setTransactionId(String transactionId) {
- this.transactionId = transactionId;
- return this;
-
- }
-
- /**
- * Sets the path.
- *
- * @param path the path
- * @return the request builder
- */
- public RequestBuilder<T> setPath(String path) {
-
- this.path = path;
- return this;
-
- }
-
- /**
- * Sets the restcore obj.
- *
- * @param restObj the restcore obj
- * @return the request builder
- */
- public RequestBuilder<T> setRestObj(RestObject<T> restObj) {
- this.restObj = restObj;
- return this;
-
- }
-
- /**
- * Sets the old server.
- *
- * @param oldServer the old server
- * @return the request builder
- */
- public RequestBuilder<T> setOldServer(boolean oldServer) {
- this.oldServer = oldServer;
- return this;
-
- }
-
- /**
- * Sets the api version.
- *
- * @param apiVersion the api version
- * @return the request builder
- */
- public RequestBuilder<T> setApiVersion(String apiVersion) {
- this.apiVersion = apiVersion;
- return this;
- }
-
- /**
- * Builds the.
- *
- * @return the request
- */
- public Request<T> build() {
- return new Request<T>(this);
- }
-
- }
-
+ public static final String V14 = "v14";
+ public final String fromAppId;
+ public final String transactionId;
+ public final String path;
+ public final RestObject<T> restObj;
+ public final boolean oldServer;
+ public final String apiVersion;
+
+ /**
+ * Instantiates a new request.
+ *
+ * @param builder the builder
+ */
+ public Request(RequestBuilder<T> builder) {
+
+ fromAppId = builder.fromAppId;
+ transactionId = builder.transactionId;
+ restObj = builder.restObj;
+ oldServer = builder.oldServer;
+ apiVersion = builder.apiVersion;
+
+ if (!oldServer) {
+ path = apiVersion + "/" + builder.path;
+ } else {
+ path = builder.path;
+ }
+
+ }
+
+ public static class RequestBuilder<T> {
+ private String fromAppId;
+ private String transactionId;
+ private String path;
+ private RestObject<T> restObj;
+ private boolean oldServer;
+ private String apiVersion = Request.V14;
+
+ /**
+ * Sets the from app id.
+ *
+ * @param fromAppId the from app id
+ * @return the request builder
+ */
+ public RequestBuilder<T> setFromAppId(String fromAppId) {
+ this.fromAppId = fromAppId;
+ return this;
+ }
+
+ /**
+ * Sets the transaction id.
+ *
+ * @param transactionId the transaction id
+ * @return the request builder
+ */
+ public RequestBuilder<T> setTransactionId(String transactionId) {
+ this.transactionId = transactionId;
+ return this;
+
+ }
+
+ /**
+ * Sets the path.
+ *
+ * @param path the path
+ * @return the request builder
+ */
+ public RequestBuilder<T> setPath(String path) {
+
+ this.path = path;
+ return this;
+
+ }
+
+ /**
+ * Sets the restcore obj.
+ *
+ * @param restObj the restcore obj
+ * @return the request builder
+ */
+ public RequestBuilder<T> setRestObj(RestObject<T> restObj) {
+ this.restObj = restObj;
+ return this;
+
+ }
+
+ /**
+ * Sets the old server.
+ *
+ * @param oldServer the old server
+ * @return the request builder
+ */
+ public RequestBuilder<T> setOldServer(boolean oldServer) {
+ this.oldServer = oldServer;
+ return this;
+
+ }
+
+ /**
+ * Sets the api version.
+ *
+ * @param apiVersion the api version
+ * @return the request builder
+ */
+ public RequestBuilder<T> setApiVersion(String apiVersion) {
+ this.apiVersion = apiVersion;
+ return this;
+ }
+
+ /**
+ * Builds the.
+ *
+ * @return the request
+ */
+ public Request<T> build() {
+ return new Request<T>(this);
+ }
+
+ }
+
}
diff --git a/aai-core/src/main/java/org/onap/aai/util/RestController.java b/aai-core/src/main/java/org/onap/aai/util/RestController.java
index 20bb0a9b..a1419d14 100644
--- a/aai-core/src/main/java/org/onap/aai/util/RestController.java
+++ b/aai-core/src/main/java/org/onap/aai/util/RestController.java
@@ -17,15 +17,8 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-package org.onap.aai.util;
-import java.security.KeyManagementException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.UUID;
-
-import org.onap.aai.exceptions.AAIException;
-import org.onap.aai.logging.LoggingContext;
+package org.onap.aai.util;
import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
@@ -35,402 +28,401 @@ import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientHandlerException;
import com.sun.jersey.api.client.ClientResponse;
+import java.security.KeyManagementException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.UUID;
+
+import org.onap.aai.exceptions.AAIException;
+import org.onap.aai.logging.LoggingContext;
+
public class RestController implements RestControllerInterface {
- private static final String TARGET_NAME = "AAI";
- private static EELFLogger LOGGER = EELFManager.getInstance().getLogger(RestController.class);
-
- private static Client client = null;
-
- private String restSrvrBaseURL;
-
- private String overrideLocalHost = null;
-
- //To do - Come up with helper function that will automatically
- //generate the REST API path based on path parameter(s) and query parameter(s)!
- public static final String REST_APIPATH_COMPLEXES = "cloud-infrastructure/complexes";
- public static final String REST_APIPATH_COMPLEX = "cloud-infrastructure/complexes/complex/";
- public static final String REST_APIPATH_PSERVERS = "cloud-infrastructure/pservers";
- public static final String REST_APIPATH_PSERVER = "cloud-infrastructure/pservers/pserver/";
- public static final String REST_APIPATH_PHYSICALLINKS = "network/physical-links/";
- public static final String REST_APIPATH_PHYSICALLINK = "network/physical-links/physical-link/";
- public static final String REST_APIPATH_PINTERFACES = "network/p-interfaces/";
- public static final String REST_APIPATH_PINTERFACE = "network/p-interfaces/p-interface/";
- public static final String REST_APIPATH_VPLSPES = "network/vpls-pes/";
- public static final String REST_APIPATH_VPLSPE = "network/vpls-pes/vpls-pe/";
- public static final String REST_APIPATH_UPDATE = "actions/update/";
- public static final String REST_APIPATH_SEARCH = "search/nodes-query?search-node-type=";
-
- public static final String REST_APIPATH_CLOUDREGION = "cloud-infrastructure/cloud-regions/cloud-region/";
- public static final String REST_APIPATH_TENANT = "cloud-infrastructure/tenants/tenant/";
- public static final String REST_APIPATH_VIRTUAL_DATA_CENTER = "cloud-infrastructure/virtual-data-centers/virtual-data-center/";
- public static final String REST_APIPATH_VIRTUAL_DATA_CENTERS = "cloud-infrastructure/virtual-data-centers/";
- public static final String REST_APIPATH_GENERIC_VNF = "network/generic-vnfs/generic-vnf/";
- public static final String REST_APIPATH_GENERIC_VNFS = "network/generic-vnfs";
- public static final String REST_APIPATH_L3_NETWORK = "network/l3-networks/l3-network/";
- public static final String REST_APIPATH_L3_NETWORKS = "network/l3-networks";
- public static final String REST_APIPATH_INSTANCE_GROUP = "network/instance-groups/instance-group";
- public static final String REST_APIPATH_INSTANCE_GROUPS = "network/instance-groups";
- public static final String REST_APIPATH_VFMODULE = "nodes/vf-modules/vf-module/";
-
- public static final String REST_APIPATH_VCE = "network/vces/vce/";
-
- public static final String REST_APIPATH_SERVICE = "service-design-and-creation/services/service/";
- public static final String REST_APIPATH_LOGICALLINKS = "network/logical-links/";
- public static final String REST_APIPATH_LOGICALLINK = "network/logical-links/logical-link/";
-
- public RestController() throws AAIException {
- this.initRestClient();
- }
- /**
- * Inits the rest client.
- *
- * @throws AAIException the AAI exception
- */
- public void initRestClient() throws AAIException
- {
- if (client == null) {
- try {
- client = getHttpsAuthClient();
- }
- catch (KeyManagementException e){
- throw new AAIException("AAI_7117", "KeyManagementException in REST call to DB: " + e.toString());
- } catch (Exception e) {
- throw new AAIException("AAI_7117", " Exception in REST call to DB: " + e.toString());
- }
- }
- }
-
+ private static final String TARGET_NAME = "AAI";
+ private static EELFLogger LOGGER = EELFManager.getInstance().getLogger(RestController.class);
+
+ private static Client client = null;
+
+ private String restSrvrBaseURL;
+
+ private String overrideLocalHost = null;
+
+ // To do - Come up with helper function that will automatically
+ // generate the REST API path based on path parameter(s) and query parameter(s)!
+ public static final String REST_APIPATH_COMPLEXES = "cloud-infrastructure/complexes";
+ public static final String REST_APIPATH_COMPLEX = "cloud-infrastructure/complexes/complex/";
+ public static final String REST_APIPATH_PSERVERS = "cloud-infrastructure/pservers";
+ public static final String REST_APIPATH_PSERVER = "cloud-infrastructure/pservers/pserver/";
+ public static final String REST_APIPATH_PHYSICALLINKS = "network/physical-links/";
+ public static final String REST_APIPATH_PHYSICALLINK = "network/physical-links/physical-link/";
+ public static final String REST_APIPATH_PINTERFACES = "network/p-interfaces/";
+ public static final String REST_APIPATH_PINTERFACE = "network/p-interfaces/p-interface/";
+ public static final String REST_APIPATH_VPLSPES = "network/vpls-pes/";
+ public static final String REST_APIPATH_VPLSPE = "network/vpls-pes/vpls-pe/";
+ public static final String REST_APIPATH_UPDATE = "actions/update/";
+ public static final String REST_APIPATH_SEARCH = "search/nodes-query?search-node-type=";
+
+ public static final String REST_APIPATH_CLOUDREGION = "cloud-infrastructure/cloud-regions/cloud-region/";
+ public static final String REST_APIPATH_TENANT = "cloud-infrastructure/tenants/tenant/";
+ public static final String REST_APIPATH_VIRTUAL_DATA_CENTER =
+ "cloud-infrastructure/virtual-data-centers/virtual-data-center/";
+ public static final String REST_APIPATH_VIRTUAL_DATA_CENTERS = "cloud-infrastructure/virtual-data-centers/";
+ public static final String REST_APIPATH_GENERIC_VNF = "network/generic-vnfs/generic-vnf/";
+ public static final String REST_APIPATH_GENERIC_VNFS = "network/generic-vnfs";
+ public static final String REST_APIPATH_L3_NETWORK = "network/l3-networks/l3-network/";
+ public static final String REST_APIPATH_L3_NETWORKS = "network/l3-networks";
+ public static final String REST_APIPATH_INSTANCE_GROUP = "network/instance-groups/instance-group";
+ public static final String REST_APIPATH_INSTANCE_GROUPS = "network/instance-groups";
+ public static final String REST_APIPATH_VFMODULE = "nodes/vf-modules/vf-module/";
+
+ public static final String REST_APIPATH_VCE = "network/vces/vce/";
+
+ public static final String REST_APIPATH_SERVICE = "service-design-and-creation/services/service/";
+ public static final String REST_APIPATH_LOGICALLINKS = "network/logical-links/";
+ public static final String REST_APIPATH_LOGICALLINK = "network/logical-links/logical-link/";
+
+ public RestController() throws AAIException {
+ this.initRestClient();
+ }
+
+ /**
+ * Inits the rest client.
+ *
+ * @throws AAIException the AAI exception
+ */
+ public void initRestClient() throws AAIException {
+ if (client == null) {
+ try {
+ client = getHttpsAuthClient();
+ } catch (KeyManagementException e) {
+ throw new AAIException("AAI_7117", "KeyManagementException in REST call to DB: " + e.toString());
+ } catch (Exception e) {
+ throw new AAIException("AAI_7117", " Exception in REST call to DB: " + e.toString());
+ }
+ }
+ }
+
public Client getHttpsAuthClient() throws KeyManagementException {
return HttpsAuthClient.getClient();
}
-
- /**
- * Sets the rest srvr base URL.
- *
- * @param baseURL the base URL
- * @throws AAIException the AAI exception
- */
- public void SetRestSrvrBaseURL(String baseURL) throws AAIException
- {
- if (baseURL == null)
- throw new AAIException("AAI_7117", "REST Server base URL cannot be null.");
- restSrvrBaseURL = baseURL;
- }
-
- /**
- * Gets the rest srvr base URL.
- *
- * @return the rest srvr base URL
- */
- public String getRestSrvrBaseURL()
- {
- return restSrvrBaseURL;
- }
-
-
- public <T> void Get(T t, String sourceID, String transId, String path, RestObject<T> restObject, boolean oldserver) throws AAIException {
- Get(t, sourceID, transId, path, restObject, oldserver, AAIConstants.AAI_RESOURCES_PORT);
- }
- /**
- * To do - optimization and automation. Also make it as generic as possible.
- *
- * @param <T> the generic type
- * @param t the t
- * @param sourceID the source ID
- * @param transId the trans id
- * @param path the path
- * @param restObject the rest object
- * @param oldserver the oldserver
- * @throws AAIException the AAI exception
- */
- @SuppressWarnings("unchecked")
- public <T> void Get(T t, String sourceID, String transId, String path, RestObject<T> restObject, boolean oldserver, int port) throws AAIException {
- String methodName = "Get";
- String url="";
- transId += ":" + UUID.randomUUID().toString();
-
- LoggingContext.save();
- LoggingContext.partnerName(sourceID);
- LoggingContext.targetEntity(TARGET_NAME);
- LoggingContext.requestId(transId);
- LoggingContext.serviceName(methodName);
- LoggingContext.targetServiceName(methodName);
-
- LOGGER.debug(methodName + " start");
-
- restObject.set(t);
-
- if (oldserver) {
- url = AAIConfig.get(AAIConstants.AAI_OLDSERVER_URL) + path;
- } else {
- if ( overrideLocalHost == null ) {
- overrideLocalHost = AAIConfig.get(AAIConstants.AAI_LOCAL_OVERRIDE, AAIConstants.AAI_LOCAL_OVERRIDE_DEFAULT);
- }
- if ( AAIConstants.AAI_LOCAL_OVERRIDE_DEFAULT.equals(overrideLocalHost )) {
- url = String.format(AAIConstants.AAI_LOCAL_REST, port, AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP)) + path;
- } else {
- url = String.format(AAIConstants.AAI_LOCAL_REST_OVERRIDE, overrideLocalHost, AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP)) + path;
- }
- }
- initRestClient();
- LOGGER.debug(url + " for the get REST API");
- ClientResponse cres = client.resource(url)
- .accept("application/json")
- .header("X-TransactionId", transId)
- .header("X-FromAppId", sourceID)
- .header("Real-Time", "true")
- .type("application/json")
- .get(ClientResponse.class);
-
-// System.out.println("cres.EntityInputSream()="+cres.getEntityInputStream().toString());
-// System.out.println("cres.tostring()="+cres.toString());
-
- if (cres.getStatus() == 200) {
-// System.out.println(methodName + ": url=" + url);
- t = (T) cres.getEntity(t.getClass());
- restObject.set(t);
- LOGGER.debug(methodName + "REST api GET was successfull!");
- } else {
- LoggingContext.restore();
-// System.out.println(methodName + ": url=" + url + " failed with status=" + cres.getStatus());
- throw new AAIException("AAI_7116", methodName +" with status="+cres.getStatus()+", url="+url);
- }
-
- LoggingContext.restore();
- }
-
- /**
- * To do - optimization and automation. Also make it as generic as possible.
- *
- * @param <T> the generic type
- * @param t the t
- * @param sourceID the source ID
- * @param transId the trans id
- * @param path the path
- * @param restObject the rest object
- * @param oldserver the oldserver
- * @throws AAIException the AAI exception
- */
- @SuppressWarnings("unchecked")
- public <T> void Get(T t, String sourceID, String transId, String path, RestObject<T> restObject, String apiVersion) throws AAIException {
- String methodName = "Get";
- String url="";
- transId += ":" + UUID.randomUUID().toString();
-
- LoggingContext.save();
- LoggingContext.partnerName(sourceID);
- LoggingContext.targetEntity(TARGET_NAME);
- LoggingContext.requestId(transId);
- LoggingContext.serviceName(methodName);
- LoggingContext.targetServiceName(methodName);
-
- LOGGER.debug(methodName + " start");
-
- restObject.set(t);
-
- url = AAIConfig.get(AAIConstants.AAI_SERVER_URL_BASE) + apiVersion + "/"+ path;
-
- initRestClient();
- LOGGER.debug(url + " for the get REST API");
- ClientResponse cres = client.resource(url)
- .accept("application/json")
- .header("X-TransactionId", transId)
- .header("X-FromAppId", sourceID)
- .header("Real-Time", "true")
- .type("application/json")
- .get(ClientResponse.class);
-
-// System.out.println("cres.EntityInputSream()="+cres.getEntityInputStream().toString());
-// System.out.println("cres.tostring()="+cres.toString());
-
- if (cres.getStatus() == 200) {
-// System.out.println(methodName + ": url=" + url);
- t = (T) cres.getEntity(t.getClass());
- restObject.set(t);
- LOGGER.debug(methodName + "REST api GET was successfull!");
- } else {
- LoggingContext.restore();
-// System.out.println(methodName + ": url=" + url + " failed with status=" + cres.getStatus());
- throw new AAIException("AAI_7116", methodName +" with status="+cres.getStatus()+", url="+url);
- }
-
- LoggingContext.restore();
- }
-
- /**
- * Map json to object list.
- *
- * @param <T> the generic type
- * @param typeDef the type def
- * @param json the json
- * @param clazz the clazz
- * @return the list
- * @throws Exception the exception
- */
- private <T> List<T> mapJsonToObjectList(T typeDef,String json, Class clazz) throws Exception
- {
- List<T> list;
- ObjectMapper mapper = new ObjectMapper();
- System.out.println(json);
- TypeFactory t = TypeFactory.defaultInstance();
- list = mapper.readValue(json, t.constructCollectionType(ArrayList.class,clazz));
-
- return list;
- }
-
- /**
- * Put.
- *
- * @param <T> the generic type
- * @param t the t
- * @param sourceID the source ID
- * @param transId the trans id
- * @param path the path
- * @throws AAIException the AAI exception
- */
- public <T> void Put(T t, String sourceID, String transId, String path) throws AAIException {
- Put( t, sourceID, transId, path, false, AAIConstants.AAI_RESOURCES_PORT);
- }
-
- /**
- * Put.
- *
- * @param <T> the generic type
- * @param t the t
- * @param sourceID the source ID
- * @param transId the trans id
- * @param path the path
- * @throws AAIException the AAI exception
- */
- public <T> void Put(T t, String sourceID, String transId, String path, boolean oldserver) throws AAIException {
- Put( t, sourceID, transId, path, oldserver, AAIConstants.AAI_RESOURCES_PORT);
- }
-
- /**
- * Put.
- *
- * @param <T> the generic type
- * @param t the t
- * @param sourceID the source ID
- * @param transId the trans id
- * @param path the path
- * @param oldserver the oldserver
- * @throws AAIException the AAI exception
- */
- public <T> void Put(T t, String sourceID, String transId, String path, boolean oldserver, int port) throws AAIException {
- String methodName = "Put";
- String url="";
- transId += ":" + UUID.randomUUID().toString();
-
- LoggingContext.save();
- LoggingContext.partnerName(sourceID);
- LoggingContext.targetEntity(TARGET_NAME);
- LoggingContext.requestId(transId);
- LoggingContext.serviceName(methodName);
- LoggingContext.targetServiceName(methodName);
-
- LOGGER.debug(methodName + " start");
-
- initRestClient();
-
- if (oldserver) {
- url = AAIConfig.get(AAIConstants.AAI_OLDSERVER_URL) + path;
- } else {
- if ( overrideLocalHost == null ) {
- overrideLocalHost = AAIConfig.get(AAIConstants.AAI_LOCAL_OVERRIDE, AAIConstants.AAI_LOCAL_OVERRIDE_DEFAULT);
- }
- if ( AAIConstants.AAI_LOCAL_OVERRIDE_DEFAULT.equals(overrideLocalHost )) {
- url = String.format(AAIConstants.AAI_LOCAL_REST, port, AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP)) + path;
- } else {
- url = String.format(AAIConstants.AAI_LOCAL_REST_OVERRIDE, overrideLocalHost, AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP)) + path;
- }
- }
-
- ClientResponse cres = client.resource(url)
- .accept("application/json")
- .header("X-TransactionId", transId)
- .header("X-FromAppId", sourceID)
- .header("Real-Time", "true")
- .type("application/json")
- .entity(t)
- .put(ClientResponse.class);
-
-// System.out.println("cres.tostring()="+cres.toString());
-
- int statuscode = cres.getStatus();
- if ( statuscode >= 200 && statuscode <= 299 ) {
- LOGGER.debug(methodName+": url=" + url + ", request=" + path);
- LoggingContext.restore();
- } else {
- LoggingContext.restore();
- throw new AAIException("AAI_7116", methodName +" with status="+statuscode+", url="+url + ", msg=" + cres.getEntity(String.class));
- }
- }
-
- public void Delete(String sourceID, String transId, String path) throws AAIException {
- Delete(sourceID, transId, path, AAIConstants.AAI_RESOURCES_PORT);
- }
- /**
- * Delete.
- *
- * @param sourceID the source ID
- * @param transId the trans id
- * @param path the path
- * @throws AAIException the AAI exception
- */
- public void Delete(String sourceID, String transId, String path, int port) throws AAIException {
- String methodName = "Delete";
- String url="";
- transId += ":" + UUID.randomUUID().toString();
-
- LoggingContext.save();
- LoggingContext.partnerName(sourceID);
- LoggingContext.targetEntity(TARGET_NAME);
- LoggingContext.requestId(transId);
- LoggingContext.serviceName(methodName);
- LoggingContext.targetServiceName(methodName);
-
- LOGGER.debug(methodName + " start");
-
- initRestClient();
- String request = "{}";
- if ( overrideLocalHost == null ) {
- overrideLocalHost = AAIConfig.get(AAIConstants.AAI_LOCAL_OVERRIDE, AAIConstants.AAI_LOCAL_OVERRIDE_DEFAULT);
- }
- if ( AAIConstants.AAI_LOCAL_OVERRIDE_DEFAULT.equals(overrideLocalHost )) {
- url = String.format(AAIConstants.AAI_LOCAL_REST, port, AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP)) + path;
- } else {
- url = String.format(AAIConstants.AAI_LOCAL_REST_OVERRIDE, overrideLocalHost, AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP)) + path;
- }
- ClientResponse cres = client.resource(url)
- .accept("application/json")
- .header("X-TransactionId", transId)
- .header("X-FromAppId", sourceID)
- .header("Real-Time", "true")
- .type("application/json")
- .entity(request)
- .delete(ClientResponse.class);
-
- if (cres.getStatus() == 404) { // resource not found
- LOGGER.info("Resource does not exist...: " + cres.getStatus()
- + ":" + cres.getEntity(String.class));
- LoggingContext.restore();
- } else if (cres.getStatus() == 200 || cres.getStatus() == 204){
- LOGGER.info("Resource " + url + " deleted");
- LoggingContext.restore();
- } else {
- LOGGER.error("Deleting Resource failed: " + cres.getStatus()
- + ":" + cres.getEntity(String.class));
- LoggingContext.restore();
+ /**
+ * Sets the rest srvr base URL.
+ *
+ * @param baseURL the base URL
+ * @throws AAIException the AAI exception
+ */
+ public void SetRestSrvrBaseURL(String baseURL) throws AAIException {
+ if (baseURL == null)
+ throw new AAIException("AAI_7117", "REST Server base URL cannot be null.");
+ restSrvrBaseURL = baseURL;
+ }
+
+ /**
+ * Gets the rest srvr base URL.
+ *
+ * @return the rest srvr base URL
+ */
+ public String getRestSrvrBaseURL() {
+ return restSrvrBaseURL;
+ }
+
+ public <T> void Get(T t, String sourceID, String transId, String path, RestObject<T> restObject, boolean oldserver)
+ throws AAIException {
+ Get(t, sourceID, transId, path, restObject, oldserver, AAIConstants.AAI_RESOURCES_PORT);
+ }
+
+ /**
+ * To do - optimization and automation. Also make it as generic as possible.
+ *
+ * @param <T> the generic type
+ * @param t the t
+ * @param sourceID the source ID
+ * @param transId the trans id
+ * @param path the path
+ * @param restObject the rest object
+ * @param oldserver the oldserver
+ * @throws AAIException the AAI exception
+ */
+ @SuppressWarnings("unchecked")
+ public <T> void Get(T t, String sourceID, String transId, String path, RestObject<T> restObject, boolean oldserver,
+ int port) throws AAIException {
+ String methodName = "Get";
+ String url = "";
+ transId += ":" + UUID.randomUUID().toString();
+
+ LoggingContext.save();
+ LoggingContext.partnerName(sourceID);
+ LoggingContext.targetEntity(TARGET_NAME);
+ LoggingContext.requestId(transId);
+ LoggingContext.serviceName(methodName);
+ LoggingContext.targetServiceName(methodName);
+
+ LOGGER.debug(methodName + " start");
+
+ restObject.set(t);
+
+ if (oldserver) {
+ url = AAIConfig.get(AAIConstants.AAI_OLDSERVER_URL) + path;
+ } else {
+ if (overrideLocalHost == null) {
+ overrideLocalHost =
+ AAIConfig.get(AAIConstants.AAI_LOCAL_OVERRIDE, AAIConstants.AAI_LOCAL_OVERRIDE_DEFAULT);
+ }
+ if (AAIConstants.AAI_LOCAL_OVERRIDE_DEFAULT.equals(overrideLocalHost)) {
+ url = String.format(AAIConstants.AAI_LOCAL_REST, port,
+ AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP)) + path;
+ } else {
+ url = String.format(AAIConstants.AAI_LOCAL_REST_OVERRIDE, overrideLocalHost,
+ AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP)) + path;
+ }
+ }
+ initRestClient();
+ LOGGER.debug(url + " for the get REST API");
+ ClientResponse cres = client.resource(url).accept("application/json").header("X-TransactionId", transId)
+ .header("X-FromAppId", sourceID).header("Real-Time", "true").type("application/json")
+ .get(ClientResponse.class);
+
+ // System.out.println("cres.EntityInputSream()="+cres.getEntityInputStream().toString());
+ // System.out.println("cres.tostring()="+cres.toString());
+
+ if (cres.getStatus() == 200) {
+ // System.out.println(methodName + ": url=" + url);
+ t = (T) cres.getEntity(t.getClass());
+ restObject.set(t);
+ LOGGER.debug(methodName + "REST api GET was successfull!");
+ } else {
+ LoggingContext.restore();
+ // System.out.println(methodName + ": url=" + url + " failed with status=" + cres.getStatus());
+ throw new AAIException("AAI_7116", methodName + " with status=" + cres.getStatus() + ", url=" + url);
+ }
+
+ LoggingContext.restore();
+ }
+
+ /**
+ * To do - optimization and automation. Also make it as generic as possible.
+ *
+ * @param <T> the generic type
+ * @param t the t
+ * @param sourceID the source ID
+ * @param transId the trans id
+ * @param path the path
+ * @param restObject the rest object
+ * @param oldserver the oldserver
+ * @throws AAIException the AAI exception
+ */
+ @SuppressWarnings("unchecked")
+ public <T> void Get(T t, String sourceID, String transId, String path, RestObject<T> restObject, String apiVersion)
+ throws AAIException {
+ String methodName = "Get";
+ String url = "";
+ transId += ":" + UUID.randomUUID().toString();
+
+ LoggingContext.save();
+ LoggingContext.partnerName(sourceID);
+ LoggingContext.targetEntity(TARGET_NAME);
+ LoggingContext.requestId(transId);
+ LoggingContext.serviceName(methodName);
+ LoggingContext.targetServiceName(methodName);
+
+ LOGGER.debug(methodName + " start");
+
+ restObject.set(t);
+
+ url = AAIConfig.get(AAIConstants.AAI_SERVER_URL_BASE) + apiVersion + "/" + path;
+
+ initRestClient();
+ LOGGER.debug(url + " for the get REST API");
+ ClientResponse cres = client.resource(url).accept("application/json").header("X-TransactionId", transId)
+ .header("X-FromAppId", sourceID).header("Real-Time", "true").type("application/json")
+ .get(ClientResponse.class);
+
+ // System.out.println("cres.EntityInputSream()="+cres.getEntityInputStream().toString());
+ // System.out.println("cres.tostring()="+cres.toString());
+
+ if (cres.getStatus() == 200) {
+ // System.out.println(methodName + ": url=" + url);
+ t = (T) cres.getEntity(t.getClass());
+ restObject.set(t);
+ LOGGER.debug(methodName + "REST api GET was successfull!");
+ } else {
+ LoggingContext.restore();
+ // System.out.println(methodName + ": url=" + url + " failed with status=" + cres.getStatus());
+ throw new AAIException("AAI_7116", methodName + " with status=" + cres.getStatus() + ", url=" + url);
+ }
+
+ LoggingContext.restore();
+ }
+
+ /**
+ * Map json to object list.
+ *
+ * @param <T> the generic type
+ * @param typeDef the type def
+ * @param json the json
+ * @param clazz the clazz
+ * @return the list
+ * @throws Exception the exception
+ */
+ private <T> List<T> mapJsonToObjectList(T typeDef, String json, Class clazz) throws Exception {
+ List<T> list;
+ ObjectMapper mapper = new ObjectMapper();
+ System.out.println(json);
+ TypeFactory t = TypeFactory.defaultInstance();
+ list = mapper.readValue(json, t.constructCollectionType(ArrayList.class, clazz));
+
+ return list;
+ }
+
+ /**
+ * Put.
+ *
+ * @param <T> the generic type
+ * @param t the t
+ * @param sourceID the source ID
+ * @param transId the trans id
+ * @param path the path
+ * @throws AAIException the AAI exception
+ */
+ public <T> void Put(T t, String sourceID, String transId, String path) throws AAIException {
+ Put(t, sourceID, transId, path, false, AAIConstants.AAI_RESOURCES_PORT);
+ }
+
+ /**
+ * Put.
+ *
+ * @param <T> the generic type
+ * @param t the t
+ * @param sourceID the source ID
+ * @param transId the trans id
+ * @param path the path
+ * @throws AAIException the AAI exception
+ */
+ public <T> void Put(T t, String sourceID, String transId, String path, boolean oldserver) throws AAIException {
+ Put(t, sourceID, transId, path, oldserver, AAIConstants.AAI_RESOURCES_PORT);
+ }
+
+ /**
+ * Put.
+ *
+ * @param <T> the generic type
+ * @param t the t
+ * @param sourceID the source ID
+ * @param transId the trans id
+ * @param path the path
+ * @param oldserver the oldserver
+ * @throws AAIException the AAI exception
+ */
+ public <T> void Put(T t, String sourceID, String transId, String path, boolean oldserver, int port)
+ throws AAIException {
+ String methodName = "Put";
+ String url = "";
+ transId += ":" + UUID.randomUUID().toString();
+
+ LoggingContext.save();
+ LoggingContext.partnerName(sourceID);
+ LoggingContext.targetEntity(TARGET_NAME);
+ LoggingContext.requestId(transId);
+ LoggingContext.serviceName(methodName);
+ LoggingContext.targetServiceName(methodName);
+
+ LOGGER.debug(methodName + " start");
+
+ initRestClient();
+
+ if (oldserver) {
+ url = AAIConfig.get(AAIConstants.AAI_OLDSERVER_URL) + path;
+ } else {
+ if (overrideLocalHost == null) {
+ overrideLocalHost =
+ AAIConfig.get(AAIConstants.AAI_LOCAL_OVERRIDE, AAIConstants.AAI_LOCAL_OVERRIDE_DEFAULT);
+ }
+ if (AAIConstants.AAI_LOCAL_OVERRIDE_DEFAULT.equals(overrideLocalHost)) {
+ url = String.format(AAIConstants.AAI_LOCAL_REST, port,
+ AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP)) + path;
+ } else {
+ url = String.format(AAIConstants.AAI_LOCAL_REST_OVERRIDE, overrideLocalHost,
+ AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP)) + path;
+ }
+ }
+
+ ClientResponse cres = client.resource(url).accept("application/json").header("X-TransactionId", transId)
+ .header("X-FromAppId", sourceID).header("Real-Time", "true").type("application/json").entity(t)
+ .put(ClientResponse.class);
+
+ // System.out.println("cres.tostring()="+cres.toString());
+
+ int statuscode = cres.getStatus();
+ if (statuscode >= 200 && statuscode <= 299) {
+ LOGGER.debug(methodName + ": url=" + url + ", request=" + path);
+ LoggingContext.restore();
+ } else {
+ LoggingContext.restore();
+ throw new AAIException("AAI_7116", methodName + " with status=" + statuscode + ", url=" + url + ", msg="
+ + cres.getEntity(String.class));
+ }
+ }
+
+ public void Delete(String sourceID, String transId, String path) throws AAIException {
+ Delete(sourceID, transId, path, AAIConstants.AAI_RESOURCES_PORT);
+ }
+
+ /**
+ * Delete.
+ *
+ * @param sourceID the source ID
+ * @param transId the trans id
+ * @param path the path
+ * @throws AAIException the AAI exception
+ */
+ public void Delete(String sourceID, String transId, String path, int port) throws AAIException {
+ String methodName = "Delete";
+ String url = "";
+ transId += ":" + UUID.randomUUID().toString();
+
+ LoggingContext.save();
+ LoggingContext.partnerName(sourceID);
+ LoggingContext.targetEntity(TARGET_NAME);
+ LoggingContext.requestId(transId);
+ LoggingContext.serviceName(methodName);
+ LoggingContext.targetServiceName(methodName);
+
+ LOGGER.debug(methodName + " start");
+
+ initRestClient();
+ String request = "{}";
+ if (overrideLocalHost == null) {
+ overrideLocalHost = AAIConfig.get(AAIConstants.AAI_LOCAL_OVERRIDE, AAIConstants.AAI_LOCAL_OVERRIDE_DEFAULT);
+ }
+ if (AAIConstants.AAI_LOCAL_OVERRIDE_DEFAULT.equals(overrideLocalHost)) {
+ url = String.format(AAIConstants.AAI_LOCAL_REST, port,
+ AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP)) + path;
+ } else {
+ url = String.format(AAIConstants.AAI_LOCAL_REST_OVERRIDE, overrideLocalHost,
+ AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP)) + path;
+ }
+ ClientResponse cres = client.resource(url).accept("application/json").header("X-TransactionId", transId)
+ .header("X-FromAppId", sourceID).header("Real-Time", "true").type("application/json").entity(request)
+ .delete(ClientResponse.class);
+
+ if (cres.getStatus() == 404) { // resource not found
+ LOGGER.info("Resource does not exist...: " + cres.getStatus() + ":" + cres.getEntity(String.class));
+ LoggingContext.restore();
+ } else if (cres.getStatus() == 200 || cres.getStatus() == 204) {
+ LOGGER.info("Resource " + url + " deleted");
+ LoggingContext.restore();
+ } else {
+ LOGGER.error("Deleting Resource failed: " + cres.getStatus() + ":" + cres.getEntity(String.class));
+ LoggingContext.restore();
throw new AAIException("AAI_7116", "Error during DELETE");
- }
- }
-
- public <T> String Post(T t, String sourceID, String transId, String path) throws Exception {
- return Post(t, sourceID, transId, path, AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP));
- }
+ }
+ }
+
+ public <T> String Post(T t, String sourceID, String transId, String path) throws Exception {
+ return Post(t, sourceID, transId, path, AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP));
+ }
+
/**
* Post.
*
@@ -443,55 +435,48 @@ public class RestController implements RestControllerInterface {
* @return the string
* @throws Exception the exception
*/
- public <T> String Post(T t, String sourceID, String transId, String path, String apiVersion) throws Exception {
+ public <T> String Post(T t, String sourceID, String transId, String path, String apiVersion) throws Exception {
String methodName = "Post";
- String url="";
+ String url = "";
transId += ":" + UUID.randomUUID().toString();
-
+
LoggingContext.save();
LoggingContext.partnerName(sourceID);
- LoggingContext.targetEntity(TARGET_NAME);
- LoggingContext.requestId(transId);
- LoggingContext.serviceName(methodName);
- LoggingContext.targetServiceName(methodName);
-
- LOGGER.debug(methodName + " start");
-
+ LoggingContext.targetEntity(TARGET_NAME);
+ LoggingContext.requestId(transId);
+ LoggingContext.serviceName(methodName);
+ LoggingContext.targetServiceName(methodName);
+
+ LOGGER.debug(methodName + " start");
+
try {
-
- initRestClient();
+
+ initRestClient();
url = AAIConfig.get(AAIConstants.AAI_SERVER_URL_BASE) + apiVersion + "/" + path;
-
- ClientResponse cres = client.resource(url)
- .accept("application/json")
- .header("X-TransactionId", transId)
- .header("X-FromAppId", sourceID)
- .header("Real-Time", "true")
- .type("application/json")
- .entity(t)
- .post(ClientResponse.class);
-
+
+ ClientResponse cres = client.resource(url).accept("application/json").header("X-TransactionId", transId)
+ .header("X-FromAppId", sourceID).header("Real-Time", "true").type("application/json").entity(t)
+ .post(ClientResponse.class);
+
int statuscode = cres.getStatus();
- if ( statuscode >= 200 && statuscode <= 299 ) {
- LOGGER.debug(methodName + "REST api POST was successful!");
- return cres.getEntity(String.class);
- } else {
- throw new AAIException("AAI_7116", methodName +" with status="+statuscode+", url="+url + ", msg=" + cres.getEntity(String.class));
- }
-
+ if (statuscode >= 200 && statuscode <= 299) {
+ LOGGER.debug(methodName + "REST api POST was successful!");
+ return cres.getEntity(String.class);
+ } else {
+ throw new AAIException("AAI_7116", methodName + " with status=" + statuscode + ", url=" + url + ", msg="
+ + cres.getEntity(String.class));
+ }
+
} catch (AAIException e) {
- throw new AAIException("AAI_7116", methodName + " with url="+url+ ", Exception: " + e.toString());
- } catch (Exception e)
- {
- throw new AAIException("AAI_7116", methodName + " with url="+url+ ", Exception: " + e.toString());
-
- }
- finally {
- LoggingContext.restore();
+ throw new AAIException("AAI_7116", methodName + " with url=" + url + ", Exception: " + e.toString());
+ } catch (Exception e) {
+ throw new AAIException("AAI_7116", methodName + " with url=" + url + ", Exception: " + e.toString());
+
+ } finally {
+ LoggingContext.restore();
}
}
-
/**
* Gets the single instance of RestController.
*
@@ -501,11 +486,10 @@ public class RestController implements RestControllerInterface {
* @throws IllegalAccessException the illegal access exception
* @throws InstantiationException the instantiation exception
*/
- public <T> T getInstance(Class<T> clazz) throws IllegalAccessException, InstantiationException
- {
- return clazz.newInstance();
- }
-
+ public <T> T getInstance(Class<T> clazz) throws IllegalAccessException, InstantiationException {
+ return clazz.newInstance();
+ }
+
/**
* Does resource exist.
*
@@ -517,122 +501,120 @@ public class RestController implements RestControllerInterface {
* @return the t
*/
/*
- * DoesResourceExist
- *
- * To check whether a resource exist or get a copy of the existing version of the resource
- *
- * Resourcepath: should contain the qualified resource path (including encoded unique key identifier value),
- * resourceClassName: is the canonical name of the resource class name,
- * fromAppId:
- * transId:
- *
- * Will return null (if the resource doesn’t exist) (or)
- * Will return the specified resource from the Graph.
- *
- * Example:
- * LogicalLink llink = new LogicalLink();
- * String resourceClassName = llink.getClass().getCanonicalName();
- * llink = RestController.DoesResourceExist("network/logical-links/logical-link/" + <encoded-link-name>, resourceClassName, fromAppId, transId);
- */
- public <T> T DoesResourceExist(String resourcePath, String resourceClassName, String fromAppId, String transId) {
-
- try {
-
- RestObject<T> restObj = new RestObject<T>();
- @SuppressWarnings("unchecked")
- T resourceObj = (T)getInstance(Class.forName(resourceClassName));
- restObj.set(resourceObj);
- Get(resourceObj, fromAppId, transId, resourcePath, restObj, false, AAIConstants.AAI_RESOURCES_PORT);
-
- resourceObj = restObj.get();
- if (resourceObj != null)
- return resourceObj;
-
- } catch (AAIException e) {
-
- } catch (ClientHandlerException che) {
-
- }catch (Exception e) {
-
- }
-
- return null;
- }
-
- /**
- * Patch.
- *
- * @param <T> the generic type
- * @param sourceID the source ID
- * @param transId the trans id
- * @param path the path
- * @throws AAIException the AAI exception
- */
- public <T> void Patch(T t, String sourceID, String transId, String path) throws AAIException {
- String methodName = "Patch";
- String url="";
- transId += ":" + UUID.randomUUID().toString();
-
- LoggingContext.save();
- LoggingContext.partnerName(sourceID);
- LoggingContext.targetEntity(TARGET_NAME);
- LoggingContext.requestId(transId);
- LoggingContext.serviceName(methodName);
- LoggingContext.targetServiceName(methodName);
-
-
- int numRetries = 5;
- ClientResponse cres = null;
- int statusCode = -1;
-
- try {
- if ( overrideLocalHost == null ) {
- overrideLocalHost = AAIConfig.get(AAIConstants.AAI_LOCAL_OVERRIDE, AAIConstants.AAI_LOCAL_OVERRIDE_DEFAULT);
- }
- if ( AAIConstants.AAI_LOCAL_OVERRIDE_DEFAULT.equals(overrideLocalHost )) {
- url = String.format(AAIConstants.AAI_LOCAL_REST, AAIConstants.AAI_RESOURCES_PORT, AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP)) + path;
- } else {
- url = String.format(AAIConstants.AAI_LOCAL_REST_OVERRIDE, overrideLocalHost, AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP)) + path;
- }
-
- initRestClient();
- do {
-
- cres = client.resource(url)
- .accept("application/json")
- .header("X-TransactionId", transId)
- .header("X-FromAppId", sourceID)
- .header("X-HTTP-Method-Override", "PATCH")
- .type("application/merge-patch+json")
- .entity(t)
- .post(ClientResponse.class);
-
- statusCode = cres.getStatus();
-
- if ( statusCode >= 200 && statusCode <= 299 ) {
- LOGGER.debug(methodName + "REST api PATCH was successful!");
- return;
- } else {
- LOGGER.debug(methodName + "Unable to make the patch request to url " + url + " so retrying");
- }
-
- numRetries--;
-
- } while(numRetries >= 0);
-
- LOGGER.debug(methodName + "Unable to make the patch request to url " + url + " even after trying = " + numRetries + " times.");
- throw new AAIException("AAI_7116", methodName +" with status="+statusCode+", url="+url + ", msg=" + cres.getEntity(String.class));
-
- } catch (AAIException e) {
- throw new AAIException("AAI_7116", methodName + " with url="+url+ ", Exception: " + e.toString());
- } catch (Exception e)
- {
- throw new AAIException("AAI_7116", methodName + " with url="+url+ ", Exception: " + e.toString());
-
- }
- finally {
- LoggingContext.restore();
- }
-
- }
+ * DoesResourceExist
+ *
+ * To check whether a resource exist or get a copy of the existing version of the resource
+ *
+ * Resourcepath: should contain the qualified resource path (including encoded unique key identifier value),
+ * resourceClassName: is the canonical name of the resource class name,
+ * fromAppId:
+ * transId:
+ *
+ * Will return null (if the resource doesn’t exist) (or)
+ * Will return the specified resource from the Graph.
+ *
+ * Example:
+ * LogicalLink llink = new LogicalLink();
+ * String resourceClassName = llink.getClass().getCanonicalName();
+ * llink = RestController.DoesResourceExist("network/logical-links/logical-link/" + <encoded-link-name>,
+ * resourceClassName, fromAppId, transId);
+ */
+ public <T> T DoesResourceExist(String resourcePath, String resourceClassName, String fromAppId, String transId) {
+
+ try {
+
+ RestObject<T> restObj = new RestObject<T>();
+ @SuppressWarnings("unchecked")
+ T resourceObj = (T) getInstance(Class.forName(resourceClassName));
+ restObj.set(resourceObj);
+ Get(resourceObj, fromAppId, transId, resourcePath, restObj, false, AAIConstants.AAI_RESOURCES_PORT);
+
+ resourceObj = restObj.get();
+ if (resourceObj != null)
+ return resourceObj;
+
+ } catch (AAIException e) {
+
+ } catch (ClientHandlerException che) {
+
+ } catch (Exception e) {
+
+ }
+
+ return null;
+ }
+
+ /**
+ * Patch.
+ *
+ * @param <T> the generic type
+ * @param sourceID the source ID
+ * @param transId the trans id
+ * @param path the path
+ * @throws AAIException the AAI exception
+ */
+ public <T> void Patch(T t, String sourceID, String transId, String path) throws AAIException {
+ String methodName = "Patch";
+ String url = "";
+ transId += ":" + UUID.randomUUID().toString();
+
+ LoggingContext.save();
+ LoggingContext.partnerName(sourceID);
+ LoggingContext.targetEntity(TARGET_NAME);
+ LoggingContext.requestId(transId);
+ LoggingContext.serviceName(methodName);
+ LoggingContext.targetServiceName(methodName);
+
+ int numRetries = 5;
+ ClientResponse cres = null;
+ int statusCode = -1;
+
+ try {
+ if (overrideLocalHost == null) {
+ overrideLocalHost =
+ AAIConfig.get(AAIConstants.AAI_LOCAL_OVERRIDE, AAIConstants.AAI_LOCAL_OVERRIDE_DEFAULT);
+ }
+ if (AAIConstants.AAI_LOCAL_OVERRIDE_DEFAULT.equals(overrideLocalHost)) {
+ url = String.format(AAIConstants.AAI_LOCAL_REST, AAIConstants.AAI_RESOURCES_PORT,
+ AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP)) + path;
+ } else {
+ url = String.format(AAIConstants.AAI_LOCAL_REST_OVERRIDE, overrideLocalHost,
+ AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP)) + path;
+ }
+
+ initRestClient();
+ do {
+
+ cres = client.resource(url).accept("application/json").header("X-TransactionId", transId)
+ .header("X-FromAppId", sourceID).header("X-HTTP-Method-Override", "PATCH")
+ .type("application/merge-patch+json").entity(t).post(ClientResponse.class);
+
+ statusCode = cres.getStatus();
+
+ if (statusCode >= 200 && statusCode <= 299) {
+ LOGGER.debug(methodName + "REST api PATCH was successful!");
+ return;
+ } else {
+ LOGGER.debug(methodName + "Unable to make the patch request to url " + url + " so retrying");
+ }
+
+ numRetries--;
+
+ } while (numRetries >= 0);
+
+ LOGGER.debug(methodName + "Unable to make the patch request to url " + url + " even after trying = "
+ + numRetries + " times.");
+ throw new AAIException("AAI_7116", methodName + " with status=" + statusCode + ", url=" + url + ", msg="
+ + cres.getEntity(String.class));
+
+ } catch (AAIException e) {
+ throw new AAIException("AAI_7116", methodName + " with url=" + url + ", Exception: " + e.toString());
+ } catch (Exception e) {
+ throw new AAIException("AAI_7116", methodName + " with url=" + url + ", Exception: " + e.toString());
+
+ } finally {
+ LoggingContext.restore();
+ }
+
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/util/RestControllerInterface.java b/aai-core/src/main/java/org/onap/aai/util/RestControllerInterface.java
index d7061188..f5eed42d 100644
--- a/aai-core/src/main/java/org/onap/aai/util/RestControllerInterface.java
+++ b/aai-core/src/main/java/org/onap/aai/util/RestControllerInterface.java
@@ -17,17 +17,19 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-package org.onap.aai.util;
-import org.onap.aai.util.RestObject;
+package org.onap.aai.util;
import org.onap.aai.exceptions.AAIException;
+import org.onap.aai.util.RestObject;
public interface RestControllerInterface {
- public <T> void Get(T t, String sourceID, String transId, String path, RestObject<T> restObject, boolean oldserver) throws AAIException;
+ public <T> void Get(T t, String sourceID, String transId, String path, RestObject<T> restObject, boolean oldserver)
+ throws AAIException;
- public <T> void Get(T t, String sourceID, String transId, String path, RestObject<T> restObject, String apiVersion) throws AAIException;
+ public <T> void Get(T t, String sourceID, String transId, String path, RestObject<T> restObject, String apiVersion)
+ throws AAIException;
public <T> void Patch(T t, String sourceID, String transId, String path) throws AAIException;
@@ -39,5 +41,5 @@ public interface RestControllerInterface {
public <T> T getInstance(Class<T> clazz) throws IllegalAccessException, InstantiationException;
- public <T> T DoesResourceExist(String resourcePath, String resourceClassName, String fromAppId, String transId) ;
-} \ No newline at end of file
+ public <T> T DoesResourceExist(String resourcePath, String resourceClassName, String fromAppId, String transId);
+}
diff --git a/aai-core/src/main/java/org/onap/aai/util/RestObject.java b/aai-core/src/main/java/org/onap/aai/util/RestObject.java
index f367c2e6..a45bfeb0 100644
--- a/aai-core/src/main/java/org/onap/aai/util/RestObject.java
+++ b/aai-core/src/main/java/org/onap/aai/util/RestObject.java
@@ -17,14 +17,16 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.util;
public class RestObject<T> {
- /**
- * Generic version of the RestObject class.
- * @param <T> the type of the value being called for the Rest object interface
- */
+ /**
+ * Generic version of the RestObject class.
+ *
+ * @param <T> the type of the value being called for the Rest object interface
+ */
// T stands for "Type"
private T t;
@@ -33,13 +35,17 @@ public class RestObject<T> {
*
* @param t the t
*/
- public void set(T t) { this.t = t; }
-
+ public void set(T t) {
+ this.t = t;
+ }
+
/**
* Gets the.
*
* @return the t
*/
- public T get() { return t; }
-
+ public T get() {
+ return t;
+ }
+
}
diff --git a/aai-core/src/main/java/org/onap/aai/util/RestURLEncoder.java b/aai-core/src/main/java/org/onap/aai/util/RestURLEncoder.java
index 94cce9b7..c6d2b7cf 100644
--- a/aai-core/src/main/java/org/onap/aai/util/RestURLEncoder.java
+++ b/aai-core/src/main/java/org/onap/aai/util/RestURLEncoder.java
@@ -17,24 +17,23 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.util;
import java.io.UnsupportedEncodingException;
-import org.springframework.web.util.UriUtils;
+import org.springframework.web.util.UriUtils;
public class RestURLEncoder {
-
- /**
- * Encode URL.
- *
- * @param nodeKey the node key
- * @return the string
- * @throws UnsupportedEncodingException the unsupported encoding exception
- */
- public static final String encodeURL (String nodeKey) throws UnsupportedEncodingException {
- return UriUtils.encode(nodeKey, "UTF-8").replaceAll("\\+", "%20");
- }
+ /**
+ * Encode URL.
+ *
+ * @param nodeKey the node key
+ * @return the string
+ * @throws UnsupportedEncodingException the unsupported encoding exception
+ */
+ public static final String encodeURL(String nodeKey) throws UnsupportedEncodingException {
+ return UriUtils.encode(nodeKey, "UTF-8").replaceAll("\\+", "%20");
+ }
}
-
diff --git a/aai-core/src/main/java/org/onap/aai/util/StoreNotificationEvent.java b/aai-core/src/main/java/org/onap/aai/util/StoreNotificationEvent.java
index 1f3341b8..8b2bf50a 100644
--- a/aai-core/src/main/java/org/onap/aai/util/StoreNotificationEvent.java
+++ b/aai-core/src/main/java/org/onap/aai/util/StoreNotificationEvent.java
@@ -17,16 +17,18 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.util;
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
+
import java.io.StringWriter;
import java.util.Iterator;
import java.util.UUID;
import javax.xml.bind.Marshaller;
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
import org.eclipse.persistence.dynamic.DynamicEntity;
import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext;
import org.json.JSONException;
@@ -44,311 +46,316 @@ import org.springframework.core.env.Environment;
public class StoreNotificationEvent {
private static final EELFLogger logger = EELFManager.getInstance().getLogger(StoreNotificationEvent.class);
-
- private MessageProducer messageProducer;
- private String fromAppId = "";
- private String transId = "";
- private final String transactionId;
- private final String sourceOfTruth;
-
- private ApplicationContext context;
- private Environment env;
-
- /**
- * Instantiates a new store notification event.
- */
- public StoreNotificationEvent(String transactionId, String sourceOfTruth) {
- this.messageProducer = new AAIDmaapEventJMSProducer();
- this.transactionId = transactionId;
- this.sourceOfTruth = sourceOfTruth;
- }
-
- public StoreNotificationEvent(AAIDmaapEventJMSProducer producer, String transactionId, String sourceOfTruth) {
- this.messageProducer = producer;
- this.transactionId = transactionId;
- this.sourceOfTruth = sourceOfTruth;
- }
-
- /**
- * Store event.
- *
- * @param eh
- * the eh
- * @param obj
- * the obj
- * @throws AAIException
- * the AAI exception
- */
- public String storeEvent(NotificationEvent.EventHeader eh, Object obj) throws AAIException {
-
- if (obj == null) {
- throw new AAIException("AAI_7350");
- }
-
- org.onap.aai.domain.notificationEvent.ObjectFactory factory = new org.onap.aai.domain.notificationEvent.ObjectFactory();
-
- org.onap.aai.domain.notificationEvent.NotificationEvent ne = factory.createNotificationEvent();
-
- if (eh.getId() == null) {
- eh.setId(genDate2() + "-" + UUID.randomUUID().toString());
- }
- if (eh.getTimestamp() == null) {
- eh.setTimestamp(genDate());
- }
-
- // there's no default, but i think we want to put this in hbase?
-
- if (eh.getEntityLink() == null) {
- eh.setEntityLink("UNK");
- }
-
- if (eh.getAction() == null) {
- eh.setAction("UNK");
- }
-
- if (eh.getEventType() == null) {
- eh.setEventType(AAIConfig.get("aai.notificationEvent.default.eventType", "UNK"));
- }
-
- if (eh.getDomain() == null) {
- eh.setDomain(AAIConfig.get("aai.notificationEvent.default.domain", "UNK"));
- }
-
- if (eh.getSourceName() == null) {
- eh.setSourceName(AAIConfig.get("aai.notificationEvent.default.sourceName", "UNK"));
- }
-
- if (eh.getSequenceNumber() == null) {
- eh.setSequenceNumber(AAIConfig.get("aai.notificationEvent.default.sequenceNumber", "UNK"));
- }
-
- if (eh.getSeverity() == null) {
- eh.setSeverity(AAIConfig.get("aai.notificationEvent.default.severity", "UNK"));
- }
-
- if (eh.getVersion() == null) {
- eh.setVersion(AAIConfig.get("aai.notificationEvent.default.version", "UNK"));
- }
-
- ne.setCambriaPartition(AAIConstants.UEB_PUB_PARTITION_AAI);
- ne.setEventHeader(eh);
- ne.setEntity(obj);
-
- try {
- PojoUtils pu = new PojoUtils();
- String entityJson = pu.getJsonFromObject(ne);
- sendToDmaapJmsQueue(entityJson);
- return entityJson;
- } catch (Exception e) {
- throw new AAIException("AAI_7350", e);
- }
- }
-
- /**
- * Store dynamic event.
- *
- * @param notificationJaxbContext
- * the notification jaxb context
- * @param notificationVersion
- * the notification version
- * @param eventHeader
- * the event header
- * @param obj
- * the obj
- * @throws AAIException
- * the AAI exception
- */
- public void storeDynamicEvent(DynamicJAXBContext notificationJaxbContext, String notificationVersion, DynamicEntity eventHeader, DynamicEntity obj) throws AAIException {
-
- if (obj == null) {
- throw new AAIException("AAI_7350");
- }
-
- DynamicEntity notificationEvent = notificationJaxbContext.getDynamicType("inventory.aai.onap.org." + notificationVersion + ".NotificationEvent").newDynamicEntity();
-
- if (eventHeader.get("id") == null) {
- eventHeader.set("id", genDate2() + "-" + UUID.randomUUID().toString());
- }
-
- if (eventHeader.get("timestamp") == null) {
- eventHeader.set("timestamp", genDate());
- }
-
- if (eventHeader.get("entityLink") == null) {
- eventHeader.set("entityLink", "UNK");
- }
-
- if (eventHeader.get("action") == null) {
- eventHeader.set("action", "UNK");
- }
-
- if (eventHeader.get("eventType") == null) {
- eventHeader.set("eventType", AAIConfig.get("aai.notificationEvent.default.eventType", "UNK"));
- }
-
- if (eventHeader.get("domain") == null) {
- eventHeader.set("domain", AAIConfig.get("aai.notificationEvent.default.domain", "UNK"));
- }
-
- if (eventHeader.get("sourceName") == null) {
- eventHeader.set("sourceName", AAIConfig.get("aai.notificationEvent.default.sourceName", "UNK"));
- }
-
- if (eventHeader.get("sequenceNumber") == null) {
- eventHeader.set("sequenceNumber", AAIConfig.get("aai.notificationEvent.default.sequenceNumber", "UNK"));
- }
-
- if (eventHeader.get("severity") == null) {
- eventHeader.set("severity", AAIConfig.get("aai.notificationEvent.default.severity", "UNK"));
- }
-
- if (eventHeader.get("version") == null) {
- eventHeader.set("version", AAIConfig.get("aai.notificationEvent.default.version", "UNK"));
- }
-
- if (notificationEvent.get("cambriaPartition") == null) {
- notificationEvent.set("cambriaPartition", AAIConstants.UEB_PUB_PARTITION_AAI);
- }
-
- notificationEvent.set("eventHeader", eventHeader);
- notificationEvent.set("entity", obj);
-
- try {
- StringWriter result = new StringWriter();
-
- Marshaller marshaller = notificationJaxbContext.createMarshaller();
- marshaller.setProperty(org.eclipse.persistence.jaxb.MarshallerProperties.MEDIA_TYPE, "application/json");
- marshaller.setProperty(org.eclipse.persistence.jaxb.MarshallerProperties.JSON_INCLUDE_ROOT, false);
- marshaller.setProperty(org.eclipse.persistence.jaxb.MarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, false);
- marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, false);
- marshaller.marshal(notificationEvent, result);
- this.sendToDmaapJmsQueue(result.toString());
-
- } catch (Exception e) {
- throw new AAIException("AAI_7350", e);
- }
- }
-
- public String storeEvent(Loader loader, Introspector eventHeader, Introspector obj) throws AAIException {
- if (obj == null) {
- throw new AAIException("AAI_7350");
- }
-
- try {
- final Introspector notificationEvent = loader.introspectorFromName("notification-event");
-
- if (eventHeader.getValue("id") == null) {
- eventHeader.setValue("id", genDate2() + "-" + UUID.randomUUID().toString());
- }
-
- if (eventHeader.getValue("timestamp") == null) {
- eventHeader.setValue("timestamp", genDate());
- }
-
- if (eventHeader.getValue("entity-link") == null) {
- eventHeader.setValue("entity-link", "UNK");
- }
-
- if (eventHeader.getValue("action") == null) {
- eventHeader.setValue("action", "UNK");
- }
-
- if (eventHeader.getValue("event-type") == null) {
- eventHeader.setValue("event-type", AAIConfig.get("aai.notificationEvent.default.eventType", "UNK"));
- }
-
- if (eventHeader.getValue("domain") == null) {
- eventHeader.setValue("domain", AAIConfig.get("aai.notificationEvent.default.domain", "UNK"));
- }
-
- if (eventHeader.getValue("source-name") == null) {
- eventHeader.setValue("source-name", AAIConfig.get("aai.notificationEvent.default.sourceName", "UNK"));
- }
-
- if (eventHeader.getValue("sequence-number") == null) {
- eventHeader.setValue("sequence-number", AAIConfig.get("aai.notificationEvent.default.sequenceNumber", "UNK"));
- }
-
- if (eventHeader.getValue("severity") == null) {
- eventHeader.setValue("severity", AAIConfig.get("aai.notificationEvent.default.severity", "UNK"));
- }
-
- if (eventHeader.getValue("version") == null) {
- eventHeader.setValue("version", AAIConfig.get("aai.notificationEvent.default.version", "UNK"));
- }
-
- if (notificationEvent.getValue("cambria-partition") == null) {
- notificationEvent.setValue("cambria-partition", AAIConfig.get("aai.notificationEvent.default.partition", AAIConstants.UEB_PUB_PARTITION_AAI));
- }
-
- notificationEvent.setValue("event-header", eventHeader.getUnderlyingObject());
- notificationEvent.setValue("entity", obj.getUnderlyingObject());
-
- String entityJson = notificationEvent.marshal(false);
- sendToDmaapJmsQueue(entityJson);
- return entityJson;
- } catch (JSONException e) {
- throw new AAIException("AAI_7350", e);
- } catch (AAIUnknownObjectException e) {
- throw new AAIException("AAI_7350", e);
- }
- }
-
- private void sendToDmaapJmsQueue(String entityString) throws JSONException {
-
-
- JSONObject entityJsonObject = new JSONObject(entityString);
-
- JSONObject entityJsonObjectUpdated = new JSONObject();
- JSONObject finalJson = new JSONObject();
-
- JSONObject entityHeader = entityJsonObject.getJSONObject("event-header");
- String cambriaPartition = entityJsonObject.getString("cambria.partition");
-
- entityJsonObject.remove("event-header");
- entityJsonObject.remove("cambria.partition");
-
- entityJsonObjectUpdated.put("event-header", entityHeader);
- entityJsonObjectUpdated.put("cambria.partition", cambriaPartition);
-
- String transId = entityHeader.getString("id");
- String fromAppId = entityHeader.getString("source-name");
-
- Iterator<String> iter = entityJsonObject.keys();
- JSONObject entity = new JSONObject();
- if (iter.hasNext()) {
- entity = entityJsonObject.getJSONObject(iter.next());
- }
-
- entityJsonObjectUpdated.put("entity", entity);
-
- finalJson.put("event-topic", "AAI-EVENT");
- finalJson.put("transId", transId);
- finalJson.put("fromAppId", fromAppId);
- finalJson.put("fullId", "");
- finalJson.put("aaiEventPayload", entityJsonObjectUpdated);
-
- messageProducer.sendMessageToDefaultDestination(finalJson);
- }
-
- /**
- * Gen date.
- *
- * @return the string
- */
- public static String genDate() {
- FormatDate fd = new FormatDate("YYYYMMdd-HH:mm:ss:SSS");
- return fd.getDateTime();
- }
-
- /**
- * Gen date 2.
- *
- * @return the string
- */
- public static String genDate2() {
- FormatDate fd = new FormatDate("YYYYMMddHHmmss");
- return fd.getDateTime();
- }
+
+ private MessageProducer messageProducer;
+ private String fromAppId = "";
+ private String transId = "";
+ private final String transactionId;
+ private final String sourceOfTruth;
+
+ private ApplicationContext context;
+ private Environment env;
+
+ /**
+ * Instantiates a new store notification event.
+ */
+ public StoreNotificationEvent(String transactionId, String sourceOfTruth) {
+ this.messageProducer = new AAIDmaapEventJMSProducer();
+ this.transactionId = transactionId;
+ this.sourceOfTruth = sourceOfTruth;
+ }
+
+ public StoreNotificationEvent(AAIDmaapEventJMSProducer producer, String transactionId, String sourceOfTruth) {
+ this.messageProducer = producer;
+ this.transactionId = transactionId;
+ this.sourceOfTruth = sourceOfTruth;
+ }
+
+ /**
+ * Store event.
+ *
+ * @param eh
+ * the eh
+ * @param obj
+ * the obj
+ * @throws AAIException
+ * the AAI exception
+ */
+ public String storeEvent(NotificationEvent.EventHeader eh, Object obj) throws AAIException {
+
+ if (obj == null) {
+ throw new AAIException("AAI_7350");
+ }
+
+ org.onap.aai.domain.notificationEvent.ObjectFactory factory =
+ new org.onap.aai.domain.notificationEvent.ObjectFactory();
+
+ org.onap.aai.domain.notificationEvent.NotificationEvent ne = factory.createNotificationEvent();
+
+ if (eh.getId() == null) {
+ eh.setId(genDate2() + "-" + UUID.randomUUID().toString());
+ }
+ if (eh.getTimestamp() == null) {
+ eh.setTimestamp(genDate());
+ }
+
+ // there's no default, but i think we want to put this in hbase?
+
+ if (eh.getEntityLink() == null) {
+ eh.setEntityLink("UNK");
+ }
+
+ if (eh.getAction() == null) {
+ eh.setAction("UNK");
+ }
+
+ if (eh.getEventType() == null) {
+ eh.setEventType(AAIConfig.get("aai.notificationEvent.default.eventType", "UNK"));
+ }
+
+ if (eh.getDomain() == null) {
+ eh.setDomain(AAIConfig.get("aai.notificationEvent.default.domain", "UNK"));
+ }
+
+ if (eh.getSourceName() == null) {
+ eh.setSourceName(AAIConfig.get("aai.notificationEvent.default.sourceName", "UNK"));
+ }
+
+ if (eh.getSequenceNumber() == null) {
+ eh.setSequenceNumber(AAIConfig.get("aai.notificationEvent.default.sequenceNumber", "UNK"));
+ }
+
+ if (eh.getSeverity() == null) {
+ eh.setSeverity(AAIConfig.get("aai.notificationEvent.default.severity", "UNK"));
+ }
+
+ if (eh.getVersion() == null) {
+ eh.setVersion(AAIConfig.get("aai.notificationEvent.default.version", "UNK"));
+ }
+
+ ne.setCambriaPartition(AAIConstants.UEB_PUB_PARTITION_AAI);
+ ne.setEventHeader(eh);
+ ne.setEntity(obj);
+
+ try {
+ PojoUtils pu = new PojoUtils();
+ String entityJson = pu.getJsonFromObject(ne);
+ sendToDmaapJmsQueue(entityJson);
+ return entityJson;
+ } catch (Exception e) {
+ throw new AAIException("AAI_7350", e);
+ }
+ }
+
+ /**
+ * Store dynamic event.
+ *
+ * @param notificationJaxbContext
+ * the notification jaxb context
+ * @param notificationVersion
+ * the notification version
+ * @param eventHeader
+ * the event header
+ * @param obj
+ * the obj
+ * @throws AAIException
+ * the AAI exception
+ */
+ public void storeDynamicEvent(DynamicJAXBContext notificationJaxbContext, String notificationVersion,
+ DynamicEntity eventHeader, DynamicEntity obj) throws AAIException {
+
+ if (obj == null) {
+ throw new AAIException("AAI_7350");
+ }
+
+ DynamicEntity notificationEvent = notificationJaxbContext
+ .getDynamicType("inventory.aai.onap.org." + notificationVersion + ".NotificationEvent")
+ .newDynamicEntity();
+
+ if (eventHeader.get("id") == null) {
+ eventHeader.set("id", genDate2() + "-" + UUID.randomUUID().toString());
+ }
+
+ if (eventHeader.get("timestamp") == null) {
+ eventHeader.set("timestamp", genDate());
+ }
+
+ if (eventHeader.get("entityLink") == null) {
+ eventHeader.set("entityLink", "UNK");
+ }
+
+ if (eventHeader.get("action") == null) {
+ eventHeader.set("action", "UNK");
+ }
+
+ if (eventHeader.get("eventType") == null) {
+ eventHeader.set("eventType", AAIConfig.get("aai.notificationEvent.default.eventType", "UNK"));
+ }
+
+ if (eventHeader.get("domain") == null) {
+ eventHeader.set("domain", AAIConfig.get("aai.notificationEvent.default.domain", "UNK"));
+ }
+
+ if (eventHeader.get("sourceName") == null) {
+ eventHeader.set("sourceName", AAIConfig.get("aai.notificationEvent.default.sourceName", "UNK"));
+ }
+
+ if (eventHeader.get("sequenceNumber") == null) {
+ eventHeader.set("sequenceNumber", AAIConfig.get("aai.notificationEvent.default.sequenceNumber", "UNK"));
+ }
+
+ if (eventHeader.get("severity") == null) {
+ eventHeader.set("severity", AAIConfig.get("aai.notificationEvent.default.severity", "UNK"));
+ }
+
+ if (eventHeader.get("version") == null) {
+ eventHeader.set("version", AAIConfig.get("aai.notificationEvent.default.version", "UNK"));
+ }
+
+ if (notificationEvent.get("cambriaPartition") == null) {
+ notificationEvent.set("cambriaPartition", AAIConstants.UEB_PUB_PARTITION_AAI);
+ }
+
+ notificationEvent.set("eventHeader", eventHeader);
+ notificationEvent.set("entity", obj);
+
+ try {
+ StringWriter result = new StringWriter();
+
+ Marshaller marshaller = notificationJaxbContext.createMarshaller();
+ marshaller.setProperty(org.eclipse.persistence.jaxb.MarshallerProperties.MEDIA_TYPE, "application/json");
+ marshaller.setProperty(org.eclipse.persistence.jaxb.MarshallerProperties.JSON_INCLUDE_ROOT, false);
+ marshaller.setProperty(org.eclipse.persistence.jaxb.MarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, false);
+ marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, false);
+ marshaller.marshal(notificationEvent, result);
+ this.sendToDmaapJmsQueue(result.toString());
+
+ } catch (Exception e) {
+ throw new AAIException("AAI_7350", e);
+ }
+ }
+
+ public String storeEvent(Loader loader, Introspector eventHeader, Introspector obj) throws AAIException {
+ if (obj == null) {
+ throw new AAIException("AAI_7350");
+ }
+
+ try {
+ final Introspector notificationEvent = loader.introspectorFromName("notification-event");
+
+ if (eventHeader.getValue("id") == null) {
+ eventHeader.setValue("id", genDate2() + "-" + UUID.randomUUID().toString());
+ }
+
+ if (eventHeader.getValue("timestamp") == null) {
+ eventHeader.setValue("timestamp", genDate());
+ }
+
+ if (eventHeader.getValue("entity-link") == null) {
+ eventHeader.setValue("entity-link", "UNK");
+ }
+
+ if (eventHeader.getValue("action") == null) {
+ eventHeader.setValue("action", "UNK");
+ }
+
+ if (eventHeader.getValue("event-type") == null) {
+ eventHeader.setValue("event-type", AAIConfig.get("aai.notificationEvent.default.eventType", "UNK"));
+ }
+
+ if (eventHeader.getValue("domain") == null) {
+ eventHeader.setValue("domain", AAIConfig.get("aai.notificationEvent.default.domain", "UNK"));
+ }
+
+ if (eventHeader.getValue("source-name") == null) {
+ eventHeader.setValue("source-name", AAIConfig.get("aai.notificationEvent.default.sourceName", "UNK"));
+ }
+
+ if (eventHeader.getValue("sequence-number") == null) {
+ eventHeader.setValue("sequence-number",
+ AAIConfig.get("aai.notificationEvent.default.sequenceNumber", "UNK"));
+ }
+
+ if (eventHeader.getValue("severity") == null) {
+ eventHeader.setValue("severity", AAIConfig.get("aai.notificationEvent.default.severity", "UNK"));
+ }
+
+ if (eventHeader.getValue("version") == null) {
+ eventHeader.setValue("version", AAIConfig.get("aai.notificationEvent.default.version", "UNK"));
+ }
+
+ if (notificationEvent.getValue("cambria-partition") == null) {
+ notificationEvent.setValue("cambria-partition",
+ AAIConfig.get("aai.notificationEvent.default.partition", AAIConstants.UEB_PUB_PARTITION_AAI));
+ }
+
+ notificationEvent.setValue("event-header", eventHeader.getUnderlyingObject());
+ notificationEvent.setValue("entity", obj.getUnderlyingObject());
+
+ String entityJson = notificationEvent.marshal(false);
+ sendToDmaapJmsQueue(entityJson);
+ return entityJson;
+ } catch (JSONException e) {
+ throw new AAIException("AAI_7350", e);
+ } catch (AAIUnknownObjectException e) {
+ throw new AAIException("AAI_7350", e);
+ }
+ }
+
+ private void sendToDmaapJmsQueue(String entityString) throws JSONException {
+
+ JSONObject entityJsonObject = new JSONObject(entityString);
+
+ JSONObject entityJsonObjectUpdated = new JSONObject();
+ JSONObject finalJson = new JSONObject();
+
+ JSONObject entityHeader = entityJsonObject.getJSONObject("event-header");
+ String cambriaPartition = entityJsonObject.getString("cambria.partition");
+
+ entityJsonObject.remove("event-header");
+ entityJsonObject.remove("cambria.partition");
+
+ entityJsonObjectUpdated.put("event-header", entityHeader);
+ entityJsonObjectUpdated.put("cambria.partition", cambriaPartition);
+
+ String transId = entityHeader.getString("id");
+ String fromAppId = entityHeader.getString("source-name");
+
+ Iterator<String> iter = entityJsonObject.keys();
+ JSONObject entity = new JSONObject();
+ if (iter.hasNext()) {
+ entity = entityJsonObject.getJSONObject(iter.next());
+ }
+
+ entityJsonObjectUpdated.put("entity", entity);
+
+ finalJson.put("event-topic", "AAI-EVENT");
+ finalJson.put("transId", transId);
+ finalJson.put("fromAppId", fromAppId);
+ finalJson.put("fullId", "");
+ finalJson.put("aaiEventPayload", entityJsonObjectUpdated);
+
+ messageProducer.sendMessageToDefaultDestination(finalJson);
+ }
+
+ /**
+ * Gen date.
+ *
+ * @return the string
+ */
+ public static String genDate() {
+ FormatDate fd = new FormatDate("YYYYMMdd-HH:mm:ss:SSS");
+ return fd.getDateTime();
+ }
+
+ /**
+ * Gen date 2.
+ *
+ * @return the string
+ */
+ public static String genDate2() {
+ FormatDate fd = new FormatDate("YYYYMMddHHmmss");
+ return fd.getDateTime();
+ }
}
diff --git a/aai-core/src/main/java/org/onap/aai/web/DmaapConfig.java b/aai-core/src/main/java/org/onap/aai/web/DmaapConfig.java
index 657656c4..078ca963 100644
--- a/aai-core/src/main/java/org/onap/aai/web/DmaapConfig.java
+++ b/aai-core/src/main/java/org/onap/aai/web/DmaapConfig.java
@@ -17,8 +17,11 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.web;
+import javax.annotation.PostConstruct;
+
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.command.ActiveMQQueue;
@@ -35,8 +38,6 @@ import org.springframework.http.HttpHeaders;
import org.springframework.jms.connection.CachingConnectionFactory;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.listener.DefaultMessageListenerContainer;
-
-import javax.annotation.PostConstruct;
import org.springframework.web.client.RestTemplate;
@Profile("dmaap")
@@ -58,7 +59,7 @@ public class DmaapConfig {
private String bindAddress;
@PostConstruct
- public void init(){
+ public void init() {
System.setProperty("activemq.tcp.url", bindAddress);
}
@@ -76,22 +77,22 @@ public class DmaapConfig {
}
@Bean(name = "connectionFactory")
- public ActiveMQConnectionFactory activeMQConnectionFactory(){
+ public ActiveMQConnectionFactory activeMQConnectionFactory() {
return new ActiveMQConnectionFactory(bindAddress);
}
@Bean
- public CachingConnectionFactory cachingConnectionFactory(){
+ public CachingConnectionFactory cachingConnectionFactory() {
return new CachingConnectionFactory(activeMQConnectionFactory());
}
@Bean(name = "destinationQueue")
- public ActiveMQQueue activeMQQueue(){
+ public ActiveMQQueue activeMQQueue() {
return new ActiveMQQueue("IN_QUEUE");
}
@Bean
- public JmsTemplate jmsTemplate(){
+ public JmsTemplate jmsTemplate() {
JmsTemplate jmsTemplate = new JmsTemplate();
jmsTemplate.setConnectionFactory(activeMQConnectionFactory());
@@ -101,11 +102,11 @@ public class DmaapConfig {
}
@Bean
- public AAIDmaapEventJMSProducer jmsProducer(){
+ public AAIDmaapEventJMSProducer jmsProducer() {
return new AAIDmaapEventJMSProducer();
}
- @Bean(name="jmsConsumer")
+ @Bean(name = "jmsConsumer")
public AAIDmaapEventJMSConsumer jmsConsumer() throws Exception {
return new AAIDmaapEventJMSConsumer(ctx.getEnvironment(), dmaapRestTemplate, dmaapHeaders);
}
diff --git a/aai-core/src/main/java/org/onap/aai/web/EventClientPublisher.java b/aai-core/src/main/java/org/onap/aai/web/EventClientPublisher.java
index 94d8f4cd..d552f231 100644
--- a/aai-core/src/main/java/org/onap/aai/web/EventClientPublisher.java
+++ b/aai-core/src/main/java/org/onap/aai/web/EventClientPublisher.java
@@ -17,10 +17,15 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.web;
import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
+
+import java.io.UnsupportedEncodingException;
+import java.util.Base64;
+
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
@@ -29,9 +34,6 @@ import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;
-import java.io.UnsupportedEncodingException;
-import java.util.Base64;
-
@Configuration
public class EventClientPublisher {
@@ -67,21 +69,20 @@ public class EventClientPublisher {
@Value("${dmaap.ribbon.contentType:application/json}")
private String contentType;
- @Bean(name="dmaapRestTemplate")
- public RestTemplate dmaapRestTemplate(){
+ @Bean(name = "dmaapRestTemplate")
+ public RestTemplate dmaapRestTemplate() {
return new RestTemplate();
}
- @Bean(name="dmaapHeaders")
- public HttpHeaders dmaapHeaders() throws UnsupportedEncodingException
- {
+ @Bean(name = "dmaapHeaders")
+ public HttpHeaders dmaapHeaders() throws UnsupportedEncodingException {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
- if(username != null && password != null){
+ if (username != null && password != null) {
- if(!StringUtils.EMPTY.equals(username) && !StringUtils.EMPTY.equals(password)){
+ if (!StringUtils.EMPTY.equals(username) && !StringUtils.EMPTY.equals(password)) {
byte[] userPass = (username + ":" + password).getBytes("UTF-8");
diff --git a/aai-core/src/main/java/org/onap/aai/workarounds/NamingExceptions.java b/aai-core/src/main/java/org/onap/aai/workarounds/NamingExceptions.java
index 435fa4dc..c140c48c 100644
--- a/aai-core/src/main/java/org/onap/aai/workarounds/NamingExceptions.java
+++ b/aai-core/src/main/java/org/onap/aai/workarounds/NamingExceptions.java
@@ -17,62 +17,63 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.workarounds;
public class NamingExceptions {
- /**
- * Instantiates a new naming exceptions.
- */
- private NamingExceptions() {
-
- }
-
- private static class Helper {
- private static final NamingExceptions INSTANCE = new NamingExceptions();
- }
-
- /**
- * Gets the single instance of NamingExceptions.
- *
- * @return single instance of NamingExceptions
- */
- public static NamingExceptions getInstance() {
- return Helper.INSTANCE;
- }
-
- /**
- * Gets the object name.
- *
- * @param name the name
- * @return the object name
- */
- public String getObjectName(String name) {
-
- String result = name;
-
- if (name.equals("cvlan-tag")) {
- result = "cvlan-tag-entry";
- }
-
- return result;
- }
-
- /**
- * Gets the DB name.
- *
- * @param name the name
- * @return the DB name
- */
- public String getDBName(String name) {
-
- String result = name;
-
- if (name.equals("cvlan-tag-entry")) {
- result = "cvlan-tag";
- }
-
- return result;
-
- }
+ /**
+ * Instantiates a new naming exceptions.
+ */
+ private NamingExceptions() {
+
+ }
+
+ private static class Helper {
+ private static final NamingExceptions INSTANCE = new NamingExceptions();
+ }
+
+ /**
+ * Gets the single instance of NamingExceptions.
+ *
+ * @return single instance of NamingExceptions
+ */
+ public static NamingExceptions getInstance() {
+ return Helper.INSTANCE;
+ }
+
+ /**
+ * Gets the object name.
+ *
+ * @param name the name
+ * @return the object name
+ */
+ public String getObjectName(String name) {
+
+ String result = name;
+
+ if (name.equals("cvlan-tag")) {
+ result = "cvlan-tag-entry";
+ }
+
+ return result;
+ }
+
+ /**
+ * Gets the DB name.
+ *
+ * @param name the name
+ * @return the DB name
+ */
+ public String getDBName(String name) {
+
+ String result = name;
+
+ if (name.equals("cvlan-tag-entry")) {
+ result = "cvlan-tag";
+ }
+
+ return result;
+
+ }
}
diff --git a/aai-core/src/test/java/org/onap/aai/AAIJunitRunner.java b/aai-core/src/test/java/org/onap/aai/AAIJunitRunner.java
index 94fce5d4..da7446bb 100644
--- a/aai-core/src/test/java/org/onap/aai/AAIJunitRunner.java
+++ b/aai-core/src/test/java/org/onap/aai/AAIJunitRunner.java
@@ -17,14 +17,15 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-package org.onap.aai;
-import org.junit.runners.Parameterized;
-import org.onap.aai.util.AAIConstants;
+package org.onap.aai;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
+import org.junit.runners.Parameterized;
+import org.onap.aai.util.AAIConstants;
+
public class AAIJunitRunner extends Parameterized {
public AAIJunitRunner(Class<?> klass) throws Throwable {
@@ -33,12 +34,12 @@ public class AAIJunitRunner extends Parameterized {
modifyOxmHome();
}
- public void setProps(){
+ public void setProps() {
System.setProperty("AJSC_HOME", ".");
System.setProperty("BUNDLECONFIG_DIR", "src/test/resources/bundleconfig-local");
}
- public void modifyOxmHome(){
+ public void modifyOxmHome() {
try {
Field aaiConstantsField = AAIConstants.class.getField("AAI_HOME_ETC_OXM");
setFinalStatic(aaiConstantsField, "../aai-schema/src/main/resources/oxm/");
diff --git a/aai-core/src/test/java/org/onap/aai/AAISetup.java b/aai-core/src/test/java/org/onap/aai/AAISetup.java
index b464ef46..ade20f4a 100644
--- a/aai-core/src/test/java/org/onap/aai/AAISetup.java
+++ b/aai-core/src/test/java/org/onap/aai/AAISetup.java
@@ -17,28 +17,28 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai;
import java.util.Map;
import org.junit.BeforeClass;
-
import org.junit.ClassRule;
import org.junit.Rule;
import org.onap.aai.config.ConfigConfiguration;
+import org.onap.aai.config.IntrospectionConfig;
+import org.onap.aai.config.RestBeanConfig;
import org.onap.aai.config.SpringContextAware;
import org.onap.aai.edges.EdgeIngestor;
-import org.onap.aai.config.IntrospectionConfig;
import org.onap.aai.introspection.LoaderFactory;
import org.onap.aai.introspection.MoxyLoader;
import org.onap.aai.nodes.NodeIngestor;
-import org.onap.aai.config.RestBeanConfig;
import org.onap.aai.rest.db.HttpEntry;
+import org.onap.aai.serialization.db.EdgeSerializer;
+import org.onap.aai.serialization.queryformats.QueryFormatTestHelper;
import org.onap.aai.setup.AAIConfigTranslator;
import org.onap.aai.setup.SchemaVersion;
import org.onap.aai.setup.SchemaVersions;
-import org.onap.aai.serialization.db.EdgeSerializer;
-import org.onap.aai.serialization.queryformats.QueryFormatTestHelper;
import org.onap.aai.util.AAIConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
@@ -47,19 +47,13 @@ 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
-})
-@TestPropertySource(properties = { "schema.uri.base.path = /aai", "schema.xsd.maxoccurs = 5000" , "schema.translator.list=config",
- "schema.nodes.location=src/test/resources/onap/oxm", "schema.edges.location=src/test/resources/onap/dbedgerules"})
+@ContextConfiguration(
+ classes = {ConfigConfiguration.class, AAIConfigTranslator.class, EdgeIngestor.class, EdgeSerializer.class,
+ NodeIngestor.class, SpringContextAware.class, IntrospectionConfig.class, RestBeanConfig.class})
+@TestPropertySource(
+ properties = {"schema.uri.base.path = /aai", "schema.xsd.maxoccurs = 5000", "schema.translator.list=config",
+ "schema.nodes.location=src/test/resources/onap/oxm",
+ "schema.edges.location=src/test/resources/onap/dbedgerules"})
public abstract class AAISetup {
@ClassRule
@@ -69,28 +63,28 @@ public abstract class AAISetup {
public final SpringMethodRule springMethodRule = new SpringMethodRule();
@Autowired
- protected Map<SchemaVersion, MoxyLoader> moxyLoaderInstance;
+ protected Map<SchemaVersion, MoxyLoader> moxyLoaderInstance;
- @Autowired
- protected HttpEntry traversalHttpEntry;
+ @Autowired
+ protected HttpEntry traversalHttpEntry;
- @Autowired
- protected HttpEntry traversalUriHttpEntry;
+ @Autowired
+ protected HttpEntry traversalUriHttpEntry;
- @Autowired
- protected NodeIngestor nodeIngestor;
+ @Autowired
+ protected NodeIngestor nodeIngestor;
- @Autowired
- protected LoaderFactory loaderFactory;
+ @Autowired
+ protected LoaderFactory loaderFactory;
- @Autowired
- protected SchemaVersions schemaVersions;
+ @Autowired
+ protected SchemaVersions schemaVersions;
- @Value("${schema.uri.base.path}")
- protected String basePath;
+ @Value("${schema.uri.base.path}")
+ protected String basePath;
- @Value("${schema.xsd.maxoccurs}")
- protected String maxOccurs;
+ @Value("${schema.xsd.maxoccurs}")
+ protected String maxOccurs;
protected static final String SERVICE_NAME = "JUNIT";
@@ -99,9 +93,8 @@ public abstract class AAISetup {
System.setProperty("AJSC_HOME", ".");
System.setProperty("BUNDLECONFIG_DIR", "src/test/resources/bundleconfig-local");
System.setProperty("aai.service.name", SERVICE_NAME);
- QueryFormatTestHelper.setFinalStatic(AAIConstants.class.getField("AAI_HOME_ETC_OXM"), "src/test/resources/bundleconfig-local/etc/oxm/");
+ QueryFormatTestHelper.setFinalStatic(AAIConstants.class.getField("AAI_HOME_ETC_OXM"),
+ "src/test/resources/bundleconfig-local/etc/oxm/");
}
-
-
}
diff --git a/aai-core/src/test/java/org/onap/aai/AAISetupForSwagger.java b/aai-core/src/test/java/org/onap/aai/AAISetupForSwagger.java
index 07731770..c11a5b2d 100644
--- a/aai-core/src/test/java/org/onap/aai/AAISetupForSwagger.java
+++ b/aai-core/src/test/java/org/onap/aai/AAISetupForSwagger.java
@@ -17,31 +17,27 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-package org.onap.aai;
+package org.onap.aai;
import org.junit.BeforeClass;
-
import org.junit.ClassRule;
import org.junit.Rule;
import org.onap.aai.edges.EdgeIngestor;
import org.onap.aai.nodes.NodeIngestor;
import org.onap.aai.serialization.queryformats.QueryFormatTestHelper;
import org.onap.aai.setup.SchemaLocationsBean;
-import org.onap.aai.util.AAIConstants;
import org.onap.aai.testutils.TestUtilConfigTranslatorforEdges;
+import org.onap.aai.util.AAIConstants;
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;
-@ContextConfiguration(classes = {
- SchemaLocationsBean.class,
- TestUtilConfigTranslatorforEdges.class,
- EdgeIngestor.class,
- NodeIngestor.class
-})
+@ContextConfiguration(
+ classes = {SchemaLocationsBean.class, TestUtilConfigTranslatorforEdges.class, EdgeIngestor.class,
+ NodeIngestor.class})
@TestPropertySource(properties = {"schemaIngestPropLoc = src/test/resources/schemaIngest/schemaIngestTest.properties"})
public abstract class AAISetupForSwagger {
@@ -52,11 +48,9 @@ public abstract class AAISetupForSwagger {
@Rule
public final SpringMethodRule springMethodRule = new SpringMethodRule();
-
@Autowired
protected NodeIngestor nodeIngestor;
-
-
+
protected static final String SERVICE_NAME = "JUNIT";
@BeforeClass
@@ -64,9 +58,8 @@ public abstract class AAISetupForSwagger {
System.setProperty("AJSC_HOME", ".");
System.setProperty("BUNDLECONFIG_DIR", "src/test/resources/bundleconfig-local");
System.setProperty("aai.service.name", SERVICE_NAME);
- QueryFormatTestHelper.setFinalStatic(AAIConstants.class.getField("AAI_HOME_ETC_OXM"), "src/test/resources/bundleconfig-local/etc/oxm/");
+ QueryFormatTestHelper.setFinalStatic(AAIConstants.class.getField("AAI_HOME_ETC_OXM"),
+ "src/test/resources/bundleconfig-local/etc/oxm/");
}
-
-
-
+
}
diff --git a/aai-core/src/test/java/org/onap/aai/AbstractConfigTranslator.java b/aai-core/src/test/java/org/onap/aai/AbstractConfigTranslator.java
index fb91e316..07183436 100644
--- a/aai-core/src/test/java/org/onap/aai/AbstractConfigTranslator.java
+++ b/aai-core/src/test/java/org/onap/aai/AbstractConfigTranslator.java
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai;
import java.io.File;
@@ -38,36 +39,35 @@ public abstract class AbstractConfigTranslator extends ConfigTranslator {
super(bean, schemaVersions);
}
-
-
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see org.onap.aai.setup.ConfigTranslator#getNodeFiles()
*/
@Override
public Map<SchemaVersion, List<String>> getNodeFiles() {
- String prefix = bean.getNodeDirectory() + AAIConstants.AAI_FILESEP ;
-
+ String prefix = bean.getNodeDirectory() + AAIConstants.AAI_FILESEP;
+
String suffix = ".xml";
-
+
Map<SchemaVersion, List<String>> files = new TreeMap<>();
for (SchemaVersion v : schemaVersions.getVersions()) {
-
+
List<String> container = getVersionNodeFiles(v);
-
-
+
files.put(v, container);
}
-
+
return files;
}
-
public List<String> getVersionNodeFiles(SchemaVersion v) {
- Pattern p = Pattern.compile("aai(.*)"+"_oxm_(.*).xml" );
-
+ Pattern p = Pattern.compile("aai(.*)" + "_oxm_(.*).xml");
+
List<String> container = new ArrayList<>();
- String directoryName = bean.getNodeDirectory() + AAIConstants.AAI_FILESEP + v.toString() + AAIConstants.AAI_FILESEP ;
-
+ String directoryName =
+ bean.getNodeDirectory() + AAIConstants.AAI_FILESEP + v.toString() + AAIConstants.AAI_FILESEP;
+
File[] files = new File(directoryName).listFiles();
for (File f : files) {
String fileName = f.getName();
@@ -76,10 +76,10 @@ public abstract class AbstractConfigTranslator extends ConfigTranslator {
String file = directoryName + m.group();
container.add(file.toString());
}
-
+
}
return container;
-
+
}
}
diff --git a/aai-core/src/test/java/org/onap/aai/DataLinkSetup.java b/aai-core/src/test/java/org/onap/aai/DataLinkSetup.java
index 125bb111..f4d62d44 100644
--- a/aai-core/src/test/java/org/onap/aai/DataLinkSetup.java
+++ b/aai-core/src/test/java/org/onap/aai/DataLinkSetup.java
@@ -17,8 +17,11 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai;
+import java.util.Map;
+
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Rule;
@@ -47,31 +50,16 @@ import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.rules.SpringClassRule;
import org.springframework.test.context.junit4.rules.SpringMethodRule;
-import java.util.Map;
-
-
-@ContextConfiguration(classes = {
- ConfigConfiguration.class,
- TestUtilConfigTranslatorforDataLink.class,
- EdgeIngestor.class,
- EdgeSerializer.class,
- NodeIngestor.class,
- SpringContextAware.class,
- IntrospectionConfig.class,
- RestBeanConfig.class
-})
-@TestPropertySource(properties = {
- "schema.uri.base.path = /aai",
- "schema.xsd.maxoccurs = 5000",
- "schema.version.api.default = v4",
- "schema.version.edge.label.start = v4",
- "schema.version.depth.start = v3",
- "schema.version.app.root.start = v4",
- "schema.version.related.link.start = v4",
- "schema.version.namespace.change.start = v4",
- "schema.version.list = v1,v2,v3,v4",
- "schema.translator.list = config"
-})
+@ContextConfiguration(
+ classes = {ConfigConfiguration.class, TestUtilConfigTranslatorforDataLink.class, EdgeIngestor.class,
+ EdgeSerializer.class, NodeIngestor.class, SpringContextAware.class, IntrospectionConfig.class,
+ RestBeanConfig.class})
+@TestPropertySource(
+ properties = {"schema.uri.base.path = /aai", "schema.xsd.maxoccurs = 5000", "schema.version.api.default = v4",
+ "schema.version.edge.label.start = v4", "schema.version.depth.start = v3",
+ "schema.version.app.root.start = v4", "schema.version.related.link.start = v4",
+ "schema.version.namespace.change.start = v4", "schema.version.list = v1,v2,v3,v4",
+ "schema.translator.list = config"})
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
public abstract class DataLinkSetup {
@@ -82,29 +70,29 @@ public abstract class DataLinkSetup {
public final SpringMethodRule springMethodRule = new SpringMethodRule();
@Autowired
- protected Map<SchemaVersion, MoxyLoader> moxyLoaderInstance;
-
- @Autowired
- protected HttpEntry traversalHttpEntry;
-
- @Autowired
- protected HttpEntry traversalUriHttpEntry;
-
- @Autowired
- protected NodeIngestor nodeIngestor;
-
- @Autowired
- protected LoaderFactory loaderFactory;
-
- @Autowired
- protected SchemaVersions schemaVersions;
-
- @Value("${schema.uri.base.path}")
- protected String basePath;
-
- @Value("${schema.xsd.maxoccurs}")
- protected String maxOccurs;
-
+ protected Map<SchemaVersion, MoxyLoader> moxyLoaderInstance;
+
+ @Autowired
+ protected HttpEntry traversalHttpEntry;
+
+ @Autowired
+ protected HttpEntry traversalUriHttpEntry;
+
+ @Autowired
+ protected NodeIngestor nodeIngestor;
+
+ @Autowired
+ protected LoaderFactory loaderFactory;
+
+ @Autowired
+ protected SchemaVersions schemaVersions;
+
+ @Value("${schema.uri.base.path}")
+ protected String basePath;
+
+ @Value("${schema.xsd.maxoccurs}")
+ protected String maxOccurs;
+
protected static final String SERVICE_NAME = "JUNIT";
@BeforeClass
@@ -112,9 +100,8 @@ public abstract class DataLinkSetup {
System.setProperty("AJSC_HOME", ".");
System.setProperty("BUNDLECONFIG_DIR", "src/test/resources/bundleconfig-local");
System.setProperty("aai.service.name", SERVICE_NAME);
- QueryFormatTestHelper.setFinalStatic(AAIConstants.class.getField("AAI_HOME_ETC_OXM"), "src/test/resources/bundleconfig-local/etc/oxm/");
+ QueryFormatTestHelper.setFinalStatic(AAIConstants.class.getField("AAI_HOME_ETC_OXM"),
+ "src/test/resources/bundleconfig-local/etc/oxm/");
}
-
-
-
+
}
diff --git a/aai-core/src/test/java/org/onap/aai/HttpTestUtil.java b/aai-core/src/test/java/org/onap/aai/HttpTestUtil.java
index 6add23e0..6a9e7256 100644
--- a/aai-core/src/test/java/org/onap/aai/HttpTestUtil.java
+++ b/aai-core/src/test/java/org/onap/aai/HttpTestUtil.java
@@ -17,10 +17,24 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai;
+import static org.mockito.Matchers.anyObject;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.when;
+
import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
+
+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;
@@ -28,7 +42,6 @@ import org.onap.aai.dbmap.DBConnectionType;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.introspection.Introspector;
import org.onap.aai.introspection.Loader;
-import org.onap.aai.setup.SchemaVersion;
import org.onap.aai.parsers.query.QueryParser;
import org.onap.aai.parsers.uri.URIToObject;
import org.onap.aai.rest.db.DBRequest;
@@ -37,25 +50,14 @@ import org.onap.aai.restcore.HttpMethod;
import org.onap.aai.restcore.RESTAPI;
import org.onap.aai.serialization.engines.QueryStyle;
import org.onap.aai.serialization.engines.TransactionalGraphEngine;
+import org.onap.aai.setup.SchemaVersion;
import org.onap.aai.setup.SchemaVersions;
-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 {
+ protected HttpEntry traversalHttpEntry;
- protected HttpEntry traversalHttpEntry;
-
- protected HttpEntry traversalUriHttpEntry;
+ protected HttpEntry traversalUriHttpEntry;
private static final EELFLogger logger = EELFManager.getInstance().getLogger(HttpTestUtil.class);
@@ -80,13 +82,13 @@ public class HttpTestUtil extends RESTAPI {
}
- public void init(){
+ public void init() {
- 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());
@@ -121,25 +123,25 @@ public class HttpTestUtil extends RESTAPI {
try {
- if(uri.startsWith("/aai/")){
+ if (uri.startsWith("/aai/")) {
uri = uri.substring(5);
}
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 != null && arr.length > 1){
- if(arr[0].matches("^v\\d+")){
+ if (arr != null && arr.length > 1) {
+ if (arr[0].matches("^v\\d+")) {
version = new SchemaVersion(arr[0]);
uri = uri.replaceAll("^v\\d+", "");
}
}
SchemaVersions schemaVersions = (SchemaVersions) SpringContextAware.getBean("schemaVersions");
- if(version == null){
+ if (version == null) {
version = schemaVersions.getDefaultVersion();
}
Mockito.when(uriInfo.getPath()).thenReturn(uri);
@@ -147,8 +149,8 @@ public class HttpTestUtil extends RESTAPI {
DBConnectionType type = DBConnectionType.REALTIME;
traversalHttpEntry.setHttpEntryProperties(version, type);
- Loader loader = traversalHttpEntry.getLoader();
- dbEngine = traversalHttpEntry.getDbEngine();
+ Loader loader = traversalHttpEntry.getLoader();
+ dbEngine = traversalHttpEntry.getDbEngine();
URI uriObject = UriBuilder.fromPath(uri).build();
URIToObject uriToObject = new URIToObject(loader, uriObject);
@@ -156,13 +158,13 @@ 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"));
@@ -170,36 +172,36 @@ public class HttpTestUtil extends RESTAPI {
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 = traversalHttpEntry.process(dbRequestList, "JUNIT");
+ Pair<Boolean, List<Pair<URI, Response>>> responsesTuple =
+ traversalHttpEntry.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){
+ } catch (Exception e) {
AAIException ex = new AAIException("AAI_4000", e);
response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.PUT, ex);
success = false;
} finally {
- if(success){
- if(response != null){
- if((response.getStatus() / 100) == 2){
- logger.info("Successfully completed the PUT request with status {} and committing it to DB", response.getStatus());
+ 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();
@@ -209,7 +211,7 @@ public class HttpTestUtil extends RESTAPI {
return response;
}
- public Response doGet(String uri, String depth){
+ public Response doGet(String uri, String depth) {
this.init();
Response response = null;
@@ -218,36 +220,36 @@ public class HttpTestUtil extends RESTAPI {
try {
- if(uri.startsWith("/aai/")){
+ if (uri.startsWith("/aai/")) {
uri = uri.substring(5);
}
logger.info("Starting the GET request for the uri {} with depth {}", uri, depth);
- String [] arr = uri.split("/");
+ String[] arr = uri.split("/");
SchemaVersion version = null;
- if(arr != null && arr.length > 1){
- if(arr[0].matches("^v\\d+")){
+ if (arr != null && arr.length > 1) {
+ if (arr[0].matches("^v\\d+")) {
version = new SchemaVersion(arr[0]);
uri = uri.replaceAll("^v\\d+", "");
}
}
SchemaVersions schemaVersions = (SchemaVersions) SpringContextAware.getBean("schemaVersions");
- if(version == null){
+ if (version == null) {
version = schemaVersions.getDefaultVersion();
}
DBConnectionType type = DBConnectionType.REALTIME;
traversalHttpEntry.setHttpEntryProperties(version, type);
- Loader loader = traversalHttpEntry.getLoader();
- dbEngine = traversalHttpEntry.getDbEngine();
+ Loader loader = traversalHttpEntry.getLoader();
+ dbEngine = traversalHttpEntry.getDbEngine();
URI uriObject = UriBuilder.fromPath(uri).build();
- if(depth != null){
+ if (depth != null) {
queryParameters.add("depth", depth);
}
@@ -266,28 +268,29 @@ 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 = traversalHttpEntry.process(dbRequestList, "JUNIT");
+ Pair<Boolean, List<Pair<URI, Response>>> responsesTuple =
+ traversalHttpEntry.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){
+ } catch (Exception e) {
AAIException ex = new AAIException("AAI_4000", e);
response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.PUT, ex);
success = false;
} finally {
- if(success){
- if(response != null){
- if((response.getStatus() / 100) == 2){
- logger.info("Successfully completed the GET request with status {} and committing it to DB", response.getStatus());
+ 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);
}
@@ -318,21 +321,21 @@ public class HttpTestUtil extends RESTAPI {
uri = uri.replaceAll("/aai/", "");
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 != null && arr.length > 1){
- if(arr[0].matches("^v\\d+")){
+ if (arr != null && 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+", "");
}
}
}
SchemaVersions schemaVersions = (SchemaVersions) SpringContextAware.getBean("schemaVersions");
- if(version == null){
+ if (version == null) {
version = schemaVersions.getDefaultVersion();
}
@@ -341,8 +344,8 @@ public class HttpTestUtil extends RESTAPI {
traversalHttpEntry.setHttpEntryProperties(version, type);
traversalHttpEntry.setHttpEntryProperties(version, type);
- Loader loader = traversalHttpEntry.getLoader();
- dbEngine = traversalHttpEntry.getDbEngine();
+ Loader loader = traversalHttpEntry.getLoader();
+ dbEngine = traversalHttpEntry.getDbEngine();
URI uriObject = UriBuilder.fromPath(uri).build();
URIToObject uriToObject = new URIToObject(loader, uriObject);
@@ -355,7 +358,7 @@ public class HttpTestUtil extends RESTAPI {
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 {
@@ -363,28 +366,29 @@ 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 = traversalHttpEntry.process(dbRequestList, "JUNIT");
+ Pair<Boolean, List<Pair<URI, Response>>> responsesTuple =
+ traversalHttpEntry.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){
+ } catch (Exception e) {
AAIException ex = new AAIException("AAI_4000", e);
response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.PUT, ex);
success = false;
} finally {
- if(success){
- if(response != null){
- if((response.getStatus() / 100) == 2){
- logger.info("Successfully completed the DELETE request with status {} and committing it to DB", response.getStatus());
+ 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);
}
@@ -399,8 +403,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-core/src/test/java/org/onap/aai/PayloadUtil.java b/aai-core/src/test/java/org/onap/aai/PayloadUtil.java
index 88261aa6..7ee6c39c 100644
--- a/aai-core/src/test/java/org/onap/aai/PayloadUtil.java
+++ b/aai-core/src/test/java/org/onap/aai/PayloadUtil.java
@@ -17,9 +17,10 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
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 +29,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 +38,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 +52,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);
@@ -63,14 +66,15 @@ public class PayloadUtil {
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,14 +85,16 @@ 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);
}
}
diff --git a/aai-core/src/test/java/org/onap/aai/auth/AAIAuthCoreTest.java b/aai-core/src/test/java/org/onap/aai/auth/AAIAuthCoreTest.java
index 2c299869..d6075c1f 100644
--- a/aai-core/src/test/java/org/onap/aai/auth/AAIAuthCoreTest.java
+++ b/aai-core/src/test/java/org/onap/aai/auth/AAIAuthCoreTest.java
@@ -17,21 +17,22 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.auth;
+import static org.junit.Assert.*;
+
import org.junit.Before;
import org.junit.Test;
import org.onap.aai.AAISetup;
import org.onap.aai.auth.exceptions.AAIUnrecognizedFunctionException;
-import static org.junit.Assert.*;
-
public class AAIAuthCoreTest extends AAISetup {
private AAIAuthCore authCore;
@Before
- public void setup(){
+ public void setup() {
authCore = new AAIAuthCore("/aai");
}
@@ -40,16 +41,16 @@ public class AAIAuthCoreTest extends AAISetup {
String uri = "/aai/v3/search/edge-tag-query";
assertEquals("Get aai function name from " + uri, "search", authCore.getAuthPolicyFunctName(uri));
-
+
uri = "/aai/v10/search/edge-tag-query";
assertEquals("Get aai function name from " + uri, "search", authCore.getAuthPolicyFunctName(uri));
uri = "/aai/search/model";
assertEquals("Get aai function name from " + uri, "search", authCore.getAuthPolicyFunctName(uri));
-
+
uri = "/aai/v9/cloud-infrastructure/cloud-regions/cloud-region/somecloudregion/some-cloud-owner";
assertEquals("Get aai function name from " + uri, "cloud-infrastructure", authCore.getAuthPolicyFunctName(uri));
-
+
uri = "/aai/v8/network/pnfs/pnf/ff4ca01orc/p-interfaces";
assertEquals("Get aai function name from " + uri, "network", authCore.getAuthPolicyFunctName(uri));
@@ -91,17 +92,20 @@ public class AAIAuthCoreTest extends AAISetup {
@Test
public void validUsernameContainsTheWildcardIdAuthTest() throws AAIUnrecognizedFunctionException {
- assertTrue(authCore.authorize("cn=blah, testWildcardId, O=".toLowerCase(), "/aai/v0/testFunction/someUri", "PUT", "", "aafWildCardIssuer"));
+ assertTrue(authCore.authorize("cn=blah, testWildcardId, O=".toLowerCase(), "/aai/v0/testFunction/someUri",
+ "PUT", "", "aafWildCardIssuer"));
}
@Test
public void validUsernameContainsTheWildcardIdInvalidIssuerAuthTest() throws AAIUnrecognizedFunctionException {
- assertFalse(authCore.authorize("cn=blah, testWildcardId, O=".toLowerCase(), "/aai/v0/testFunction/someUri", "PUT", "", "invalidIssuer"));
+ assertFalse(authCore.authorize("cn=blah, testWildcardId, O=".toLowerCase(), "/aai/v0/testFunction/someUri",
+ "PUT", "", "invalidIssuer"));
}
@Test
public void invalidUsernameContainsRegularUsernameAuthTest() throws AAIUnrecognizedFunctionException {
- assertFalse(authCore.authorize("cn=blah, testUser, O=".toLowerCase(), "/aai/v0/testFunction/someUri", "PUT", ""));
+ assertFalse(
+ authCore.authorize("cn=blah, testUser, O=".toLowerCase(), "/aai/v0/testFunction/someUri", "PUT", ""));
}
@Test
@@ -116,93 +120,115 @@ public class AAIAuthCoreTest extends AAISetup {
@Test
public void validUsernameViaHaProxyAuthTest() throws AAIUnrecognizedFunctionException {
- assertTrue(authCore.authorize("ha-proxy-user".toLowerCase(), "/aai/v0/testFunction/someUri", "PUT", "testUser".toLowerCase()));
+ assertTrue(authCore.authorize("ha-proxy-user".toLowerCase(), "/aai/v0/testFunction/someUri", "PUT",
+ "testUser".toLowerCase()));
}
@Test
public void validUsernameInvalidHttpMethodViaHaProxyAuthTest() throws AAIUnrecognizedFunctionException {
- assertFalse(authCore.authorize("ha-proxy-user".toLowerCase(), "/aai/v0/testFunction/someUri", "POST", "testUser".toLowerCase()));
+ assertFalse(authCore.authorize("ha-proxy-user".toLowerCase(), "/aai/v0/testFunction/someUri", "POST",
+ "testUser".toLowerCase()));
}
@Test(expected = AAIUnrecognizedFunctionException.class)
public void validUsernameInvalidFunctionInURIViaHaProxyAuthTest() throws AAIUnrecognizedFunctionException {
- authCore.authorize("ha-proxy-user".toLowerCase(), "/aai/v0/badFunction/someUri", "PUT", "testUser".toLowerCase());
+ authCore.authorize("ha-proxy-user".toLowerCase(), "/aai/v0/badFunction/someUri", "PUT",
+ "testUser".toLowerCase());
}
@Test
public void invalidUsernameViaHaProxyAuthTest() throws AAIUnrecognizedFunctionException {
- assertFalse(authCore.authorize("ha-proxy-user".toLowerCase(), "/aai/v0/testFunction/someUri", "PUT", "invlaidTestUser".toLowerCase()));
+ assertFalse(authCore.authorize("ha-proxy-user".toLowerCase(), "/aai/v0/testFunction/someUri", "PUT",
+ "invlaidTestUser".toLowerCase()));
}
@Test
public void validUsernameIsTheExactWildcardIdViaHaProxyAuthTest() throws AAIUnrecognizedFunctionException {
- assertTrue(authCore.authorize("ha-proxy-user".toLowerCase(), "/aai/v0/testFunction/someUri", "PUT", "testWildcardId".toLowerCase()));
+ assertTrue(authCore.authorize("ha-proxy-user".toLowerCase(), "/aai/v0/testFunction/someUri", "PUT",
+ "testWildcardId".toLowerCase()));
}
@Test
public void validUsernameContainsTheWildcardIdViaHaProxyAuthTest() throws AAIUnrecognizedFunctionException {
- assertTrue(authCore.authorize("ha-proxy-user".toLowerCase(), "/aai/v0/testFunction/someUri", "PUT", "cn=blah, testWildcardId, O=".toLowerCase(), "aafWildCardIssuer"));
+ assertTrue(authCore.authorize("ha-proxy-user".toLowerCase(), "/aai/v0/testFunction/someUri", "PUT",
+ "cn=blah, testWildcardId, O=".toLowerCase(), "aafWildCardIssuer"));
}
@Test
public void invalidUsernameContainsRegularUsernameViaHaProxyAuthTest() throws AAIUnrecognizedFunctionException {
- assertFalse(authCore.authorize("ha-proxy-user".toLowerCase(), "/aai/v0/testFunction/someUri", "PUT", "cn=blah, testUser, O=".toLowerCase()));
+ assertFalse(authCore.authorize("ha-proxy-user".toLowerCase(), "/aai/v0/testFunction/someUri", "PUT",
+ "cn=blah, testUser, O=".toLowerCase()));
}
@Test
public void haProxyUsernameTwiceAuthTest() throws AAIUnrecognizedFunctionException {
- assertFalse(authCore.authorize("ha-proxy-user".toLowerCase(), "/aai/v0/testFunction/someUri", "PUT", "ha-proxy-user".toLowerCase()));
+ assertFalse(authCore.authorize("ha-proxy-user".toLowerCase(), "/aai/v0/testFunction/someUri", "PUT",
+ "ha-proxy-user".toLowerCase()));
}
-
@Test
public void haProxyWildcardIdAuthTest() throws AAIUnrecognizedFunctionException {
- assertTrue(authCore.authorize("cn=blah, ha-proxy-wildcard-id, O=".toLowerCase(), "/aai/util/echo", "GET", "", "aafWildCardIssuer"));
+ assertTrue(authCore.authorize("cn=blah, ha-proxy-wildcard-id, O=".toLowerCase(), "/aai/util/echo", "GET", "",
+ "aafWildCardIssuer"));
}
@Test
public void haProxyWildcardIdInvalidFunctionAuthTest() throws AAIUnrecognizedFunctionException {
- assertFalse(authCore.authorize("cn=blah, ha-proxy-wildcard-id, O=".toLowerCase(), "/aai/v0/testFunction/someUri", "PUT", ""));
+ assertFalse(authCore.authorize("cn=blah, ha-proxy-wildcard-id, O=".toLowerCase(),
+ "/aai/v0/testFunction/someUri", "PUT", ""));
}
@Test
public void validUsernameViaHaProxyWildcardIdAuthTest() throws AAIUnrecognizedFunctionException {
- assertTrue(authCore.authorize("cn=blah, ha-proxy-wildcard-id, O=".toLowerCase(), "/aai/v0/testFunction/someUri", "PUT", "testUser".toLowerCase(), "aafWildCardIssuer"));
+ assertTrue(authCore.authorize("cn=blah, ha-proxy-wildcard-id, O=".toLowerCase(), "/aai/v0/testFunction/someUri",
+ "PUT", "testUser".toLowerCase(), "aafWildCardIssuer"));
}
@Test
public void validUsernameInvalidHttpMethodViaHaProxyWildcardIdAuthTest() throws AAIUnrecognizedFunctionException {
- assertFalse(authCore.authorize("cn=blah, ha-proxy-wildcard-id, O=".toLowerCase(), "/aai/v0/testFunction/someUri", "POST", "testUser".toLowerCase()));
+ assertFalse(authCore.authorize("cn=blah, ha-proxy-wildcard-id, O=".toLowerCase(),
+ "/aai/v0/testFunction/someUri", "POST", "testUser".toLowerCase()));
}
@Test(expected = AAIUnrecognizedFunctionException.class)
- public void validUsernameInvalidFunctionInURIViaHaProxyWildcardIdAuthTest() throws AAIUnrecognizedFunctionException {
- authCore.authorize("cn=blah, ha-proxy-wildcard-id, O=".toLowerCase(), "/aai/v0/badFunction/someUri", "PUT", "testUser".toLowerCase());
+ public void validUsernameInvalidFunctionInURIViaHaProxyWildcardIdAuthTest()
+ throws AAIUnrecognizedFunctionException {
+ authCore.authorize("cn=blah, ha-proxy-wildcard-id, O=".toLowerCase(), "/aai/v0/badFunction/someUri", "PUT",
+ "testUser".toLowerCase());
}
@Test
public void invalidUsernameViaHaProxyWildcardIdAuthTest() throws AAIUnrecognizedFunctionException {
- assertFalse(authCore.authorize("cn=blah, ha-proxy-wildcard-id, O=".toLowerCase(), "/aai/v0/testFunction/someUri", "PUT", "invlaidTestUser".toLowerCase()));
+ assertFalse(authCore.authorize("cn=blah, ha-proxy-wildcard-id, O=".toLowerCase(),
+ "/aai/v0/testFunction/someUri", "PUT", "invlaidTestUser".toLowerCase()));
}
@Test
- public void validUsernameIsTheExactWildcardIdViaHaProxyWildcardIdAuthTest() throws AAIUnrecognizedFunctionException {
- assertTrue(authCore.authorize("cn=blah, ha-proxy-wildcard-id, O=".toLowerCase(), "/aai/v0/testFunction/someUri", "PUT", "testWildcardId".toLowerCase(), "aafWildCardIssuer"));
+ public void validUsernameIsTheExactWildcardIdViaHaProxyWildcardIdAuthTest()
+ throws AAIUnrecognizedFunctionException {
+ assertTrue(authCore.authorize("cn=blah, ha-proxy-wildcard-id, O=".toLowerCase(), "/aai/v0/testFunction/someUri",
+ "PUT", "testWildcardId".toLowerCase(), "aafWildCardIssuer"));
}
@Test
- public void validUsernameContainsTheWildcardIdViaHaProxyWildcardIdAuthTest() throws AAIUnrecognizedFunctionException {
- assertTrue(authCore.authorize("cn=blah, ha-proxy-wildcard-id, O=".toLowerCase(), "/aai/v0/testFunction/someUri", "PUT", "cn=blah, testWildcardId, O=".toLowerCase(), "aafWildCardIssuer"));
+ public void validUsernameContainsTheWildcardIdViaHaProxyWildcardIdAuthTest()
+ throws AAIUnrecognizedFunctionException {
+ assertTrue(authCore.authorize("cn=blah, ha-proxy-wildcard-id, O=".toLowerCase(), "/aai/v0/testFunction/someUri",
+ "PUT", "cn=blah, testWildcardId, O=".toLowerCase(), "aafWildCardIssuer"));
}
@Test
- public void validUsernameContainsTheWildcardIdViaHaProxyWildcardIdInvalidIssuerAuthTest() throws AAIUnrecognizedFunctionException {
- assertFalse(authCore.authorize("cn=blah, ha-proxy-wildcard-id, O=".toLowerCase(), "/aai/v0/testFunction/someUri", "PUT", "cn=blah, testWildcardId, O=".toLowerCase(), "invalidIssuer"));
+ public void validUsernameContainsTheWildcardIdViaHaProxyWildcardIdInvalidIssuerAuthTest()
+ throws AAIUnrecognizedFunctionException {
+ assertFalse(authCore.authorize("cn=blah, ha-proxy-wildcard-id, O=".toLowerCase(),
+ "/aai/v0/testFunction/someUri", "PUT", "cn=blah, testWildcardId, O=".toLowerCase(), "invalidIssuer"));
}
@Test
- public void invalidUsernameContainsRegularUsernameViaHaProxyWildcardIdAuthTest() throws AAIUnrecognizedFunctionException {
- assertFalse(authCore.authorize("cn=blah, ha-proxy-wildcard-id, O=".toLowerCase(), "/aai/v0/testFunction/someUri", "PUT", "cn=blah, testUser, O=".toLowerCase()));
+ public void invalidUsernameContainsRegularUsernameViaHaProxyWildcardIdAuthTest()
+ throws AAIUnrecognizedFunctionException {
+ assertFalse(authCore.authorize("cn=blah, ha-proxy-wildcard-id, O=".toLowerCase(),
+ "/aai/v0/testFunction/someUri", "PUT", "cn=blah, testUser, O=".toLowerCase()));
}
}
diff --git a/aai-core/src/test/java/org/onap/aai/auth/AAIUserTest.java b/aai-core/src/test/java/org/onap/aai/auth/AAIUserTest.java
index a90c7feb..cf5eafbd 100644
--- a/aai-core/src/test/java/org/onap/aai/auth/AAIUserTest.java
+++ b/aai-core/src/test/java/org/onap/aai/auth/AAIUserTest.java
@@ -17,13 +17,14 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.auth;
+import static org.junit.Assert.assertEquals;
+
import org.junit.Test;
import org.onap.aai.AAISetup;
-import static org.junit.Assert.assertEquals;
-
public class AAIUserTest extends AAISetup {
@Test
@@ -33,19 +34,19 @@ public class AAIUserTest extends AAISetup {
usr.setUserAccess("auth", "GET");
usr.setUserAccess("auth", "PUT");
usr.setUserAccess("authentication", "PUT", "GET", "POST");
-
+
assertEquals(true, usr.hasAccess("auth", "GET"));
assertEquals(true, usr.hasAccess("auth", "PUT"));
assertEquals(true, usr.hasAccess("authentication", "POST"));
}
-
+
@Test
public void testIsNotAuth() {
AAIUser usr = new AAIUser("testUser");
usr.addRole("testRole");
-
+
assertEquals(false, usr.hasAccess("auth", "GET"));
-
+
usr.setUserAccess("auth", "GET");
assertEquals(false, usr.hasAccess("auth", "PUT"));
}
diff --git a/aai-core/src/test/java/org/onap/aai/concurrent/AaiCallableTest.java b/aai-core/src/test/java/org/onap/aai/concurrent/AaiCallableTest.java
index 94b1ef6b..0c3857ae 100644
--- a/aai-core/src/test/java/org/onap/aai/concurrent/AaiCallableTest.java
+++ b/aai-core/src/test/java/org/onap/aai/concurrent/AaiCallableTest.java
@@ -17,32 +17,34 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.concurrent;
import static org.junit.Assert.assertTrue;
+
import java.lang.Object;
+
import org.junit.Test;
import org.onap.aai.AAISetup;
-import org.slf4j.MDC;
import org.onap.aai.concurrent.AaiCallable;
+import org.slf4j.MDC;
public class AaiCallableTest extends AAISetup {
@Test
public void testAaiCallable() {
MDC.put("test_name", "test_value");
-
+
AaiCallable<Object> task = new AaiCallable<Object>() {
@Override
public Object process() {
String mdcValue = MDC.get("test_name");
- assertTrue( "MDC value retained", "test_value".equals(mdcValue));
+ assertTrue("MDC value retained", "test_value".equals(mdcValue));
return (new Object());
}
};
try {
task.call();
- }
- catch (Exception e) {
+ } catch (Exception e) {
e.printStackTrace();
}
}
diff --git a/aai-core/src/test/java/org/onap/aai/dbmap/AAIGraphTest.java b/aai-core/src/test/java/org/onap/aai/dbmap/AAIGraphTest.java
index 41a5f20b..48d2583d 100644
--- a/aai-core/src/test/java/org/onap/aai/dbmap/AAIGraphTest.java
+++ b/aai-core/src/test/java/org/onap/aai/dbmap/AAIGraphTest.java
@@ -17,8 +17,20 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.dbmap;
+import static org.hamcrest.CoreMatchers.containsString;
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.Matchers.matchesPattern;
+import static org.junit.Assert.*;
+
+import java.io.FileNotFoundException;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+
import org.janusgraph.core.JanusGraph;
import org.janusgraph.core.JanusGraphFactory;
import org.janusgraph.core.schema.JanusGraphIndex;
@@ -36,66 +48,65 @@ import org.onap.aai.schema.enums.PropertyMetadata;
import org.onap.aai.setup.SchemaVersions;
import org.onap.aai.util.AAIConstants;
-import java.io.FileNotFoundException;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Optional;
-import java.util.Set;
-
-import static org.hamcrest.CoreMatchers.containsString;
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.Matchers.matchesPattern;
-import static org.junit.Assert.*;
-
-public class AAIGraphTest extends AAISetup{
- @Before
- public void setup() {
- AAIGraph.getInstance();
- }
+public class AAIGraphTest extends AAISetup {
+ @Before
+ public void setup() {
+ AAIGraph.getInstance();
+ }
- @Test
- public void getRealtimeInstanceConnectionName() throws Exception {
+ @Test
+ public void getRealtimeInstanceConnectionName() throws Exception {
- JanusGraphManagement graphMgt = AAIGraph.getInstance().getGraph().openManagement();
- String connectionInstanceName = graphMgt.getOpenInstances().stream().filter(c -> c.contains("current")).findFirst().get();
- assertThat(connectionInstanceName, containsString(SERVICE_NAME));
- assertThat(connectionInstanceName, containsString("realtime"));
- assertThat(connectionInstanceName, matchesPattern("^\\d+_[\\w\\-\\d]+_" + SERVICE_NAME + "_realtime_\\d+\\(current\\)$"));
- graphMgt.rollback();
- }
+ JanusGraphManagement graphMgt = AAIGraph.getInstance().getGraph().openManagement();
+ String connectionInstanceName =
+ graphMgt.getOpenInstances().stream().filter(c -> c.contains("current")).findFirst().get();
+ assertThat(connectionInstanceName, containsString(SERVICE_NAME));
+ assertThat(connectionInstanceName, containsString("realtime"));
+ assertThat(connectionInstanceName,
+ matchesPattern("^\\d+_[\\w\\-\\d]+_" + SERVICE_NAME + "_realtime_\\d+\\(current\\)$"));
+ graphMgt.rollback();
+ }
- @Test
- public void getCachedInstanceConnectionName() throws Exception {
+ @Test
+ public void getCachedInstanceConnectionName() throws Exception {
- JanusGraphManagement graphMgt = AAIGraph.getInstance().getGraph(DBConnectionType.CACHED).openManagement();
- String connectionInstanceName = graphMgt.getOpenInstances().stream().filter(c -> c.contains("current")).findFirst().get();
- assertThat(connectionInstanceName, containsString(SERVICE_NAME));
- assertThat(connectionInstanceName, containsString("cached"));
- assertThat(connectionInstanceName, matchesPattern("^\\d+_[\\w\\-\\d]+_" + SERVICE_NAME + "_cached_\\d+\\(current\\)$"));
- graphMgt.rollback();
- }
+ JanusGraphManagement graphMgt = AAIGraph.getInstance().getGraph(DBConnectionType.CACHED).openManagement();
+ String connectionInstanceName =
+ graphMgt.getOpenInstances().stream().filter(c -> c.contains("current")).findFirst().get();
+ assertThat(connectionInstanceName, containsString(SERVICE_NAME));
+ assertThat(connectionInstanceName, containsString("cached"));
+ assertThat(connectionInstanceName,
+ matchesPattern("^\\d+_[\\w\\-\\d]+_" + SERVICE_NAME + "_cached_\\d+\\(current\\)$"));
+ graphMgt.rollback();
+ }
- @Test
- public void JanusGraphOpenNameTest() throws Exception{
- JanusGraph graph = JanusGraphFactory.open(new AAIGraphConfig.Builder(AAIConstants.REALTIME_DB_CONFIG).forService(SERVICE_NAME).withGraphType("graphType").buildConfiguration());
- JanusGraphManagement graphMgt = graph.openManagement();
- String connectionInstanceName = graphMgt.getOpenInstances().stream().filter(c -> c.contains("current")).findFirst().get();
- assertThat(connectionInstanceName,matchesPattern("^\\d+_[\\w\\-\\d]+_" + SERVICE_NAME + "_graphType_\\d+\\(current\\)$"));
- graphMgt.rollback();
- graph.close();
- }
+ @Test
+ public void JanusGraphOpenNameTest() throws Exception {
+ JanusGraph graph = JanusGraphFactory.open(new AAIGraphConfig.Builder(AAIConstants.REALTIME_DB_CONFIG)
+ .forService(SERVICE_NAME).withGraphType("graphType").buildConfiguration());
+ JanusGraphManagement graphMgt = graph.openManagement();
+ String connectionInstanceName =
+ graphMgt.getOpenInstances().stream().filter(c -> c.contains("current")).findFirst().get();
+ assertThat(connectionInstanceName,
+ matchesPattern("^\\d+_[\\w\\-\\d]+_" + SERVICE_NAME + "_graphType_\\d+\\(current\\)$"));
+ graphMgt.rollback();
+ graph.close();
+ }
- @Test (expected=FileNotFoundException.class)
- public void JanusGraphOpenNameWithInvalidFilePathTest() throws Exception{
- JanusGraph graph = JanusGraphFactory.open(new AAIGraphConfig.Builder("invalid").forService(SERVICE_NAME).withGraphType("graphType").buildConfiguration());
- JanusGraphManagement graphMgt = graph.openManagement();
- String connectionInstanceName = graphMgt.getOpenInstances().stream().filter(c -> c.contains("current")).findFirst().get();
- assertThat(connectionInstanceName,matchesPattern("^\\d+_[\\w\\-\\d]+_" + SERVICE_NAME + "_graphType_\\d+\\(current\\)$"));
- graphMgt.rollback();
- graph.close();
- }
+ @Test(expected = FileNotFoundException.class)
+ public void JanusGraphOpenNameWithInvalidFilePathTest() throws Exception {
+ JanusGraph graph = JanusGraphFactory.open(new AAIGraphConfig.Builder("invalid").forService(SERVICE_NAME)
+ .withGraphType("graphType").buildConfiguration());
+ JanusGraphManagement graphMgt = graph.openManagement();
+ String connectionInstanceName =
+ graphMgt.getOpenInstances().stream().filter(c -> c.contains("current")).findFirst().get();
+ assertThat(connectionInstanceName,
+ matchesPattern("^\\d+_[\\w\\-\\d]+_" + SERVICE_NAME + "_graphType_\\d+\\(current\\)$"));
+ graphMgt.rollback();
+ graph.close();
+ }
- @Ignore("Need to create schema specific to the test")
+ @Ignore("Need to create schema specific to the test")
@Test
public void checkIndexOfAliasedIndexedProps() throws Exception {
Set<String> aliasedIndexedProps = getAliasedIndexedProps();
@@ -104,14 +115,15 @@ public class AAIGraphTest extends AAISetup{
JanusGraphIndex index = graphMgt.getGraphIndex(aliasedIndexedProp);
assertNotNull(aliasedIndexedProp + " index exists", index);
assertEquals(aliasedIndexedProp + " index has 1 property keys", index.getFieldKeys().length, 1);
- assertThat(aliasedIndexedProp + " index indexes " + aliasedIndexedProp + " property key", index.getFieldKeys()[0].name(), is(aliasedIndexedProp));
+ assertThat(aliasedIndexedProp + " index indexes " + aliasedIndexedProp + " property key",
+ index.getFieldKeys()[0].name(), is(aliasedIndexedProp));
}
graphMgt.rollback();
}
private Set<String> getAliasedIndexedProps() {
Set<String> aliasedIndexedProps = new HashSet<>();
- LoaderFactory loaderFactory = SpringContextAware.getBean(LoaderFactory.class);
+ LoaderFactory loaderFactory = SpringContextAware.getBean(LoaderFactory.class);
SchemaVersions schemaVersions = SpringContextAware.getBean(SchemaVersions.class);
Loader loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getDefaultVersion());
Map<String, Introspector> objs = loader.getAllObjects();
diff --git a/aai-core/src/test/java/org/onap/aai/domain/restPolicyException/PolicyExceptionTest.java b/aai-core/src/test/java/org/onap/aai/domain/restPolicyException/PolicyExceptionTest.java
index e537c3df..63f01475 100644
--- a/aai-core/src/test/java/org/onap/aai/domain/restPolicyException/PolicyExceptionTest.java
+++ b/aai-core/src/test/java/org/onap/aai/domain/restPolicyException/PolicyExceptionTest.java
@@ -19,6 +19,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.domain.restPolicyException;
import static org.junit.Assert.assertEquals;
@@ -30,9 +31,9 @@ import org.junit.Before;
import org.junit.Test;
import org.onap.aai.AAISetup;
-public class PolicyExceptionTest extends AAISetup{
+public class PolicyExceptionTest extends AAISetup {
private PolicyException exception;
-
+
@Before
public void setup() {
exception = new PolicyException();
@@ -43,13 +44,13 @@ public class PolicyExceptionTest extends AAISetup{
exception.setAdditionalProperty("property1", "value1");
assertEquals(exception.getAdditionalProperties().get("property1"), "value1");
}
-
+
@Test
public void testGetMessageId() throws Exception {
exception.setMessageId("samplemessage");
assertEquals(exception.getMessageId(), "samplemessage");
}
-
+
@Test
public void testGetText() throws Exception {
exception.setText("sampletext");
@@ -63,6 +64,6 @@ public class PolicyExceptionTest extends AAISetup{
expectedVariables.add("secondvariable");
exception.setVariables(expectedVariables);
assertEquals(exception.getVariables(), expectedVariables);
-
+
}
}
diff --git a/aai-core/src/test/java/org/onap/aai/domain/restPolicyException/RequestErrorTest.java b/aai-core/src/test/java/org/onap/aai/domain/restPolicyException/RequestErrorTest.java
index 77e95e48..803337aa 100644
--- a/aai-core/src/test/java/org/onap/aai/domain/restPolicyException/RequestErrorTest.java
+++ b/aai-core/src/test/java/org/onap/aai/domain/restPolicyException/RequestErrorTest.java
@@ -19,6 +19,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.domain.restPolicyException;
import static org.junit.Assert.assertEquals;
@@ -27,9 +28,9 @@ import org.junit.Before;
import org.junit.Test;
import org.onap.aai.AAISetup;
-public class RequestErrorTest extends AAISetup{
+public class RequestErrorTest extends AAISetup {
private RequestError reqError;
-
+
@Before
public void setup() {
reqError = new RequestError();
diff --git a/aai-core/src/test/java/org/onap/aai/exceptions/AAIExceptionTest.java b/aai-core/src/test/java/org/onap/aai/exceptions/AAIExceptionTest.java
index 99597f7f..aef06fae 100644
--- a/aai-core/src/test/java/org/onap/aai/exceptions/AAIExceptionTest.java
+++ b/aai-core/src/test/java/org/onap/aai/exceptions/AAIExceptionTest.java
@@ -17,20 +17,21 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.exceptions;
+import static org.junit.Assert.assertEquals;
+
import org.junit.Test;
import org.onap.aai.AAISetup;
-import static org.junit.Assert.assertEquals;
-
public class AAIExceptionTest extends AAISetup {
private static final String code = "4004";
private static final String details = "This is a detailed description of the exception.";
private static final Throwable cause = new RuntimeException("This is a runtime exception.");
private static final Throwable noMessage = new RuntimeException();
-
+
/**
* Test constructor with 0 params.
*
@@ -41,7 +42,7 @@ public class AAIExceptionTest extends AAISetup {
AAIException exception = new AAIException();
assertEquals(exception, exception);
}
-
+
/**
* Test constructor with 1 params.
*
@@ -52,7 +53,7 @@ public class AAIExceptionTest extends AAISetup {
AAIException exception = new AAIException(code);
assertEquals(exception, exception);
}
-
+
/**
* Test constructor with 2 params details.
*
@@ -63,7 +64,7 @@ public class AAIExceptionTest extends AAISetup {
AAIException exception = new AAIException(code, details);
assertEquals(details, exception.getMessage());
}
-
+
/**
* Test constructor with 2 params cause.
*
@@ -74,7 +75,7 @@ public class AAIExceptionTest extends AAISetup {
AAIException exception = new AAIException(code, cause);
assertEquals("java.lang.RuntimeException: This is a runtime exception.", exception.getMessage());
}
-
+
/**
* Test constructor with 2 params null message.
*
@@ -85,7 +86,7 @@ public class AAIExceptionTest extends AAISetup {
AAIException exception = new AAIException(code, noMessage);
assertEquals(noMessage.toString(), exception.getMessage());
}
-
+
/**
* Test constructor with 3 params.
*
@@ -97,7 +98,7 @@ public class AAIExceptionTest extends AAISetup {
String details = "This is a detailed description of the exception.";
assertEquals(details, exception.getMessage());
}
-
+
/**
* Test constructor with 3 params null message.
*
diff --git a/aai-core/src/test/java/org/onap/aai/exceptions/AAIExceptionWithInfoTest.java b/aai-core/src/test/java/org/onap/aai/exceptions/AAIExceptionWithInfoTest.java
index b0727813..34620731 100644
--- a/aai-core/src/test/java/org/onap/aai/exceptions/AAIExceptionWithInfoTest.java
+++ b/aai-core/src/test/java/org/onap/aai/exceptions/AAIExceptionWithInfoTest.java
@@ -17,18 +17,18 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.exceptions;
-import org.junit.Test;
-import org.onap.aai.AAISetup;
+import static org.junit.Assert.assertEquals;
import java.util.HashMap;
-import static org.junit.Assert.assertEquals;
+import org.junit.Test;
+import org.onap.aai.AAISetup;
public class AAIExceptionWithInfoTest extends AAISetup {
-
private static final HashMap<String, Object> map = new HashMap<String, Object>();
{
@@ -124,11 +124,11 @@ public class AAIExceptionWithInfoTest extends AAISetup {
HashMap<String, Object> newMap = new HashMap<String, Object>();
newMap.put("itemInteger", 2);
exception.setInfoHash(newMap);
-
+
assertEquals(newMap, exception.getInfoHash());
assertEquals(info, exception.getInfo());
}
-
+
/**
* Test set info.
*/
@@ -138,7 +138,7 @@ public class AAIExceptionWithInfoTest extends AAISetup {
String newInfo = "This is updated info.";
exception.setInfo(newInfo);
-
+
assertEquals(map, exception.getInfoHash());
assertEquals(newInfo, exception.getInfo());
}
diff --git a/aai-core/src/test/java/org/onap/aai/introspection/IntrospectorTestSpec.java b/aai-core/src/test/java/org/onap/aai/introspection/IntrospectorTestSpec.java
index 44cbe6cc..804ce1bd 100644
--- a/aai-core/src/test/java/org/onap/aai/introspection/IntrospectorTestSpec.java
+++ b/aai-core/src/test/java/org/onap/aai/introspection/IntrospectorTestSpec.java
@@ -17,41 +17,31 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.introspection;
+import static org.junit.Assert.assertEquals;
+
import org.onap.aai.AAISetup;
import org.onap.aai.introspection.exceptions.AAIUnknownObjectException;
-import static org.junit.Assert.assertEquals;
-
public abstract class IntrospectorTestSpec extends AAISetup {
-
-
/**
* Container test set.
*
* @param wrappedPortGroups the wrapped port groups
- * @throws AAIUnknownObjectException
+ * @throws AAIUnknownObjectException
*/
protected void containerTestSet(Introspector wrappedPortGroups) throws AAIUnknownObjectException {
-
- assertEquals(
- "isContainer",
- true,
- wrappedPortGroups.isContainer());
-
- assertEquals(
- "newInstanceOfNestedProperty",
- "PortGroup",
+
+ assertEquals("isContainer", true, wrappedPortGroups.isContainer());
+
+ assertEquals("newInstanceOfNestedProperty", "PortGroup",
wrappedPortGroups.newInstanceOfNestedProperty("port-group").getClass().getSimpleName());
-
- assertEquals(
- "isComplexGenericType",
- true,
- wrappedPortGroups.isComplexGenericType("port-group"));
-
-
+
+ assertEquals("isComplexGenericType", true, wrappedPortGroups.isComplexGenericType("port-group"));
+
}
-
+
}
diff --git a/aai-core/src/test/java/org/onap/aai/introspection/JSONStrategyTest.java b/aai-core/src/test/java/org/onap/aai/introspection/JSONStrategyTest.java
index 65b13c27..8b44b312 100644
--- a/aai-core/src/test/java/org/onap/aai/introspection/JSONStrategyTest.java
+++ b/aai-core/src/test/java/org/onap/aai/introspection/JSONStrategyTest.java
@@ -17,26 +17,26 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.introspection;
-import org.json.simple.JSONArray;
+import java.util.HashSet;
+import java.util.Set;
+import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.onap.aai.AAISetup;
-import java.util.HashSet;
-import java.util.Set;
-
-public class JSONStrategyTest extends AAISetup{
+public class JSONStrategyTest extends AAISetup {
private JSONStrategy jsonStrategy;
private JSONStrategy jsonStrategyContainer;
private JSONStrategy jsonStrategyComplex;
@Before
- public void setup(){
+ public void setup() {
try {
JSONObject pserver = new JSONObject();
pserver.put("hostname", "value1");
@@ -54,14 +54,13 @@ public class JSONStrategyTest extends AAISetup{
JSONObject complex = new JSONObject();
complex.put("pserver", pserver);
jsonStrategyComplex = new JSONStrategy(complex, "pservers-type");
- }
- catch (Exception e){
+ } catch (Exception e) {
System.out.println("error during setup: " + e.getMessage());
}
}
@Test
- public void getSetTest(){
+ public void getSetTest() {
jsonStrategy.setValue("ramInMegabytes", 1024);
Assert.assertEquals("value1", jsonStrategy.getValue("hostname"));
Assert.assertEquals(4, jsonStrategy.getValue("numberofCpus"));
@@ -79,7 +78,8 @@ public class JSONStrategyTest extends AAISetup{
@Test
public void getGenericTypeTest() {
// If the values of this object are arrays, return the type within the array
- Assert.assertEquals("class org.json.simple.JSONObject" , jsonStrategyContainer.getGenericTypeClass("pservers").toString());
+ Assert.assertEquals("class org.json.simple.JSONObject",
+ jsonStrategyContainer.getGenericTypeClass("pservers").toString());
}
@Test
@@ -87,6 +87,7 @@ public class JSONStrategyTest extends AAISetup{
Assert.assertEquals("org.json.simple.JSONObject", jsonStrategy.getJavaClassName());
Assert.assertEquals("org.json.simple.JSONObject", jsonStrategyContainer.getJavaClassName());
}
+
@Test
public void getTypeTest() {
Assert.assertEquals("java.lang.String", jsonStrategy.getType("hostname"));
@@ -100,16 +101,19 @@ public class JSONStrategyTest extends AAISetup{
@Test
public void newInstanceOfPropertyTest() {
- Assert.assertEquals("class org.json.simple.JSONArray", jsonStrategyContainer.newInstanceOfProperty("pservers").getClass().toString());
+ Assert.assertEquals("class org.json.simple.JSONArray",
+ jsonStrategyContainer.newInstanceOfProperty("pservers").getClass().toString());
}
@Test(expected = NullPointerException.class)
public void newInvalidInstanceOfPropertyTest() {
Assert.assertEquals(null, jsonStrategyContainer.newInstanceOfProperty("invalid").getClass().toString());
}
+
@Test
public void newInstanceOfNestedPropertyTest() {
- Assert.assertEquals("class org.json.simple.JSONObject", jsonStrategyContainer.newInstanceOfNestedProperty("pservers").getClass().toString());
+ Assert.assertEquals("class org.json.simple.JSONObject",
+ jsonStrategyContainer.newInstanceOfNestedProperty("pservers").getClass().toString());
}
@Test(expected = NullPointerException.class)
diff --git a/aai-core/src/test/java/org/onap/aai/introspection/MoxyEngineTest.java b/aai-core/src/test/java/org/onap/aai/introspection/MoxyEngineTest.java
index 463c9174..0e6a9aab 100644
--- a/aai-core/src/test/java/org/onap/aai/introspection/MoxyEngineTest.java
+++ b/aai-core/src/test/java/org/onap/aai/introspection/MoxyEngineTest.java
@@ -17,31 +17,30 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.introspection;
import org.junit.Test;
import org.onap.aai.introspection.exceptions.AAIUnknownObjectException;
import org.springframework.test.annotation.DirtiesContext;
-
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
public class MoxyEngineTest extends IntrospectorTestSpec {
/**
* Container object.
- * @throws AAIUnknownObjectException
+ *
+ * @throws AAIUnknownObjectException
*/
@Test
public void containerObject() throws AAIUnknownObjectException {
-
+
Loader loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getDepthVersion());
-
+
Introspector obj = loader.introspectorFromName("port-groups");
this.containerTestSet(obj);
-
+
}
-
-
-
+
}
diff --git a/aai-core/src/test/java/org/onap/aai/introspection/PropertyPredicatesTest.java b/aai-core/src/test/java/org/onap/aai/introspection/PropertyPredicatesTest.java
index 190e3243..4473c8d4 100644
--- a/aai-core/src/test/java/org/onap/aai/introspection/PropertyPredicatesTest.java
+++ b/aai-core/src/test/java/org/onap/aai/introspection/PropertyPredicatesTest.java
@@ -17,58 +17,56 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.introspection;
-import org.junit.Before;
+import static org.hamcrest.Matchers.hasItems;
+import static org.hamcrest.Matchers.not;
+import static org.junit.Assert.assertThat;
+import java.util.Set;
+
+import org.junit.Before;
import org.junit.Test;
import org.onap.aai.AAISetup;
import org.onap.aai.introspection.exceptions.AAIUnknownObjectException;
import org.springframework.test.annotation.DirtiesContext;
-import java.util.Set;
-
-import static org.hamcrest.Matchers.hasItems;
-import static org.hamcrest.Matchers.not;
-import static org.junit.Assert.assertThat;
-
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
public class PropertyPredicatesTest extends AAISetup {
private Loader loader;
private ModelType introspectorFactoryType = ModelType.MOXY;
private Introspector obj;
-
+
@Before
public void setup() throws Exception {
loader = loaderFactory.createLoaderForVersion(introspectorFactoryType, schemaVersions.getDefaultVersion());
obj = loader.introspectorFromName("generic-vnf");
}
-
+
@Test
public void includeInTestGeneration() throws AAIUnknownObjectException {
-
+
Set<String> props = obj.getProperties(PropertyPredicates.includeInTestGeneration());
- assertThat("props not found", props,
- not(hasItems("model-invariant-id", "model-version-id")));
+ assertThat("props not found", props, not(hasItems("model-invariant-id", "model-version-id")));
}
-
+
@Test
public void isVisible() throws AAIUnknownObjectException {
-
+
Set<String> props = obj.getProperties(PropertyPredicates.isVisible());
assertThat("props not found", props, hasItems("model-invariant-id", "model-version-id"));
}
-
+
@Test
public void all() throws AAIUnknownObjectException {
-
+
Set<String> props = obj.getProperties();
assertThat("all found", props, hasItems("model-invariant-id", "model-version-id"));
}
-
}
diff --git a/aai-core/src/test/java/org/onap/aai/introspection/generator/CreateExampleTest.java b/aai-core/src/test/java/org/onap/aai/introspection/generator/CreateExampleTest.java
index c7d4cf82..9c03331f 100644
--- a/aai-core/src/test/java/org/onap/aai/introspection/generator/CreateExampleTest.java
+++ b/aai-core/src/test/java/org/onap/aai/introspection/generator/CreateExampleTest.java
@@ -17,8 +17,15 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.introspection.generator;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import java.util.ArrayList;
+import java.util.List;
+
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
@@ -28,35 +35,27 @@ import org.onap.aai.exceptions.AAIException;
import org.onap.aai.introspection.*;
import org.onap.aai.introspection.exceptions.AAIUnknownObjectException;
-import java.util.ArrayList;
-import java.util.List;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
public class CreateExampleTest extends AAISetup {
-
- private static CreateExample createExample;
- private Loader loader;
+
+ private static CreateExample createExample;
+ private Loader loader;
private static boolean classLoaded = false;
-
-
+
@BeforeClass
public static void setUp() {
-
-
+
}
-
-
+
@Before
- public void createLoaderVersion(){
- if(!classLoaded){
+ public void createLoaderVersion() {
+ if (!classLoaded) {
loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getAppRootVersion());
createExample = new CreateExample(loader, "edge-prop-names");
classLoaded = false;
}
}
-
+
@Test
public void testGetExampleObject() throws AAIException {
Introspector introspector = loader.introspectorFromName("edge-prop-names");
@@ -70,7 +69,7 @@ public class CreateExampleTest extends AAISetup {
Introspector introspector = loader.introspectorFromName("edge-prop-names");
createExample.processPrimitive(propName, introspector);
}
-
+
@Test
public void testProcessPrimitiveLong() throws AAIUnknownObjectException {
String propName = "vlan-id-inner";
@@ -84,14 +83,14 @@ public class CreateExampleTest extends AAISetup {
Introspector introspector = loader.introspectorFromName("vserver");
createExample.processPrimitive(propName, introspector);
}
-
+
@Test
public void testProcessPrimitiveInteger() throws AAIUnknownObjectException {
String propName = "module-index";
Introspector introspector = loader.introspectorFromName("vf-module");
createExample.processPrimitive(propName, introspector);
}
-
+
@Test
public void testProcessPrimitiveList() throws AAIUnknownObjectException {
String propName = "ipaddress-v4-vig";
diff --git a/aai-core/src/test/java/org/onap/aai/introspection/sideeffect/DataCopyTest.java b/aai-core/src/test/java/org/onap/aai/introspection/sideeffect/DataCopyTest.java
index f9911295..79597355 100644
--- a/aai-core/src/test/java/org/onap/aai/introspection/sideeffect/DataCopyTest.java
+++ b/aai-core/src/test/java/org/onap/aai/introspection/sideeffect/DataCopyTest.java
@@ -17,15 +17,29 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.introspection.sideeffect;
-import org.janusgraph.core.JanusGraphFactory;
-import org.janusgraph.core.JanusGraph;
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.when;
+
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.lang.reflect.InvocationTargetException;
+import java.net.MalformedURLException;
+import java.net.URISyntaxException;
+import java.util.Arrays;
+import java.util.Collection;
+
import org.apache.commons.io.IOUtils;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.VertexProperty;
+import org.janusgraph.core.JanusGraph;
+import org.janusgraph.core.JanusGraphFactory;
import org.junit.*;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
@@ -35,95 +49,85 @@ import org.mockito.MockitoAnnotations;
import org.onap.aai.AAISetup;
import org.onap.aai.db.props.AAIProperties;
import org.onap.aai.dbmap.DBConnectionType;
+import org.onap.aai.edges.enums.EdgeProperty;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.introspection.*;
-
import org.onap.aai.introspection.sideeffect.exceptions.AAIMissingRequiredPropertyException;
import org.onap.aai.parsers.query.QueryParser;
import org.onap.aai.serialization.db.DBSerializer;
-import org.onap.aai.edges.enums.EdgeProperty;
-import org.onap.aai.serialization.engines.QueryStyle;
import org.onap.aai.serialization.engines.JanusGraphDBEngine;
+import org.onap.aai.serialization.engines.QueryStyle;
import org.onap.aai.serialization.engines.TransactionalGraphEngine;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.UnsupportedEncodingException;
-import java.lang.reflect.InvocationTargetException;
-import java.net.MalformedURLException;
-import java.net.URISyntaxException;
-import java.util.Arrays;
-import java.util.Collection;
-
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.when;
-
@RunWith(value = Parameterized.class)
-public class DataCopyTest extends AAISetup{
+public class DataCopyTest extends AAISetup {
-
-
private static JanusGraph graph;
private final static ModelType introspectorFactoryType = ModelType.MOXY;
private final static DBConnectionType type = DBConnectionType.REALTIME;
private static Loader loader;
private static TransactionalGraphEngine dbEngine;
- @Mock private Vertex self;
- @Mock private VertexProperty<String> prop;
- @Mock private QueryParser uriQuery;
- @Rule public ExpectedException thrown = ExpectedException.none();
+ @Mock
+ private Vertex self;
+ @Mock
+ private VertexProperty<String> prop;
+ @Mock
+ private QueryParser uriQuery;
+ @Rule
+ public ExpectedException thrown = ExpectedException.none();
-
-
@Parameterized.Parameter(value = 0)
public QueryStyle queryStyle;
@Parameterized.Parameters(name = "QueryStyle.{0}")
public static Collection<Object[]> data() {
- return Arrays.asList(new Object[][]{
- {QueryStyle.TRAVERSAL},
- {QueryStyle.TRAVERSAL_URI}
- });
+ return Arrays.asList(new Object[][] {{QueryStyle.TRAVERSAL}, {QueryStyle.TRAVERSAL_URI}});
}
-
-
+
@BeforeClass
public static void setup() throws NoSuchFieldException, SecurityException, Exception {
- graph = JanusGraphFactory.build().set("storage.backend","inmemory").open();
+ graph = JanusGraphFactory.build().set("storage.backend", "inmemory").open();
System.setProperty("AJSC_HOME", ".");
System.setProperty("BUNDLECONFIG_DIR", "src/test/resources/bundleconfig-local");
-
- graph.traversal().addV("aai-node-type", "model", "model-invariant-id", "key1", AAIProperties.AAI_URI, "/service-design-and-creation/models/model/key1").as("v1")
- .addV("aai-node-type", "model-ver", "model-ver", "myValue", "model-version-id", "key2", "model-version", "testValue", AAIProperties.AAI_URI, "/service-design-and-creation/models/model/key1/model-vers/model-ver/key2")
+
+ graph.traversal()
+ .addV("aai-node-type", "model", "model-invariant-id", "key1", AAIProperties.AAI_URI,
+ "/service-design-and-creation/models/model/key1")
+ .as("v1")
+ .addV("aai-node-type", "model-ver", "model-ver", "myValue", "model-version-id", "key2", "model-version",
+ "testValue", AAIProperties.AAI_URI,
+ "/service-design-and-creation/models/model/key1/model-vers/model-ver/key2")
.addOutE("org.onap.relationships.inventory.BelongsTo", "v1", EdgeProperty.CONTAINS.toString(), true)
- .addV("aai-node-type", "model", "model-invariant-id", "key3", AAIProperties.AAI_URI, "/service-design-and-creation/models/model/key3").as("v2")
- .addV("aai-node-type", "model-ver", "model-ver", "myValue", "model-version-id", "key4", AAIProperties.AAI_URI, "/service-design-and-creation/models/model/key3/model-vers/model-ver/key4")
+ .addV("aai-node-type", "model", "model-invariant-id", "key3", AAIProperties.AAI_URI,
+ "/service-design-and-creation/models/model/key3")
+ .as("v2")
+ .addV("aai-node-type", "model-ver", "model-ver", "myValue", "model-version-id", "key4",
+ AAIProperties.AAI_URI,
+ "/service-design-and-creation/models/model/key3/model-vers/model-ver/key4")
.addOutE("org.onap.relationships.inventory.BelongsTo", "v2", EdgeProperty.CONTAINS.toString(), true)
- .next();
+ .next();
graph.tx().commit();
}
-
+
@AfterClass
public static void tearDown() {
graph.tx().rollback();
graph.close();
}
-
+
@Before
public void initMock() {
loader = loaderFactory.createLoaderForVersion(introspectorFactoryType, schemaVersions.getDefaultVersion());
MockitoAnnotations.initMocks(this);
- dbEngine = new JanusGraphDBEngine(
- queryStyle,
- type,
- loader);
+ dbEngine = new JanusGraphDBEngine(queryStyle, type, loader);
}
-
+
@Test
- public void runPopulatePersonaModelVer() throws URISyntaxException, AAIException, UnsupportedEncodingException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException, InstantiationException, NoSuchMethodException, MalformedURLException {
-
+ public void runPopulatePersonaModelVer() throws URISyntaxException, AAIException, UnsupportedEncodingException,
+ IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException,
+ InstantiationException, NoSuchMethodException, MalformedURLException {
+
final Loader loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getDefaultVersion());
final Introspector obj = loader.introspectorFromName("generic-vnf");
obj.setValue("vnf-id", "myId");
@@ -137,25 +141,26 @@ public class DataCopyTest extends AAISetup{
when(adminSpy.getTraversalSource()).thenReturn(traversal);
when(self.<String>property(AAIProperties.AAI_URI)).thenReturn(prop);
when(prop.orElse(null)).thenReturn(obj.getURI());
- DBSerializer serializer = new DBSerializer(schemaVersions.getDefaultVersion(), spy, introspectorFactoryType, "AAI_TEST");
- SideEffectRunner runner = new SideEffectRunner
- .Builder(spy, serializer).addSideEffect(DataCopy.class).build();
-
+ DBSerializer serializer =
+ new DBSerializer(schemaVersions.getDefaultVersion(), spy, introspectorFactoryType, "AAI_TEST");
+ SideEffectRunner runner = new SideEffectRunner.Builder(spy, serializer).addSideEffect(DataCopy.class).build();
+
runner.execute(obj, self);
assertEquals("value populated", "testValue", obj.getValue("persona-model-version"));
-
+
g.tx().rollback();
-
-
+
}
-
+
@Test
- public void verifyNestedSideEffect() throws URISyntaxException, AAIException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException, InstantiationException, NoSuchMethodException, IOException {
-
+ public void verifyNestedSideEffect()
+ throws URISyntaxException, AAIException, IllegalAccessException, IllegalArgumentException,
+ InvocationTargetException, SecurityException, InstantiationException, NoSuchMethodException, IOException {
+
final Loader loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getDefaultVersion());
final Introspector obj = loader.unmarshal("customer", this.getJsonString("nested-case.json"));
- //System.out.println(obj.marshal(true));
+ // System.out.println(obj.marshal(true));
TransactionalGraphEngine spy = spy(dbEngine);
TransactionalGraphEngine.Admin adminSpy = spy(dbEngine.asAdmin());
Graph g = graph.newTransaction();
@@ -166,19 +171,21 @@ public class DataCopyTest extends AAISetup{
when(self.<String>property(AAIProperties.AAI_URI)).thenReturn(prop);
when(prop.orElse(null)).thenReturn(obj.getURI());
when(uriQuery.isDependent()).thenReturn(false);
- DBSerializer serializer = new DBSerializer(schemaVersions.getDefaultVersion(), spy, introspectorFactoryType, "AAI_TEST");
- Vertex v= serializer.createNewVertex(obj);
+ DBSerializer serializer =
+ new DBSerializer(schemaVersions.getDefaultVersion(), spy, introspectorFactoryType, "AAI_TEST");
+ Vertex v = serializer.createNewVertex(obj);
serializer.serializeToDb(obj, v, uriQuery, obj.getURI(), "test");
-
- assertEquals("nested value populated", "testValue", g.traversal().V().has("service-instance-id", "nested-instance-key").next().property("persona-model-version").orElse(""));
+
+ assertEquals("nested value populated", "testValue", g.traversal().V()
+ .has("service-instance-id", "nested-instance-key").next().property("persona-model-version").orElse(""));
g.tx().rollback();
}
-
+
@Test
public void expectedMissingPropertyExceptionInURI() throws AAIException, UnsupportedEncodingException {
-
+
final Loader loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getDefaultVersion());
final Introspector obj = loader.introspectorFromName("generic-vnf");
obj.setValue("vnf-id", "myId");
@@ -192,14 +199,14 @@ public class DataCopyTest extends AAISetup{
when(adminSpy.getTraversalSource()).thenReturn(traversal);
when(self.<String>property(AAIProperties.AAI_URI)).thenReturn(prop);
when(prop.orElse(null)).thenReturn(obj.getURI());
- DBSerializer serializer = new DBSerializer(schemaVersions.getDefaultVersion(), spy, introspectorFactoryType, "AAI_TEST");
- SideEffectRunner runner = new SideEffectRunner
- .Builder(spy, serializer).addSideEffect(DataCopy.class).build();
-
+ DBSerializer serializer =
+ new DBSerializer(schemaVersions.getDefaultVersion(), spy, introspectorFactoryType, "AAI_TEST");
+ SideEffectRunner runner = new SideEffectRunner.Builder(spy, serializer).addSideEffect(DataCopy.class).build();
+
thrown.expect(AAIMissingRequiredPropertyException.class);
runner.execute(obj, self);
}
-
+
@Test
public void expectedMissingPropertyExceptionForResultingObject() throws AAIException, UnsupportedEncodingException {
final Loader loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getDefaultVersion());
@@ -216,14 +223,14 @@ public class DataCopyTest extends AAISetup{
when(adminSpy.getTraversalSource()).thenReturn(traversal);
when(self.<String>property(AAIProperties.AAI_URI)).thenReturn(prop);
when(prop.orElse(null)).thenReturn(obj.getURI());
- DBSerializer serializer = new DBSerializer(schemaVersions.getDefaultVersion(), spy, introspectorFactoryType, "AAI_TEST");
- SideEffectRunner runner = new SideEffectRunner
- .Builder(spy, serializer).addSideEffect(DataCopy.class).build();
-
+ DBSerializer serializer =
+ new DBSerializer(schemaVersions.getDefaultVersion(), spy, introspectorFactoryType, "AAI_TEST");
+ SideEffectRunner runner = new SideEffectRunner.Builder(spy, serializer).addSideEffect(DataCopy.class).build();
+
thrown.expect(AAIMissingRequiredPropertyException.class);
runner.execute(obj, self);
}
-
+
@Test
public void expectNoProcessingWithNoProperties() throws AAIException, UnsupportedEncodingException {
final Loader loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getDefaultVersion());
@@ -238,24 +245,23 @@ public class DataCopyTest extends AAISetup{
when(adminSpy.getTraversalSource()).thenReturn(traversal);
when(self.<String>property(AAIProperties.AAI_URI)).thenReturn(prop);
when(prop.orElse(null)).thenReturn(obj.getURI());
- DBSerializer serializer = new DBSerializer(schemaVersions.getDefaultVersion(), spy, introspectorFactoryType, "AAI_TEST");
- SideEffectRunner runner = new SideEffectRunner
- .Builder(spy, serializer).addSideEffect(DataCopy.class).build();
-
+ DBSerializer serializer =
+ new DBSerializer(schemaVersions.getDefaultVersion(), spy, introspectorFactoryType, "AAI_TEST");
+ SideEffectRunner runner = new SideEffectRunner.Builder(spy, serializer).addSideEffect(DataCopy.class).build();
+
runner.execute(obj, self);
-
+
assertEquals("no model-version-id", true, obj.getValue("model-version-id") == null);
assertEquals("no model-invariant-id", true, obj.getValue("model-invariant-id") == null);
-
+
}
-
+
private String getJsonString(String filename) throws IOException {
-
-
+
FileInputStream is = new FileInputStream("src/test/resources/oxm/sideeffect/" + filename);
- String s = IOUtils.toString(is, "UTF-8");
+ String s = IOUtils.toString(is, "UTF-8");
IOUtils.closeQuietly(is);
-
+
return s;
}
}
diff --git a/aai-core/src/test/java/org/onap/aai/introspection/sideeffect/DataLinkTest.java b/aai-core/src/test/java/org/onap/aai/introspection/sideeffect/DataLinkTest.java
index 5b9a0fa6..cec342ea 100644
--- a/aai-core/src/test/java/org/onap/aai/introspection/sideeffect/DataLinkTest.java
+++ b/aai-core/src/test/java/org/onap/aai/introspection/sideeffect/DataLinkTest.java
@@ -17,18 +17,32 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.introspection.sideeffect;
-import org.janusgraph.core.JanusGraphFactory;
-import org.janusgraph.core.JanusGraph;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.*;
+import static org.junit.Assert.*;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.when;
+
+import java.io.UnsupportedEncodingException;
+import java.lang.reflect.InvocationTargetException;
+import java.net.MalformedURLException;
+import java.net.URISyntaxException;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.List;
+
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
+import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.Vertex;
-import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.VertexProperty;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.*;
+import org.janusgraph.core.JanusGraph;
+import org.janusgraph.core.JanusGraphFactory;
import org.junit.*;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
@@ -39,28 +53,15 @@ import org.onap.aai.AAISetup;
import org.onap.aai.DataLinkSetup;
import org.onap.aai.db.props.AAIProperties;
import org.onap.aai.dbmap.DBConnectionType;
+import org.onap.aai.edges.enums.EdgeProperty;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.introspection.*;
import org.onap.aai.parsers.query.QueryParser;
import org.onap.aai.serialization.db.DBSerializer;
-import org.onap.aai.edges.enums.EdgeProperty;
-import org.onap.aai.serialization.engines.QueryStyle;
import org.onap.aai.serialization.engines.JanusGraphDBEngine;
+import org.onap.aai.serialization.engines.QueryStyle;
import org.onap.aai.serialization.engines.TransactionalGraphEngine;
-import java.io.UnsupportedEncodingException;
-import java.lang.reflect.InvocationTargetException;
-import java.net.MalformedURLException;
-import java.net.URISyntaxException;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.List;
-
-import static org.junit.Assert.*;
-import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.when;
-
@RunWith(value = Parameterized.class)
public class DataLinkTest extends DataLinkSetup {
@@ -69,71 +70,88 @@ public class DataLinkTest extends DataLinkSetup {
private final static DBConnectionType type = DBConnectionType.REALTIME;
private static Loader loader;
private static TransactionalGraphEngine dbEngine;
- @Mock private QueryParser parser;
- @Mock private Vertex self;
- @Mock private VertexProperty<String> prop;
+ @Mock
+ private QueryParser parser;
+ @Mock
+ private Vertex self;
+ @Mock
+ private VertexProperty<String> prop;
@Rule
public ExpectedException thrown = ExpectedException.none();
-
-
@Parameterized.Parameter(value = 0)
public QueryStyle queryStyle;
@Parameterized.Parameters(name = "QueryStyle.{0}")
public static Collection<Object[]> data() {
- return Arrays.asList(new Object[][]{
- {QueryStyle.TRAVERSAL},
- {QueryStyle.TRAVERSAL_URI}
- });
+ return Arrays.asList(new Object[][] {{QueryStyle.TRAVERSAL}, {QueryStyle.TRAVERSAL_URI}});
}
-
+
@BeforeClass
public static void setup() throws NoSuchFieldException, SecurityException, Exception {
- graph = JanusGraphFactory.build().set("storage.backend","inmemory").open();
-
+ graph = JanusGraphFactory.build().set("storage.backend", "inmemory").open();
- graph.traversal().addV("aai-node-type", "vpn-binding", "vpn-id", "addKey", AAIProperties.AAI_URI, "/network/vpn-bindings/vpn-binding/addKey").as("v1")
- .addV("aai-node-type", "vpn-binding", "vpn-id", "modifyKey", AAIProperties.AAI_URI, "/network/vpn-bindings/vpn-binding/modifyKey").as("v2")
- .addV("aai-node-type", "route-target", "global-route-target", "modifyTargetKey", "route-target-role", "modifyRoleKey", "linked", true, AAIProperties.AAI_URI, "/network/vpn-bindings/vpn-binding/modifyKey/route-targets/route-target/modifyTargetKey/modifyRoleKey")
+ graph.traversal()
+ .addV("aai-node-type", "vpn-binding", "vpn-id", "addKey", AAIProperties.AAI_URI,
+ "/network/vpn-bindings/vpn-binding/addKey")
+ .as("v1")
+ .addV("aai-node-type", "vpn-binding", "vpn-id", "modifyKey", AAIProperties.AAI_URI,
+ "/network/vpn-bindings/vpn-binding/modifyKey")
+ .as("v2")
+ .addV("aai-node-type", "route-target", "global-route-target", "modifyTargetKey", "route-target-role",
+ "modifyRoleKey", "linked", true, AAIProperties.AAI_URI,
+ "/network/vpn-bindings/vpn-binding/modifyKey/route-targets/route-target/modifyTargetKey/modifyRoleKey")
.addOutE("org.onap.relationships.inventory.BelongsTo", "v2", EdgeProperty.CONTAINS.toString(), true)
- .addV("aai-node-type", "vpn-binding", "vpn-id", "deleteKey",AAIProperties.AAI_URI, "/network/vpn-bindings/vpn-binding/deleteKey").as("v3" )
- .addV("aai-node-type", "route-target", "global-route-target", "deleteTargetKey", "route-target-role", "deleteRoleKey", "linked", true, AAIProperties.AAI_URI, "/network/vpn-bindings/vpn-binding/deleteKey/route-targets/route-target/deleteTargetKey/deleteRoleKey")
+ .addV("aai-node-type", "vpn-binding", "vpn-id", "deleteKey", AAIProperties.AAI_URI,
+ "/network/vpn-bindings/vpn-binding/deleteKey")
+ .as("v3")
+ .addV("aai-node-type", "route-target", "global-route-target", "deleteTargetKey", "route-target-role",
+ "deleteRoleKey", "linked", true, AAIProperties.AAI_URI,
+ "/network/vpn-bindings/vpn-binding/deleteKey/route-targets/route-target/deleteTargetKey/deleteRoleKey")
.addOutE("org.onap.relationships.inventory.BelongsTo", "v3", EdgeProperty.CONTAINS.toString(), true)
- .addV("aai-node-type", "vpn-binding", "vpn-id", "getKey", AAIProperties.AAI_URI, "/network/vpn-bindings/vpn-binding/getKey").as("v4")
- .addV("aai-node-type", "route-target", "global-route-target", "getTargetKey", "route-target-role", "getRoleKey", "linked", true, AAIProperties.AAI_URI, "/network/vpn-bindings/vpn-binding/getKey/route-targets/route-target/getTargetKeyNoLink/getRoleKeyNoLink")
+ .addV("aai-node-type", "vpn-binding", "vpn-id", "getKey", AAIProperties.AAI_URI,
+ "/network/vpn-bindings/vpn-binding/getKey")
+ .as("v4")
+ .addV("aai-node-type", "route-target", "global-route-target", "getTargetKey", "route-target-role",
+ "getRoleKey", "linked", true, AAIProperties.AAI_URI,
+ "/network/vpn-bindings/vpn-binding/getKey/route-targets/route-target/getTargetKeyNoLink/getRoleKeyNoLink")
.addOutE("org.onap.relationships.inventory.BelongsTo", "v4", EdgeProperty.CONTAINS.toString(), true)
- .addV("aai-node-type", "vpn-binding", "vpn-id", "getKeyNoLink", AAIProperties.AAI_URI, "/network/vpn-bindings/vpn-binding/getKeyNoLink").as("v5")
- .addV("aai-node-type", "route-target", "global-route-target", "getTargetKeyNoLink", "route-target-role", "getRoleKeyNoLink", AAIProperties.AAI_URI, "/network/vpn-bindings/vpn-binding/getKeyNoLink/route-targets/route-target/getTargetKeyNoLink/getRoleKeyNoLink")
+ .addV("aai-node-type", "vpn-binding", "vpn-id", "getKeyNoLink", AAIProperties.AAI_URI,
+ "/network/vpn-bindings/vpn-binding/getKeyNoLink")
+ .as("v5")
+ .addV("aai-node-type", "route-target", "global-route-target", "getTargetKeyNoLink", "route-target-role",
+ "getRoleKeyNoLink", AAIProperties.AAI_URI,
+ "/network/vpn-bindings/vpn-binding/getKeyNoLink/route-targets/route-target/getTargetKeyNoLink/getRoleKeyNoLink")
.addOutE("org.onap.relationships.inventory.BelongsTo", "v5", EdgeProperty.CONTAINS.toString(), true)
- .next();
+ .next();
graph.tx().commit();
- /*Commented for SysOut issues
+ /*
+ * Commented for SysOut issues
*/
- //graph.traversal().V().has("aai-uri","/network/vpn-bindings/vpn-binding/deleteKey").properties().forEachRemaining(p->System.out.println(p.key() +" : " + p.value()));
-
+ // graph.traversal().V().has("aai-uri","/network/vpn-bindings/vpn-binding/deleteKey").properties().forEachRemaining(p->System.out.println(p.key()
+ // +" : " + p.value()));
+
}
-
+
@AfterClass
public static void tearDown() {
graph.tx().rollback();
graph.close();
}
-
+
@Before
public void initMock() {
loader = loaderFactory.createLoaderForVersion(introspectorFactoryType, schemaVersions.getDefaultVersion());
MockitoAnnotations.initMocks(this);
- dbEngine = new JanusGraphDBEngine(
- queryStyle,
- type,
- loader);
+ dbEngine = new JanusGraphDBEngine(queryStyle, type, loader);
}
-
+
@Test
- public void verifyCreationOfVertex() throws URISyntaxException, AAIException, UnsupportedEncodingException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException, InstantiationException, NoSuchMethodException, MalformedURLException {
-
+ public void verifyCreationOfVertex() throws URISyntaxException, AAIException, UnsupportedEncodingException,
+ IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException,
+ InstantiationException, NoSuchMethodException, MalformedURLException {
+
final Loader loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getDepthVersion());
final Introspector obj = loader.introspectorFromName("vpn-binding");
obj.setValue("vpn-id", "addKey");
@@ -143,44 +161,48 @@ public class DataLinkTest extends DataLinkSetup {
TransactionalGraphEngine.Admin adminSpy = spy(dbEngine.asAdmin());
Graph g = graph.newTransaction();
GraphTraversalSource traversal = g.traversal();
-// Graph g = graph.newTransaction();
-// GraphTraversalSource traversal = g;
- // System.out.println("Begin method inventory:");
+ // Graph g = graph.newTransaction();
+ // GraphTraversalSource traversal = g;
+ // System.out.println("Begin method inventory:");
Iterator<Vertex> vertexItr = traversal.V();
- while( vertexItr != null && vertexItr.hasNext() ){
+ while (vertexItr != null && vertexItr.hasNext()) {
Vertex v = vertexItr.next();
- // System.out.println("\nnodeType="+v.<String>property("aai-node-type"));
- for(String key: v.keys()) {
- // System.out.println("label="+v.label()+";key= "+key+";value= "+v.value(key)+";id= "+v.id());
+ // System.out.println("\nnodeType="+v.<String>property("aai-node-type"));
+ for (String key : v.keys()) {
+ // System.out.println("label="+v.label()+";key= "+key+";value= "+v.value(key)+";id= "+v.id());
}
Direction d = null;
Iterator<Edge> edgeItr = v.edges(Direction.BOTH);
- while( edgeItr != null && edgeItr.hasNext() ){
+ while (edgeItr != null && edgeItr.hasNext()) {
Edge e = edgeItr.next();
- //System.out.println("outV="+e.outVertex().property(AAIProperties.NODE_TYPE)+"/"+e.outVertex().id()+";inV= "+e.inVertex().property(AAIProperties.NODE_TYPE)+"/"+e.inVertex().id());
+ // System.out.println("outV="+e.outVertex().property(AAIProperties.NODE_TYPE)+"/"+e.outVertex().id()+";inV=
+ // "+e.inVertex().property(AAIProperties.NODE_TYPE)+"/"+e.inVertex().id());
}
}
- //System.out.println("End method inventory:");
+ // System.out.println("End method inventory:");
when(spy.asAdmin()).thenReturn(adminSpy);
when(adminSpy.getTraversalSource()).thenReturn(traversal);
when(spy.tx()).thenReturn(g);
when(self.<String>property(AAIProperties.AAI_URI)).thenReturn(prop);
when(prop.orElse(null)).thenReturn(obj.getURI());
- DBSerializer serializer = new DBSerializer(schemaVersions.getDefaultVersion(), spy, introspectorFactoryType, "AAI_TEST");
- SideEffectRunner runner = new SideEffectRunner
- .Builder(spy, serializer).addSideEffect(DataLinkWriter.class).build();
-
+ DBSerializer serializer =
+ new DBSerializer(schemaVersions.getDefaultVersion(), spy, introspectorFactoryType, "AAI_TEST");
+ SideEffectRunner runner =
+ new SideEffectRunner.Builder(spy, serializer).addSideEffect(DataLinkWriter.class).build();
+
runner.execute(obj, self);
- assertEquals("route-target vertex found", true, traversal.V()
- .has(AAIProperties.NODE_TYPE, "route-target").has("global-route-target", "key1").has("route-target-role", "key2").has("linked", true).hasNext());
+ assertEquals("route-target vertex found", true, traversal.V().has(AAIProperties.NODE_TYPE, "route-target")
+ .has("global-route-target", "key1").has("route-target-role", "key2").has("linked", true).hasNext());
g.tx().rollback();
-
+
}
-
+
@Test
- public void verifyModificationOfVertex() throws URISyntaxException, AAIException, UnsupportedEncodingException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException, InstantiationException, NoSuchMethodException, MalformedURLException {
-
+ public void verifyModificationOfVertex() throws URISyntaxException, AAIException, UnsupportedEncodingException,
+ IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException,
+ InstantiationException, NoSuchMethodException, MalformedURLException {
+
final Loader loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getDepthVersion());
final Introspector obj = loader.introspectorFromName("vpn-binding");
obj.setValue("vpn-id", "modifyKey");
@@ -188,86 +210,101 @@ public class DataLinkTest extends DataLinkSetup {
obj.setValue("route-target-role", "modifyRoleKey2");
TransactionalGraphEngine spy = spy(dbEngine);
TransactionalGraphEngine.Admin adminSpy = spy(dbEngine.asAdmin());
-// Graph g = graph.newTransaction();
-// GraphTraversalSource traversal = g;
+ // Graph g = graph.newTransaction();
+ // GraphTraversalSource traversal = g;
Graph g = graph.newTransaction();
GraphTraversalSource traversal = g.traversal();
Iterator<Vertex> vertexItr = traversal.V();
- while( vertexItr != null && vertexItr.hasNext() ){
+ while (vertexItr != null && vertexItr.hasNext()) {
Vertex v = vertexItr.next();
- //System.out.println("\nnodeType="+v.<String>property("aai-node-type"));
- for(String key: v.keys()) {
- //System.out.println("label="+v.label()+";key= "+key+";value= "+v.value(key)+"/"+v.id());
+ // System.out.println("\nnodeType="+v.<String>property("aai-node-type"));
+ for (String key : v.keys()) {
+ // System.out.println("label="+v.label()+";key= "+key+";value= "+v.value(key)+"/"+v.id());
}
Direction d = null;
Iterator<Edge> edgeItr = v.edges(Direction.BOTH);
- while( edgeItr != null && edgeItr.hasNext() ){
+ while (edgeItr != null && edgeItr.hasNext()) {
Edge e = edgeItr.next();
- // System.out.println("outV="+e.outVertex().property(AAIProperties.NODE_TYPE)+"/"+e.outVertex().id()+";inV= "+e.inVertex().property(AAIProperties.NODE_TYPE)+"/"+e.inVertex().id());
+ // System.out.println("outV="+e.outVertex().property(AAIProperties.NODE_TYPE)+"/"+e.outVertex().id()+";inV=
+ // "+e.inVertex().property(AAIProperties.NODE_TYPE)+"/"+e.inVertex().id());
}
}
- // System.out.println("End method inventory:");
+ // System.out.println("End method inventory:");
when(spy.asAdmin()).thenReturn(adminSpy);
when(adminSpy.getTraversalSource()).thenReturn(traversal);
-// when(spy.tx()).thenReturn(graph);
+ // when(spy.tx()).thenReturn(graph);
when(spy.tx()).thenReturn(g);
when(self.<String>property(AAIProperties.AAI_URI)).thenReturn(prop);
when(prop.orElse(null)).thenReturn(obj.getURI());
- DBSerializer serializer = new DBSerializer(schemaVersions.getDefaultVersion(), spy, introspectorFactoryType, "AAI_TEST");
- SideEffectRunner runner = new SideEffectRunner
- .Builder(spy, serializer).addSideEffect(DataLinkWriter.class).build();
- //System.out.println("Traversal Source: "+traversal.toString());
+ DBSerializer serializer =
+ new DBSerializer(schemaVersions.getDefaultVersion(), spy, introspectorFactoryType, "AAI_TEST");
+ SideEffectRunner runner =
+ new SideEffectRunner.Builder(spy, serializer).addSideEffect(DataLinkWriter.class).build();
+ // System.out.println("Traversal Source: "+traversal.toString());
vertexItr = traversal.V();
- // System.out.println("Begin method inventory:");
- while( vertexItr != null && vertexItr.hasNext() ){
+ // System.out.println("Begin method inventory:");
+ while (vertexItr != null && vertexItr.hasNext()) {
Vertex v = vertexItr.next();
- //System.out.println("\nnodeType="+v.<String>property("aai-node-type"));
- for(String key: v.keys()) {
- // System.out.println("label="+v.label()+";key= "+key+";value= "+v.value(key)+"/"+v.id());
+ // System.out.println("\nnodeType="+v.<String>property("aai-node-type"));
+ for (String key : v.keys()) {
+ // System.out.println("label="+v.label()+";key= "+key+";value= "+v.value(key)+"/"+v.id());
}
Iterator<Edge> edgeItr = v.edges(Direction.BOTH);
- while( edgeItr != null && edgeItr.hasNext() ){
+ while (edgeItr != null && edgeItr.hasNext()) {
Edge e = edgeItr.next();
- //System.out.println("outV="+e.outVertex().property(AAIProperties.NODE_TYPE)+"/"+e.outVertex().id()+";inV= "+e.inVertex().property(AAIProperties.NODE_TYPE)+"/"+e.inVertex().id());
+ // System.out.println("outV="+e.outVertex().property(AAIProperties.NODE_TYPE)+"/"+e.outVertex().id()+";inV=
+ // "+e.inVertex().property(AAIProperties.NODE_TYPE)+"/"+e.inVertex().id());
}
}
- //System.out.println("End method inventory:");
+ // System.out.println("End method inventory:");
try {
- runner.execute(obj, self);
- } catch(Exception e) {
+ runner.execute(obj, self);
+ } catch (Exception e) {
}
-// runner.execute(obj, self);
- //System.out.println("=================\n");
+ // runner.execute(obj, self);
+ // System.out.println("=================\n");
vertexItr = traversal.V();
- while( vertexItr != null && vertexItr.hasNext() ){
+ while (vertexItr != null && vertexItr.hasNext()) {
Vertex v = vertexItr.next();
- //System.out.println("\nnodeType="+v.<String>property("aai-node-type"));
- for(String key: v.keys()) {
- // System.out.println("label="+v.label()+";key= "+key+";value= "+v.value(key)+"/"+v.id());
+ // System.out.println("\nnodeType="+v.<String>property("aai-node-type"));
+ for (String key : v.keys()) {
+ // System.out.println("label="+v.label()+";key= "+key+";value= "+v.value(key)+"/"+v.id());
}
Iterator<Edge> edgeItr = v.edges(Direction.BOTH);
- while( edgeItr != null && edgeItr.hasNext() ){
+ while (edgeItr != null && edgeItr.hasNext()) {
Edge e = edgeItr.next();
- // System.out.println("outV="+e.outVertex().property(AAIProperties.NODE_TYPE)+"/"+e.outVertex().id()+";inV= "+e.inVertex().property(AAIProperties.NODE_TYPE)+"/"+e.inVertex().id());
+ // System.out.println("outV="+e.outVertex().property(AAIProperties.NODE_TYPE)+"/"+e.outVertex().id()+";inV=
+ // "+e.inVertex().property(AAIProperties.NODE_TYPE)+"/"+e.inVertex().id());
}
}
- assertThat("new route-target vertex found with/or without link", traversal.V()
- .has(AAIProperties.NODE_TYPE, "route-target").has("global-route-target", "modifyTargetKey2").has("route-target-role", "modifyRoleKey2").hasNext(),is(true));
- assertThat("new route-target vertex found", traversal.V()
- .has(AAIProperties.NODE_TYPE, "route-target").has("global-route-target", "modifyTargetKey2").has("route-target-role", "modifyRoleKey2").has("linked", true).hasNext(),is(true));
- assertThat("previous link removed", traversal.V()
- .has(AAIProperties.NODE_TYPE, "route-target").has("global-route-target", "modifyTargetKey").has("route-target-role", "modifyRoleKey").has("linked").hasNext(),is(not(true)));
- assertThat("previous vertex still exists", traversal.V()
- .has(AAIProperties.NODE_TYPE, "route-target").has("global-route-target", "modifyTargetKey").has("route-target-role", "modifyRoleKey").hasNext(),is(true));
+ assertThat("new route-target vertex found with/or without link",
+ traversal.V().has(AAIProperties.NODE_TYPE, "route-target")
+ .has("global-route-target", "modifyTargetKey2").has("route-target-role", "modifyRoleKey2")
+ .hasNext(),
+ is(true));
+ assertThat("new route-target vertex found",
+ traversal.V().has(AAIProperties.NODE_TYPE, "route-target")
+ .has("global-route-target", "modifyTargetKey2").has("route-target-role", "modifyRoleKey2")
+ .has("linked", true).hasNext(),
+ is(true));
+ assertThat("previous link removed",
+ traversal.V().has(AAIProperties.NODE_TYPE, "route-target").has("global-route-target", "modifyTargetKey")
+ .has("route-target-role", "modifyRoleKey").has("linked").hasNext(),
+ is(not(true)));
+ assertThat("previous vertex still exists", traversal.V().has(AAIProperties.NODE_TYPE, "route-target")
+ .has("global-route-target", "modifyTargetKey").has("route-target-role", "modifyRoleKey").hasNext(),
+ is(true));
g.tx().rollback();
-
+
}
-
+
@Test
- public void verifyDeleteOfVertex() throws URISyntaxException, AAIException, UnsupportedEncodingException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException, InstantiationException, NoSuchMethodException, MalformedURLException {
-
+ public void verifyDeleteOfVertex() throws URISyntaxException, AAIException, UnsupportedEncodingException,
+ IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException,
+ InstantiationException, NoSuchMethodException, MalformedURLException {
+
final Loader loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getDepthVersion());
final Introspector obj = loader.introspectorFromName("vpn-binding");
obj.setValue("vpn-id", "deleteKey");
@@ -281,27 +318,26 @@ public class DataLinkTest extends DataLinkSetup {
when(spy.tx()).thenReturn(g);
when(self.<String>property(AAIProperties.AAI_URI)).thenReturn(prop);
when(prop.orElse(null)).thenReturn(obj.getURI());
- DBSerializer serializer = new DBSerializer(schemaVersions.getDefaultVersion(), spy, introspectorFactoryType, "AAI_TEST");
- SideEffectRunner runner = new SideEffectRunner
- .Builder(spy, serializer).addSideEffect(DataLinkWriter.class).build();
-
+ DBSerializer serializer =
+ new DBSerializer(schemaVersions.getDefaultVersion(), spy, introspectorFactoryType, "AAI_TEST");
+ SideEffectRunner runner =
+ new SideEffectRunner.Builder(spy, serializer).addSideEffect(DataLinkWriter.class).build();
+
runner.execute(obj, self);
- assertEquals("route-target vertex not found", false, traversal.V()
- .has(AAIProperties.NODE_TYPE, "route-target")
- .has("global-route-target", "deleteTargetKey")
- .has("route-target-role", "deleteRoleKey")
- .has("linked", true)
- .hasNext()
- );
+ assertEquals("route-target vertex not found", false,
+ traversal.V().has(AAIProperties.NODE_TYPE, "route-target").has("global-route-target", "deleteTargetKey")
+ .has("route-target-role", "deleteRoleKey").has("linked", true).hasNext());
g.tx().rollback();
-
+
}
-
+
@Test
- public void verifyPropertyPopulation() throws URISyntaxException, AAIException, UnsupportedEncodingException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException, InstantiationException, NoSuchMethodException, MalformedURLException {
-
+ public void verifyPropertyPopulation() throws URISyntaxException, AAIException, UnsupportedEncodingException,
+ IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException,
+ InstantiationException, NoSuchMethodException, MalformedURLException {
+
final Loader loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getDepthVersion());
final Introspector obj = loader.introspectorFromName("vpn-binding");
obj.setValue("vpn-id", "getKey");
@@ -314,19 +350,24 @@ public class DataLinkTest extends DataLinkSetup {
when(spy.tx()).thenReturn(g);
when(self.<String>property(AAIProperties.AAI_URI)).thenReturn(prop);
when(prop.orElse(null)).thenReturn(obj.getURI());
- DBSerializer serializer = new DBSerializer(schemaVersions.getDefaultVersion(), spy, introspectorFactoryType, "AAI_TEST");
- SideEffectRunner runner = new SideEffectRunner
- .Builder(spy, serializer).addSideEffect(DataLinkReader.class).build();
-
+ DBSerializer serializer =
+ new DBSerializer(schemaVersions.getDefaultVersion(), spy, introspectorFactoryType, "AAI_TEST");
+ SideEffectRunner runner =
+ new SideEffectRunner.Builder(spy, serializer).addSideEffect(DataLinkReader.class).build();
+
runner.execute(obj, self);
- assertEquals("both properties have been populated in target object", true, obj.getValue("global-route-target").equals("getTargetKey") && obj.getValue("route-target-role").equals("getRoleKey"));
+ assertEquals("both properties have been populated in target object", true,
+ obj.getValue("global-route-target").equals("getTargetKey")
+ && obj.getValue("route-target-role").equals("getRoleKey"));
g.tx().rollback();
-
+
}
-
+
@Test
- public void verifyPropertyPopulationWithV10OnlyPut() throws URISyntaxException, AAIException, UnsupportedEncodingException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException, InstantiationException, NoSuchMethodException, MalformedURLException {
+ public void verifyPropertyPopulationWithV10OnlyPut() throws URISyntaxException, AAIException,
+ UnsupportedEncodingException, IllegalAccessException, IllegalArgumentException, InvocationTargetException,
+ SecurityException, InstantiationException, NoSuchMethodException, MalformedURLException {
final Introspector obj = loader.introspectorFromName("vpn-binding");
obj.setValue("vpn-id", "getKeyNoLink");
final Introspector routeTargets = loader.introspectorFromName("route-targets");
@@ -351,16 +392,19 @@ public class DataLinkTest extends DataLinkSetup {
when(parser.isDependent()).thenReturn(false);
when(self.<String>property(AAIProperties.AAI_URI)).thenReturn(prop);
when(prop.orElse(null)).thenReturn(obj.getURI());
- DBSerializer serializer = new DBSerializer(schemaVersions.getDefaultVersion(), spy, introspectorFactoryType, "AAI_TEST");
+ DBSerializer serializer =
+ new DBSerializer(schemaVersions.getDefaultVersion(), spy, introspectorFactoryType, "AAI_TEST");
Vertex v = serializer.createNewVertex(obj);
serializer.serializeToDb(obj, v, parser, obj.getURI(), "testing");
Vertex routeTargetOneV = traversal.V().has("global-route-target", "getTargetKeyNoLink").next();
Vertex routeTargetTwoV = traversal.V().has("global-route-target", "getTargetKeyNoLink2").next();
- assertEquals("first route target put has linked", true, routeTargetOneV.property(AAIProperties.LINKED).orElse(false));
- assertEquals("second route target put does not have linked", false, routeTargetTwoV.property(AAIProperties.LINKED).orElse(false));
+ assertEquals("first route target put has linked", true,
+ routeTargetOneV.property(AAIProperties.LINKED).orElse(false));
+ assertEquals("second route target put does not have linked", false,
+ routeTargetTwoV.property(AAIProperties.LINKED).orElse(false));
g.tx().rollback();
-
+
}
}
diff --git a/aai-core/src/test/java/org/onap/aai/introspection/sideeffect/PrivateEdgeTest.java b/aai-core/src/test/java/org/onap/aai/introspection/sideeffect/PrivateEdgeTest.java
index 5cd1fb53..1bae4065 100644
--- a/aai-core/src/test/java/org/onap/aai/introspection/sideeffect/PrivateEdgeTest.java
+++ b/aai-core/src/test/java/org/onap/aai/introspection/sideeffect/PrivateEdgeTest.java
@@ -17,9 +17,22 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.introspection.sideeffect;
-import org.springframework.test.annotation.DirtiesContext;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.empty;
+import static org.hamcrest.Matchers.not;
+import static org.hamcrest.core.Is.is;
+import static org.hamcrest.core.StringContains.containsString;
+import static org.junit.Assert.*;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.when;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Graph;
@@ -40,110 +53,76 @@ import org.onap.aai.serialization.db.DBSerializer;
import org.onap.aai.serialization.engines.JanusGraphDBEngine;
import org.onap.aai.serialization.engines.QueryStyle;
import org.onap.aai.serialization.engines.TransactionalGraphEngine;
-
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.List;
-
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.empty;
-import static org.hamcrest.Matchers.not;
-import static org.hamcrest.core.Is.is;
-import static org.hamcrest.core.StringContains.containsString;
-import static org.junit.Assert.*;
-import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.when;
+import org.springframework.test.annotation.DirtiesContext;
@RunWith(value = Parameterized.class)
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
-public class PrivateEdgeTest extends AAISetup{
+public class PrivateEdgeTest extends AAISetup {
private static JanusGraph graph;
private final static ModelType introspectorFactoryType = ModelType.MOXY;
private final static DBConnectionType type = DBConnectionType.REALTIME;
private Loader loader;
private static TransactionalGraphEngine dbEngine;
-
-
-
+
@Rule
public ExpectedException thrown = ExpectedException.none();
-
@Parameterized.Parameter(value = 0)
public QueryStyle queryStyle;
@Parameterized.Parameters(name = "QueryStyle.{0}")
public static Collection<Object[]> data() {
- return Arrays.asList(new Object[][]{
- {QueryStyle.TRAVERSAL},
- {QueryStyle.TRAVERSAL_URI}
- });
+ return Arrays.asList(new Object[][] {{QueryStyle.TRAVERSAL}, {QueryStyle.TRAVERSAL_URI}});
}
-
+
@BeforeClass
public static void setup() throws Exception {
- graph = JanusGraphFactory.build().set("storage.backend","inmemory").open();
+ graph = JanusGraphFactory.build().set("storage.backend", "inmemory").open();
System.setProperty("AJSC_HOME", ".");
System.setProperty("BUNDLECONFIG_DIR", "src/test/resources/bundleconfig-local");
-
-
graph.traversal()
- .addV("aai-node-type", "model",
- "model-invariant-id", "key1",
- AAIProperties.AAI_URI, "/service-design-and-creation/models/model/key1").as("v1")
- .addV("aai-node-type", "model-ver",
- "model-ver", "myValue",
- "model-version-id", "key2",
- "model-version", "testValue",
- AAIProperties.AAI_URI, "/service-design-and-creation/models/model/key1/model-vers/model-ver/key2")
- .addOutE("org.onap.relationships.inventory.BelongsTo", "v1",
- EdgeProperty.CONTAINS.toString(), true
- )
- .addV("aai-node-type", "model",
- "model-invariant-id", "key100",
- AAIProperties.AAI_URI, "/service-design-and-creation/models/model/key100").as("v5")
- .addV("aai-node-type", "model-ver",
- "model-ver", "myValue",
- "model-version-id", "key200",
- "model-version", "testValue",
- AAIProperties.AAI_URI, "/service-design-and-creation/models/model/key100/model-vers/model-ver/key200")
- .addOutE("org.onap.relationships.inventory.BelongsTo", "v5",
- EdgeProperty.CONTAINS.toString(), true
- )
- .addV("aai-node-type", "model",
- "model-invariant-id", "key3",
- AAIProperties.AAI_URI, "/service-design-and-creation/models/model/key3").as("v2")
- .addV("aai-node-type", "model-ver",
- "model-ver", "myValue",
- "model-version-id", "key4",
- AAIProperties.AAI_URI, "/service-design-and-creation/models/model/key3/model-vers/model-ver/key4")
- .addOutE("org.onap.relationships.inventory.BelongsTo", "v2",
- EdgeProperty.CONTAINS.toString(), true
- )
- .next();
+ .addV("aai-node-type", "model", "model-invariant-id", "key1", AAIProperties.AAI_URI,
+ "/service-design-and-creation/models/model/key1")
+ .as("v1")
+ .addV("aai-node-type", "model-ver", "model-ver", "myValue", "model-version-id", "key2", "model-version",
+ "testValue", AAIProperties.AAI_URI,
+ "/service-design-and-creation/models/model/key1/model-vers/model-ver/key2")
+ .addOutE("org.onap.relationships.inventory.BelongsTo", "v1", EdgeProperty.CONTAINS.toString(), true)
+ .addV("aai-node-type", "model", "model-invariant-id", "key100", AAIProperties.AAI_URI,
+ "/service-design-and-creation/models/model/key100")
+ .as("v5")
+ .addV("aai-node-type", "model-ver", "model-ver", "myValue", "model-version-id", "key200",
+ "model-version", "testValue", AAIProperties.AAI_URI,
+ "/service-design-and-creation/models/model/key100/model-vers/model-ver/key200")
+ .addOutE("org.onap.relationships.inventory.BelongsTo", "v5", EdgeProperty.CONTAINS.toString(), true)
+ .addV("aai-node-type", "model", "model-invariant-id", "key3", AAIProperties.AAI_URI,
+ "/service-design-and-creation/models/model/key3")
+ .as("v2")
+ .addV("aai-node-type", "model-ver", "model-ver", "myValue", "model-version-id", "key4",
+ AAIProperties.AAI_URI,
+ "/service-design-and-creation/models/model/key3/model-vers/model-ver/key4")
+ .addOutE("org.onap.relationships.inventory.BelongsTo", "v2", EdgeProperty.CONTAINS.toString(), true)
+ .next();
graph.tx().commit();
}
-
+
@AfterClass
public static void tearDown() {
graph.tx().rollback();
graph.close();
}
-
+
@Before
public void initMock() {
loader = loaderFactory.createLoaderForVersion(introspectorFactoryType, schemaVersions.getDefaultVersion());
MockitoAnnotations.initMocks(this);
- dbEngine = new JanusGraphDBEngine(
- queryStyle,
- type,
- loader);
+ dbEngine = new JanusGraphDBEngine(queryStyle, type, loader);
}
-
+
@Test
public void testWhenPrivateEdgeThrowsExceptionWhenHavingOnlyOnePartOfKey() throws Exception {
@@ -158,15 +137,12 @@ public class PrivateEdgeTest extends AAISetup{
when(spy.asAdmin()).thenReturn(adminSpy);
when(adminSpy.getTraversalSource()).thenReturn(traversal);
- Vertex selfV = traversal.addV(
- "aai-node-type", "generic-vnf",
- "vnf-id", "myId",
- "aai-uri",obj.getURI(),
- "model-invariant-id", "key1"
- ).next();
+ Vertex selfV = traversal.addV("aai-node-type", "generic-vnf", "vnf-id", "myId", "aai-uri", obj.getURI(),
+ "model-invariant-id", "key1").next();
thrown.expectMessage(containsString("Cannot complete privateEdge uri"));
- DBSerializer serializer = new DBSerializer(schemaVersions.getDefaultVersion(), spy, introspectorFactoryType, "AAI_TEST");
+ DBSerializer serializer =
+ new DBSerializer(schemaVersions.getDefaultVersion(), spy, introspectorFactoryType, "AAI_TEST");
PrivateEdge privateEdge = new PrivateEdge(obj, selfV, spy, serializer);
privateEdge.execute();
diff --git a/aai-core/src/test/java/org/onap/aai/introspection/tools/CreateUUIDTest.java b/aai-core/src/test/java/org/onap/aai/introspection/tools/CreateUUIDTest.java
index e44fdd52..6d8508ce 100644
--- a/aai-core/src/test/java/org/onap/aai/introspection/tools/CreateUUIDTest.java
+++ b/aai-core/src/test/java/org/onap/aai/introspection/tools/CreateUUIDTest.java
@@ -17,8 +17,12 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.introspection.tools;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
import org.junit.Before;
import org.junit.Test;
import org.onap.aai.AAISetup;
@@ -26,9 +30,6 @@ import org.onap.aai.introspection.*;
import org.onap.aai.introspection.exceptions.AAIUnknownObjectException;
import org.springframework.test.annotation.DirtiesContext;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
public class CreateUUIDTest extends AAISetup {
@@ -38,7 +39,7 @@ public class CreateUUIDTest extends AAISetup {
private Issue issue;
@Before
- public void setup(){
+ public void setup() {
createUUID = new CreateUUID();
loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getDefaultVersion());
}
diff --git a/aai-core/src/test/java/org/onap/aai/introspection/tools/DefaultFieldsTest.java b/aai-core/src/test/java/org/onap/aai/introspection/tools/DefaultFieldsTest.java
index 5fd185d5..664a69c5 100644
--- a/aai-core/src/test/java/org/onap/aai/introspection/tools/DefaultFieldsTest.java
+++ b/aai-core/src/test/java/org/onap/aai/introspection/tools/DefaultFieldsTest.java
@@ -17,8 +17,14 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.introspection.tools;
+import static junit.framework.TestCase.assertNotNull;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
import org.junit.Before;
import org.junit.Test;
import org.onap.aai.AAISetup;
@@ -26,11 +32,6 @@ import org.onap.aai.introspection.*;
import org.onap.aai.introspection.exceptions.AAIUnknownObjectException;
import org.springframework.test.annotation.DirtiesContext;
-import static junit.framework.TestCase.assertNotNull;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
public class DefaultFieldsTest extends AAISetup {
@@ -40,8 +41,8 @@ public class DefaultFieldsTest extends AAISetup {
@Before
public void setup() {
- loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getDefaultVersion());
- issue = new Issue();
+ loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getDefaultVersion());
+ issue = new Issue();
defaultFields = new DefaultFields();
}
diff --git a/aai-core/src/test/java/org/onap/aai/introspection/tools/InjectKeysFromURITest.java b/aai-core/src/test/java/org/onap/aai/introspection/tools/InjectKeysFromURITest.java
index 713a8ae0..cd5bdb93 100644
--- a/aai-core/src/test/java/org/onap/aai/introspection/tools/InjectKeysFromURITest.java
+++ b/aai-core/src/test/java/org/onap/aai/introspection/tools/InjectKeysFromURITest.java
@@ -17,8 +17,17 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.introspection.tools;
+import static junit.framework.TestCase.assertNotNull;
+import static org.eclipse.persistence.jpa.jpql.Assert.fail;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import java.net.URI;
+
import org.junit.Before;
import org.junit.Test;
import org.onap.aai.AAISetup;
@@ -26,14 +35,6 @@ import org.onap.aai.introspection.*;
import org.onap.aai.introspection.exceptions.AAIUnknownObjectException;
import org.springframework.test.annotation.DirtiesContext;
-import java.net.URI;
-
-import static junit.framework.TestCase.assertNotNull;
-import static org.eclipse.persistence.jpa.jpql.Assert.fail;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
public class InjectKeysFromURITest extends AAISetup {
@@ -43,19 +44,20 @@ public class InjectKeysFromURITest extends AAISetup {
@Before
public void setup() {
- loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getDefaultVersion());
- issue = new Issue();
+ loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getDefaultVersion());
+ issue = new Issue();
}
+
@Test
public void testInjectKeysFromURIOfPserverIsNotResolved() throws AAIUnknownObjectException {
try {
ik = new InjectKeysFromURI(loader, new URI("/aai/v12/cloud-infrastructure/complexes"));
- }catch(Exception e) {
+ } catch (Exception e) {
fail("InjectKeys instantiation threw an exception");
}
Introspector pserver = loader.introspectorFromName("pserver");
- pserver.setValue("in-maint",false);
+ pserver.setValue("in-maint", false);
pserver.setValue("hostname", "pserver2");
assertNotNull("Unable to load the template introspector", pserver);
@@ -68,13 +70,14 @@ public class InjectKeysFromURITest extends AAISetup {
assertFalse("Unable to resolve the pserver in-maint issue", issueResolved);
assertEquals("Introspector didn't successfully modify the pserver in-maint", false,
- pserver.getValue("in-maint"));
+ pserver.getValue("in-maint"));
}
+
@Test
public void testInjectKeysFromURIOfPserverSuccessfullyResolved() throws AAIUnknownObjectException {
try {
ik = new InjectKeysFromURI(loader, new URI("/aai/v12/cloud-infrastructure/pservers/pserver/pserver1"));
- }catch(Exception e) {
+ } catch (Exception e) {
fail("InjectKeys instantiation threw an exception");
}
diff --git a/aai-core/src/test/java/org/onap/aai/introspection/tools/IntrospectorValidatorTest.java b/aai-core/src/test/java/org/onap/aai/introspection/tools/IntrospectorValidatorTest.java
index 68a03b3b..41c6353b 100644
--- a/aai-core/src/test/java/org/onap/aai/introspection/tools/IntrospectorValidatorTest.java
+++ b/aai-core/src/test/java/org/onap/aai/introspection/tools/IntrospectorValidatorTest.java
@@ -17,8 +17,15 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.introspection.tools;
+import static junit.framework.TestCase.assertNotNull;
+import static org.eclipse.persistence.jpa.jpql.Assert.fail;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
import org.junit.Before;
import org.junit.Test;
import org.onap.aai.AAISetup;
@@ -26,12 +33,6 @@ import org.onap.aai.introspection.*;
import org.onap.aai.introspection.exceptions.AAIUnknownObjectException;
import org.springframework.test.annotation.DirtiesContext;
-import static junit.framework.TestCase.assertNotNull;
-import static org.eclipse.persistence.jpa.jpql.Assert.fail;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
public class IntrospectorValidatorTest extends AAISetup {
@@ -47,7 +48,7 @@ public class IntrospectorValidatorTest extends AAISetup {
issue = new Issue();
try {
introspector = loader.introspectorFromName("pserver");
- }catch(Exception e){
+ } catch (Exception e) {
fail("Introspector instantiation call threw an exception " + e);
}
b = new IntrospectorValidator.Builder();
@@ -59,11 +60,11 @@ public class IntrospectorValidatorTest extends AAISetup {
return true;
}
});
- //this method does nothing
- iv.processPrimitiveList("TEST",introspector);
+ // this method does nothing
+ iv.processPrimitiveList("TEST", introspector);
}
- public void setupIssue(String message, IssueType type, String propName, Introspector introspector){
+ public void setupIssue(String message, IssueType type, String propName, Introspector introspector) {
issue.setDetail(message);
issue.setType(type);
issue.setPropName(propName);
@@ -72,56 +73,57 @@ public class IntrospectorValidatorTest extends AAISetup {
@Test
public void testIntrospectorValidatorMaxDepth() throws AAIUnknownObjectException {
- setupIssue("Some message", IssueType.MISSING_REQUIRED_PROP, "hostname", introspector );
+ setupIssue("Some message", IssueType.MISSING_REQUIRED_PROP, "hostname", introspector);
b.restrictDepth(4);
assertEquals("Maximum Depth should be 4", 4, b.getMaximumDepth());
}
@Test
public void testIntrospectorValidatorValidationRequired() throws AAIUnknownObjectException {
- setupIssue("Some message", IssueType.MISSING_REQUIRED_PROP, "hostname", introspector );
+ setupIssue("Some message", IssueType.MISSING_REQUIRED_PROP, "hostname", introspector);
b.validateRequired(true);
assertTrue("Validation should be required", b.getValidateRequired());
}
@Test
- public void testIntrospectorValidatorValidatedFalse() throws AAIUnknownObjectException{
- setupIssue("Some message", IssueType.MISSING_REQUIRED_PROP, "hostname", introspector );
+ public void testIntrospectorValidatorValidatedFalse() throws AAIUnknownObjectException {
+ setupIssue("Some message", IssueType.MISSING_REQUIRED_PROP, "hostname", introspector);
try {
assertFalse("Not currently validated", iv.validate(introspector));
- }catch (Exception e){
+ } catch (Exception e) {
fail("Introspector validate call threw an exception " + e);
}
}
@Test
- public void testIntrospectorValidatorResolveIssues() throws AAIUnknownObjectException{
- setupIssue("Some message", IssueType.MISSING_REQUIRED_PROP, "hostname", introspector );
+ public void testIntrospectorValidatorResolveIssues() throws AAIUnknownObjectException {
+ setupIssue("Some message", IssueType.MISSING_REQUIRED_PROP, "hostname", introspector);
assertTrue("Introspector call to resolve issues should return true", iv.resolveIssues());
}
@Test
- public void testIntrospectorValidatorGetIssues() throws AAIUnknownObjectException{
- setupIssue("Some message", IssueType.MISSING_REQUIRED_PROP, "hostname", introspector );
+ public void testIntrospectorValidatorGetIssues() throws AAIUnknownObjectException {
+ setupIssue("Some message", IssueType.MISSING_REQUIRED_PROP, "hostname", introspector);
iv.getIssues();
}
@Test
- public void testIntrospectorValidatorProcessComplexObject() throws AAIUnknownObjectException{
- setupIssue("Some message", IssueType.MISSING_REQUIRED_PROP, "hostname", introspector );
+ public void testIntrospectorValidatorProcessComplexObject() throws AAIUnknownObjectException {
+ setupIssue("Some message", IssueType.MISSING_REQUIRED_PROP, "hostname", introspector);
iv.processComplexObj(introspector);
}
@Test
- public void testIntrospectorValidatorCreateComplexListSize() throws AAIUnknownObjectException{
- setupIssue("Some message", IssueType.MISSING_REQUIRED_PROP, "hostname", introspector );
- assertEquals("create complex list size should return 0", 0, iv.createComplexListSize(introspector, introspector));
+ public void testIntrospectorValidatorCreateComplexListSize() throws AAIUnknownObjectException {
+ setupIssue("Some message", IssueType.MISSING_REQUIRED_PROP, "hostname", introspector);
+ assertEquals("create complex list size should return 0", 0,
+ iv.createComplexListSize(introspector, introspector));
}
@Test
- public void testIntrospectorValidatorGetResolvers() throws AAIUnknownObjectException{
- setupIssue("Some message", IssueType.MISSING_REQUIRED_PROP, "hostname", introspector );
- assertNotNull("Get resolvers should not be null", b.getResolvers());
+ public void testIntrospectorValidatorGetResolvers() throws AAIUnknownObjectException {
+ setupIssue("Some message", IssueType.MISSING_REQUIRED_PROP, "hostname", introspector);
+ assertNotNull("Get resolvers should not be null", b.getResolvers());
}
}
diff --git a/aai-core/src/test/java/org/onap/aai/introspection/tools/RemoveNonVisiblePropertyTest.java b/aai-core/src/test/java/org/onap/aai/introspection/tools/RemoveNonVisiblePropertyTest.java
index cf1b7782..a3380ee2 100644
--- a/aai-core/src/test/java/org/onap/aai/introspection/tools/RemoveNonVisiblePropertyTest.java
+++ b/aai-core/src/test/java/org/onap/aai/introspection/tools/RemoveNonVisiblePropertyTest.java
@@ -17,8 +17,13 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.introspection.tools;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
import org.junit.Before;
import org.junit.Test;
import org.onap.aai.AAISetup;
@@ -26,10 +31,6 @@ import org.onap.aai.introspection.*;
import org.onap.aai.introspection.exceptions.AAIUnknownObjectException;
import org.springframework.test.annotation.DirtiesContext;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.assertNull;
-
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
public class RemoveNonVisiblePropertyTest extends AAISetup {
@@ -38,7 +39,7 @@ public class RemoveNonVisiblePropertyTest extends AAISetup {
private RemoveNonVisibleProperty rn;
@Before
- public void setup(){
+ public void setup() {
rn = new RemoveNonVisibleProperty();
loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getDefaultVersion());
}
@@ -66,5 +67,4 @@ public class RemoveNonVisiblePropertyTest extends AAISetup {
assertFalse("Nonvisible property not present so should not have been removed", rn.resolveIssue(issue));
}
-
}
diff --git a/aai-core/src/test/java/org/onap/aai/introspection/validation/IntrospectorValidationTest.java b/aai-core/src/test/java/org/onap/aai/introspection/validation/IntrospectorValidationTest.java
index 0902aec8..7bb38790 100644
--- a/aai-core/src/test/java/org/onap/aai/introspection/validation/IntrospectorValidationTest.java
+++ b/aai-core/src/test/java/org/onap/aai/introspection/validation/IntrospectorValidationTest.java
@@ -17,15 +17,19 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.introspection.validation;
+import static org.junit.Assert.assertEquals;
+
+import java.util.List;
+
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.onap.aai.AAISetup;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.introspection.*;
-
import org.onap.aai.introspection.tools.IntrospectorValidator;
import org.onap.aai.introspection.tools.Issue;
import org.onap.aai.introspection.tools.IssueType;
@@ -33,10 +37,6 @@ import org.onap.aai.serialization.queryformats.QueryFormatTestHelper;
import org.onap.aai.util.AAIConstants;
import org.springframework.beans.factory.annotation.Autowired;
-import java.util.List;
-
-import static org.junit.Assert.assertEquals;
-
public class IntrospectorValidationTest extends AAISetup {
private final static ModelType introspectorFactoryType = ModelType.MOXY;
@@ -50,11 +50,9 @@ public class IntrospectorValidationTest extends AAISetup {
System.setProperty("AJSC_HOME", ".");
System.setProperty("BUNDLECONFIG_DIR", "bundleconfig-local");
loader = loaderFactory.createLoaderForVersion(introspectorFactoryType, schemaVersions.getRelatedLinkVersion());
- validator = new IntrospectorValidator.Builder()
- .validateRequired(false)
- .restrictDepth(10000)
- .build();
+ validator = new IntrospectorValidator.Builder().validateRequired(false).restrictDepth(10000).build();
}
+
@Ignore
@Test
public void verifySuccessWhenEmpty() throws AAIException {
@@ -77,6 +75,7 @@ public class IntrospectorValidationTest extends AAISetup {
Issue issue = issues.get(0);
assertEquals("found expected issue", IssueType.DEPENDENT_PROP_NOT_FOUND, issue.getType());
}
+
@Ignore
@Test
public void verifyRequiresSuccess() throws AAIException {
diff --git a/aai-core/src/test/java/org/onap/aai/logging/CustomLogPatternLayoutTest.java b/aai-core/src/test/java/org/onap/aai/logging/CustomLogPatternLayoutTest.java
index 198bb064..dce34b53 100644
--- a/aai-core/src/test/java/org/onap/aai/logging/CustomLogPatternLayoutTest.java
+++ b/aai-core/src/test/java/org/onap/aai/logging/CustomLogPatternLayoutTest.java
@@ -17,31 +17,32 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.logging;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
import org.junit.Test;
import org.onap.aai.logging.CNName;
import org.onap.aai.logging.CustomLogPatternLayout;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
public class CustomLogPatternLayoutTest {
-
+
/**
* Test null when defaultConverterMap doesn't have corresponding entry.
*/
@Test
- public void testNull(){
+ public void testNull() {
String s = CustomLogPatternLayout.defaultConverterMap.get("z");
assertFalse("Entry not found for key 'z'", CNName.class.getName().equals(s));
}
-
+
/**
* Test defaultConverterMap when valid entry exists.
*/
@Test
- public void testEntryFor_Z(){
+ public void testEntryFor_Z() {
CustomLogPatternLayout layout = new CustomLogPatternLayout();
String s = CustomLogPatternLayout.defaultConverterMap.get("z");
assertTrue("Entry not found for key 'z'", CNName.class.getName().equals(s));
diff --git a/aai-core/src/test/java/org/onap/aai/logging/DME2RestFlagTest.java b/aai-core/src/test/java/org/onap/aai/logging/DME2RestFlagTest.java
index 09e6ed1e..bc7f9499 100644
--- a/aai-core/src/test/java/org/onap/aai/logging/DME2RestFlagTest.java
+++ b/aai-core/src/test/java/org/onap/aai/logging/DME2RestFlagTest.java
@@ -17,12 +17,15 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.logging;
+
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
+
import ch.qos.logback.access.spi.IAccessEvent;
-import org.junit.*;
+import org.junit.*;
public class DME2RestFlagTest {
@@ -31,51 +34,49 @@ public class DME2RestFlagTest {
String[] temp = new String[4];
-
@Before
public void setUp() throws Exception {
mockAccEvent = mock(IAccessEvent.class);
- _DME2RestFlag= spy(DME2RestFlag.class);
+ _DME2RestFlag = spy(DME2RestFlag.class);
}
- private DME2RestFlag getTestObj(final boolean instanceStarted){
- return new DME2RestFlag(){
+
+ private DME2RestFlag getTestObj(final boolean instanceStarted) {
+ return new DME2RestFlag() {
@Override
- public
- boolean isStarted(){
+ public boolean isStarted() {
return instanceStarted;
}
};
}
@Test
- public void convertTestAllValid(){
- temp[0]= "temp1";
+ public void convertTestAllValid() {
+ temp[0] = "temp1";
temp[1] = "-";
when(mockAccEvent.getRequestParameter("envContext")).thenReturn(temp);
when(mockAccEvent.getRequestParameter("routeOffer")).thenReturn(temp);
when(mockAccEvent.getRequestParameter("version")).thenReturn(temp);
_DME2RestFlag = getTestObj(true);
- assertEquals(_DME2RestFlag.convert(mockAccEvent),"DME2");
+ assertEquals(_DME2RestFlag.convert(mockAccEvent), "DME2");
}
@Test
- public void convertMissingRouteTest(){
- temp[0]= "";
+ public void convertMissingRouteTest() {
+ temp[0] = "";
temp[1] = "-";
when(mockAccEvent.getRequestParameter("envContext")).thenReturn(temp);
when(mockAccEvent.getRequestParameter("routeOffer")).thenReturn(temp);
when(mockAccEvent.getRequestParameter("version")).thenReturn(temp);
_DME2RestFlag = getTestObj(true);
- assertEquals(_DME2RestFlag.convert(mockAccEvent),"REST");
+ assertEquals(_DME2RestFlag.convert(mockAccEvent), "REST");
}
@Test
- public void convertIsStartedFalseTest(){
+ public void convertIsStartedFalseTest() {
_DME2RestFlag = getTestObj(false);
- assertEquals(_DME2RestFlag.convert(mockAccEvent),"INACTIVE_HEADER_CONV");
+ assertEquals(_DME2RestFlag.convert(mockAccEvent), "INACTIVE_HEADER_CONV");
}
-
}
diff --git a/aai-core/src/test/java/org/onap/aai/logging/EcompErrorCategoryTest.java b/aai-core/src/test/java/org/onap/aai/logging/EcompErrorCategoryTest.java
index b29cf51f..65c78121 100644
--- a/aai-core/src/test/java/org/onap/aai/logging/EcompErrorCategoryTest.java
+++ b/aai-core/src/test/java/org/onap/aai/logging/EcompErrorCategoryTest.java
@@ -17,14 +17,15 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.logging;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import ch.qos.logback.classic.Level;
-
import ch.qos.logback.classic.spi.ILoggingEvent;
+
import org.junit.*;
public class EcompErrorCategoryTest {
@@ -36,11 +37,12 @@ public class EcompErrorCategoryTest {
public void setUp() throws Exception {
mockEvent = mock(ILoggingEvent.class);
- _ecompErrorCategory= spy(EcompErrorCategory.class);
+ _ecompErrorCategory = spy(EcompErrorCategory.class);
}
+
@Test
- public void warn(){
+ public void warn() {
String defaultCategory = "WARN";
assertEquals(_ecompErrorCategory.convert(mockEvent), defaultCategory);
}
diff --git a/aai-core/src/test/java/org/onap/aai/logging/EcompResponseCodeTest.java b/aai-core/src/test/java/org/onap/aai/logging/EcompResponseCodeTest.java
index 10edb456..8319f9a3 100644
--- a/aai-core/src/test/java/org/onap/aai/logging/EcompResponseCodeTest.java
+++ b/aai-core/src/test/java/org/onap/aai/logging/EcompResponseCodeTest.java
@@ -17,14 +17,15 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.logging;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import ch.qos.logback.classic.Level;
-
import ch.qos.logback.classic.spi.ILoggingEvent;
+
import org.junit.*;
public class EcompResponseCodeTest {
@@ -36,11 +37,12 @@ public class EcompResponseCodeTest {
public void setUp() throws Exception {
mockEvent = mock(ILoggingEvent.class);
- _ecompResponseCode= spy(EcompResponseCode.class);
+ _ecompResponseCode = spy(EcompResponseCode.class);
}
+
@Test
- public void getDefaultCode(){
+ public void getDefaultCode() {
assertEquals(_ecompResponseCode.convert(mockEvent), LoggingContext.UNKNOWN_ERROR);
}
diff --git a/aai-core/src/test/java/org/onap/aai/logging/EcompResponseDescriptionTest.java b/aai-core/src/test/java/org/onap/aai/logging/EcompResponseDescriptionTest.java
index fbdc998e..deec8828 100644
--- a/aai-core/src/test/java/org/onap/aai/logging/EcompResponseDescriptionTest.java
+++ b/aai-core/src/test/java/org/onap/aai/logging/EcompResponseDescriptionTest.java
@@ -17,31 +17,33 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.logging;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import ch.qos.logback.classic.Level;
-
import ch.qos.logback.classic.spi.ILoggingEvent;
+
import org.junit.*;
import org.onap.aai.logging.LoggingContext.LoggingField;
public class EcompResponseDescriptionTest {
- EcompResponseDescription _ecompResponseDescription;
+ EcompResponseDescription _ecompResponseDescription;
ILoggingEvent mockEvent;
@Before
public void setUp() throws Exception {
mockEvent = mock(ILoggingEvent.class);
- _ecompResponseDescription= spy(EcompResponseDescription.class);
+ _ecompResponseDescription = spy(EcompResponseDescription.class);
}
+
@Test
- public void getDefaultDesc(){
+ public void getDefaultDesc() {
assertEquals(_ecompResponseDescription.convert(mockEvent), _ecompResponseDescription.DefaultDescription);
}
diff --git a/aai-core/src/test/java/org/onap/aai/logging/EelfClassOfCallerTest.java b/aai-core/src/test/java/org/onap/aai/logging/EelfClassOfCallerTest.java
index be04f276..bc77ae81 100644
--- a/aai-core/src/test/java/org/onap/aai/logging/EelfClassOfCallerTest.java
+++ b/aai-core/src/test/java/org/onap/aai/logging/EelfClassOfCallerTest.java
@@ -17,11 +17,14 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.logging;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
+
import ch.qos.logback.classic.spi.ILoggingEvent;
+
import org.junit.*;
public class EelfClassOfCallerTest {
@@ -32,37 +35,36 @@ public class EelfClassOfCallerTest {
StackTraceElement[] cdaone = new StackTraceElement[1];
StackTraceElement[] cdazero = new StackTraceElement[0];
-
@Before
public void setUp() throws Exception {
mockEvent = mock(ILoggingEvent.class);
- _eelfClassOfCaller= spy(EelfClassOfCaller.class);
+ _eelfClassOfCaller = spy(EelfClassOfCaller.class);
}
-
@Test
- public void getFullyQualifiedNameCDALENFiveTest(){
- StackTraceElement temp = new StackTraceElement("classname_five","methodname","filename", 4);
- cdafive[2]=temp;
+ public void getFullyQualifiedNameCDALENFiveTest() {
+ StackTraceElement temp = new StackTraceElement("classname_five", "methodname", "filename", 4);
+ cdafive[2] = temp;
when(mockEvent.getCallerData()).thenReturn(cdafive);
- assertEquals(_eelfClassOfCaller.getFullyQualifiedName(mockEvent),"classname_five");
+ assertEquals(_eelfClassOfCaller.getFullyQualifiedName(mockEvent), "classname_five");
}
+
@Test
- public void getFullyQualifiedNameCDALenOneTest(){
- StackTraceElement temp = new StackTraceElement("classname_one","methodname","filename", 4);
- cdaone[0]=temp;
+ public void getFullyQualifiedNameCDALenOneTest() {
+ StackTraceElement temp = new StackTraceElement("classname_one", "methodname", "filename", 4);
+ cdaone[0] = temp;
when(mockEvent.getCallerData()).thenReturn(cdaone);
- assertEquals(_eelfClassOfCaller.getFullyQualifiedName(mockEvent),"classname_one");
+ assertEquals(_eelfClassOfCaller.getFullyQualifiedName(mockEvent), "classname_one");
}
@Test
- public void getFullyQualifiedNameCDALenZeroTest(){
+ public void getFullyQualifiedNameCDALenZeroTest() {
when(mockEvent.getCallerData()).thenReturn(cdazero);
- assertEquals(_eelfClassOfCaller.getFullyQualifiedName(mockEvent),"?");
+ assertEquals(_eelfClassOfCaller.getFullyQualifiedName(mockEvent), "?");
}
diff --git a/aai-core/src/test/java/org/onap/aai/logging/ErrorObjectTest.java b/aai-core/src/test/java/org/onap/aai/logging/ErrorObjectTest.java
index 8db1ece9..1c55bc11 100644
--- a/aai-core/src/test/java/org/onap/aai/logging/ErrorObjectTest.java
+++ b/aai-core/src/test/java/org/onap/aai/logging/ErrorObjectTest.java
@@ -17,145 +17,166 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.logging;
+import static org.junit.Assert.*;
+
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
-import static org.junit.Assert.*;
import org.junit.*;
public class ErrorObjectTest {
-
- ErrorObject newErrorObject = new ErrorObject("disposition","category","severity", 200, "restErrorCode","errorCode","errorText");
-
- //Constructor Tests
- @Test
- public void createObjectTest1(){
- //No HTTP Status argument
- ErrorObject errorObject = new ErrorObject("severity","errorcode","errortext","disposition","category");
+
+ ErrorObject newErrorObject =
+ new ErrorObject("disposition", "category", "severity", 200, "restErrorCode", "errorCode", "errorText");
+
+ // Constructor Tests
+ @Test
+ public void createObjectTest1() {
+ // No HTTP Status argument
+ ErrorObject errorObject = new ErrorObject("severity", "errorcode", "errortext", "disposition", "category");
assertNotNull(errorObject);
}
+
@Test
- public void createObjectTest2(){
- //HTTP Status code as integer
- ErrorObject errorObject = new ErrorObject("severity",200,"errorcode","errortext","disposition","category");
+ public void createObjectTest2() {
+ // HTTP Status code as integer
+ ErrorObject errorObject = new ErrorObject("severity", 200, "errorcode", "errortext", "disposition", "category");
assertNotNull(errorObject);
}
+
@Test
- public void createObjectTest3(){
- //HTTP Status code as Status
- ErrorObject errorObject = new ErrorObject("severity",Status.OK,"errorcode","errortext","disposition","category");
+ public void createObjectTest3() {
+ // HTTP Status code as Status
+ ErrorObject errorObject =
+ new ErrorObject("severity", Status.OK, "errorcode", "errortext", "disposition", "category");
assertNotNull(errorObject);
}
- //Disposition Tests
+
+ // Disposition Tests
@Test
public void getDispositionTest() {
assertEquals(newErrorObject.getDisposition(), "disposition");
}
+
@Test
public void setDispositionTest() {
newErrorObject.setDisposition("newDisposition");
assertEquals(newErrorObject.getDisposition(), "newDisposition");
}
-
- //Category Tests
+
+ // Category Tests
@Test
- public void getCategoryTest(){
+ public void getCategoryTest() {
assertEquals(newErrorObject.getCategory(), "category");
}
+
@Test
- public void setCategoryTest(){
+ public void setCategoryTest() {
newErrorObject.setCategory("newCategory");
assertEquals(newErrorObject.getCategory(), "newCategory");
}
-
- //Severity Tests
+
+ // Severity Tests
@Test
- public void getSeverityTest(){
+ public void getSeverityTest() {
assertEquals(newErrorObject.getSeverity(), "severity");
}
+
@Test
- public void setSeverityTest(){
+ public void setSeverityTest() {
newErrorObject.setSeverity("newSeverity");
assertEquals(newErrorObject.getSeverity(), "newSeverity");
}
-
- //Error Code Tests
+
+ // Error Code Tests
@Test
- public void getErrorCodeTest(){
+ public void getErrorCodeTest() {
assertEquals(newErrorObject.getErrorCode(), "errorCode");
}
+
@Test
- public void SetErrorCodeTest(){
+ public void SetErrorCodeTest() {
newErrorObject.setErrorCode("newErrorCode");
assertEquals(newErrorObject.getErrorCode(), "newErrorCode");
}
-
- //HTTP Response Code Tests
+
+ // HTTP Response Code Tests
@Test
- public void getHTTPCodeTest(){
+ public void getHTTPCodeTest() {
assertEquals(newErrorObject.getHTTPResponseCode(), Status.OK);
}
+
@Test
- public void setHTTPCodeTest(){
+ public void setHTTPCodeTest() {
newErrorObject.setHTTPResponseCode(201);
assertEquals(newErrorObject.getHTTPResponseCode(), Status.CREATED);
}
- @Test(expected=IllegalArgumentException.class)
- public void invalidHttpCodeTest(){
+
+ @Test(expected = IllegalArgumentException.class)
+ public void invalidHttpCodeTest() {
newErrorObject.setHTTPResponseCode(6281723);
}
- @Test(expected=IllegalArgumentException.class)
- public void invalidHttpCodeTest2(){
+
+ @Test(expected = IllegalArgumentException.class)
+ public void invalidHttpCodeTest2() {
newErrorObject.setHTTPResponseCode("82901");
}
-
- //Rest Error Code Tests
+
+ // Rest Error Code Tests
@Test
- public void getRestErrorCodeTest(){
+ public void getRestErrorCodeTest() {
assertEquals(newErrorObject.getRESTErrorCode(), "restErrorCode");
}
+
@Test
- public void setRestErrorCodeTest(){
+ public void setRestErrorCodeTest() {
newErrorObject.setRESTErrorCode("newRestErrorCode");
assertEquals(newErrorObject.getRESTErrorCode(), "newRestErrorCode");
}
-
- //Error Text Tests
+
+ // Error Text Tests
@Test
- public void getErrorTextTest(){
+ public void getErrorTextTest() {
assertEquals(newErrorObject.getErrorText(), "errorText");
}
+
@Test
- public void setErrorTextTest(){
+ public void setErrorTextTest() {
newErrorObject.setErrorText("newErrorText");
assertEquals(newErrorObject.getErrorText(), "newErrorText");
}
+
@Test
- public void getErrorCodeStringTest(){
+ public void getErrorCodeStringTest() {
assertEquals(newErrorObject.getErrorCodeString(), "disposition.category.errorCode");
}
+
@Test
- public void getErrorCodeStringDisposition5Test(){
- //get Error Code String while Disposition = 5
+ public void getErrorCodeStringDisposition5Test() {
+ // get Error Code String while Disposition = 5
newErrorObject.setDisposition("5");
assertEquals(newErrorObject.getErrorCodeString(), "ERR.5.category.errorCode");
}
+
@Test
- public void getSeverityCodeTest(){
+ public void getSeverityCodeTest() {
newErrorObject.setSeverity("WARN");
assertEquals(newErrorObject.getSeverityCode(newErrorObject.getSeverity()), "1");
-
+
newErrorObject.setSeverity("ERROR");
assertEquals(newErrorObject.getSeverityCode(newErrorObject.getSeverity()), "2");
-
+
newErrorObject.setSeverity("FATAL");
assertEquals(newErrorObject.getSeverityCode(newErrorObject.getSeverity()), "3");
}
- //To String Test
+
+ // To String Test
@Test
- public void toStringTest(){
- assertEquals(newErrorObject.toString(), "ErrorObject [errorCode=errorCode, errorText=errorText, restErrorCode=restErrorCode, httpResponseCode=OK, severity=severity, disposition=disposition, category=category]");
+ public void toStringTest() {
+ assertEquals(newErrorObject.toString(),
+ "ErrorObject [errorCode=errorCode, errorText=errorText, restErrorCode=restErrorCode, httpResponseCode=OK, severity=severity, disposition=disposition, category=category]");
}
}
diff --git a/aai-core/src/test/java/org/onap/aai/logging/LoggingContextTest.java b/aai-core/src/test/java/org/onap/aai/logging/LoggingContextTest.java
index 0e2a1c3d..74347730 100644
--- a/aai-core/src/test/java/org/onap/aai/logging/LoggingContextTest.java
+++ b/aai-core/src/test/java/org/onap/aai/logging/LoggingContextTest.java
@@ -17,13 +17,14 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.logging;
-import org.junit.Test;
+import static org.junit.Assert.*;
import java.util.*;
-import static org.junit.Assert.*;
+import org.junit.Test;
public class LoggingContextTest {
@@ -33,9 +34,10 @@ public class LoggingContextTest {
public void testStopWatch() {
try {
LoggingContext.stopWatchStop();
- throw new AssertionError("No exception thrown when LoggingContext.stopWatchStop() called without a prior LoggingContext.stopWatchStart()");
+ throw new AssertionError(
+ "No exception thrown when LoggingContext.stopWatchStop() called without a prior LoggingContext.stopWatchStart()");
} catch (StopWatchNotStartedException e) {
- //Expected
+ // Expected
}
LoggingContext.stopWatchStart();
@@ -46,12 +48,12 @@ public class LoggingContextTest {
LoggingContext.stopWatchStop();
throw new AssertionError("No exception thrown when LoggingContext.stopWatchStop() twice in succession");
} catch (StopWatchNotStartedException e) {
- //Expected
+ // Expected
}
}
@Test
- public void testRequestId() { //AKA Transaction ID
+ public void testRequestId() { // AKA Transaction ID
final String sUuid = "57d51eaa-edc6-4f50-a69d-f2d4d2445120";
LoggingContext.requestId(sUuid);
@@ -64,12 +66,12 @@ public class LoggingContextTest {
assertEquals(LoggingContext.requestId(), uuid);
- LoggingContext.requestId("foo"); //Illegal - this will result in a new, randomly
- //generated UUID as per the logging spec
+ LoggingContext.requestId("foo"); // Illegal - this will result in a new, randomly
+ // generated UUID as per the logging spec
- assertNotNull(LoggingContext.requestId()); //Make sure ANY UUID was assigned
- assertNotEquals(LoggingContext.requestId(), uuid); //Make sure it actually changed from the last
- //known valid UUID
+ assertNotNull(LoggingContext.requestId()); // Make sure ANY UUID was assigned
+ assertNotEquals(LoggingContext.requestId(), uuid); // Make sure it actually changed from the last
+ // known valid UUID
}
@Test
@@ -83,13 +85,13 @@ public class LoggingContextTest {
@Test
public void testSaveRestore() {
- final Deque<Map<String, String>> contexts = new LinkedList<Map<String, String>> ();
+ final Deque<Map<String, String>> contexts = new LinkedList<Map<String, String>>();
LoggingContext.init();
for (int i = 0; i < MAX_STORED_CONTEXTS; i++) {
LoggingContext.customField1(String.valueOf(i));
-
+
assertEquals(LoggingContext.customField1(), String.valueOf(i));
LoggingContext.save();
diff --git a/aai-core/src/test/java/org/onap/aai/parsers/query/GraphTraversalTest.java b/aai-core/src/test/java/org/onap/aai/parsers/query/GraphTraversalTest.java
index 478f8bfa..1f347318 100644
--- a/aai-core/src/test/java/org/onap/aai/parsers/query/GraphTraversalTest.java
+++ b/aai-core/src/test/java/org/onap/aai/parsers/query/GraphTraversalTest.java
@@ -17,8 +17,25 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.parsers.query;
+import static org.hamcrest.CoreMatchers.containsString;
+import static org.hamcrest.Matchers.hasProperty;
+import static org.hamcrest.Matchers.is;
+import static org.junit.Assert.assertEquals;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URI;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+
+import javax.ws.rs.core.MultivaluedHashMap;
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.core.UriBuilder;
+
import org.apache.tinkerpop.gremlin.process.traversal.P;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__;
@@ -35,26 +52,11 @@ import org.onap.aai.db.props.AAIProperties;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.introspection.ModelType;
import org.onap.aai.rest.RestTokens;
-import org.onap.aai.serialization.engines.QueryStyle;
import org.onap.aai.serialization.engines.JanusGraphDBEngine;
+import org.onap.aai.serialization.engines.QueryStyle;
import org.onap.aai.serialization.engines.TransactionalGraphEngine;
import org.springframework.test.annotation.DirtiesContext;
-import javax.ws.rs.core.MultivaluedHashMap;
-import javax.ws.rs.core.MultivaluedMap;
-import javax.ws.rs.core.UriBuilder;
-import java.io.UnsupportedEncodingException;
-import java.net.URI;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.List;
-
-import static org.hamcrest.CoreMatchers.containsString;
-import static org.hamcrest.Matchers.hasProperty;
-import static org.hamcrest.Matchers.is;
-import static org.junit.Assert.assertEquals;
-
@RunWith(value = Parameterized.class)
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
public class GraphTraversalTest extends DataLinkSetup {
@@ -67,32 +69,26 @@ public class GraphTraversalTest extends DataLinkSetup {
@Parameterized.Parameters(name = "QueryStyle.{0}")
public static Collection<Object[]> data() {
- return Arrays.asList(new Object[][]{
- {QueryStyle.TRAVERSAL},
- {QueryStyle.TRAVERSAL_URI}
- });
+ return Arrays.asList(new Object[][] {{QueryStyle.TRAVERSAL}, {QueryStyle.TRAVERSAL_URI}});
}
- @Rule public ExpectedException thrown = ExpectedException.none();
-
+ @Rule
+ public ExpectedException thrown = ExpectedException.none();
/**
* Configure.
+ *
* @throws Exception
* @throws SecurityException
* @throws NoSuchFieldException
*/
@Before
public void configure() throws Exception {
- dbEngine =
- new JanusGraphDBEngine(queryStyle,
- loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getDefaultVersion()),
- false);
-
- dbEngineDepthVersion =
- new JanusGraphDBEngine(queryStyle,
- loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getDepthVersion()),
- false);
+ dbEngine = new JanusGraphDBEngine(queryStyle,
+ loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getDefaultVersion()), false);
+
+ dbEngineDepthVersion = new JanusGraphDBEngine(queryStyle,
+ loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getDepthVersion()), false);
}
/**
@@ -107,25 +103,15 @@ public class GraphTraversalTest extends DataLinkSetup {
QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri);
- GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start().has("physical-location-id", "key1").has("aai-node-type", "complex");
- assertEquals(
- "gremlin query should be " + expected.toString(),
- expected.toString(),
+ GraphTraversal<Vertex, Vertex> expected =
+ __.<Vertex>start().has("physical-location-id", "key1").has("aai-node-type", "complex");
+ assertEquals("gremlin query should be " + expected.toString(), expected.toString(),
query.getQueryBuilder().getQuery().toString());
- assertEquals(
- "parent gremlin query should be equal to normal query",
- expected.toString(),
+ assertEquals("parent gremlin query should be equal to normal query", expected.toString(),
query.getQueryBuilder().getParentQuery().getQuery().toString());
- assertEquals(
- "result type should be complex",
- "complex",
- query.getResultType());
- assertEquals(
- "result type should be empty",
- "",
- query.getParentResultType());
- assertEquals("dependent",false, query.isDependent());
-
+ assertEquals("result type should be complex", "complex", query.getResultType());
+ assertEquals("result type should be empty", "", query.getParentResultType());
+ assertEquals("dependent", false, query.isDependent());
}
@@ -137,33 +123,21 @@ public class GraphTraversalTest extends DataLinkSetup {
*/
@Test
public void childQuery() throws UnsupportedEncodingException, AAIException {
- URI uri = UriBuilder.fromPath("cloud-infrastructure/complexes/complex/key1/ctag-pools/ctag-pool/key2/key3").build();
+ URI uri = UriBuilder.fromPath("cloud-infrastructure/complexes/complex/key1/ctag-pools/ctag-pool/key2/key3")
+ .build();
QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri);
- GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start()
- .has("physical-location-id", "key1").has("aai-node-type", "complex")
- .in("org.onap.relationships.inventory.BelongsTo")
- .has("aai-node-type", "ctag-pool")
- .has("target-pe", "key2").has("availability-zone-name", "key3");
- GraphTraversal<Vertex, Vertex> expectedParent = __.<Vertex>start()
- .has("physical-location-id", "key1").has("aai-node-type", "complex");
- assertEquals(
- "gremlin query should be " + expected.toString(),
- expected.toString(),
+ GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start().has("physical-location-id", "key1")
+ .has("aai-node-type", "complex").in("org.onap.relationships.inventory.BelongsTo")
+ .has("aai-node-type", "ctag-pool").has("target-pe", "key2").has("availability-zone-name", "key3");
+ GraphTraversal<Vertex, Vertex> expectedParent =
+ __.<Vertex>start().has("physical-location-id", "key1").has("aai-node-type", "complex");
+ assertEquals("gremlin query should be " + expected.toString(), expected.toString(),
query.getQueryBuilder().getQuery().toString());
- assertEquals(
- "parent gremlin query should be equal the query for complex",
- expectedParent.toString(),
+ assertEquals("parent gremlin query should be equal the query for complex", expectedParent.toString(),
query.getQueryBuilder().getParentQuery().getQuery().toString());
- assertEquals(
- "result type should be complex",
- "complex",
- query.getParentResultType());
- assertEquals(
- "result type should be ctag-pool",
- "ctag-pool",
- query.getResultType());
- assertEquals("dependent",true, query.isDependent());
-
+ assertEquals("result type should be complex", "complex", query.getParentResultType());
+ assertEquals("result type should be ctag-pool", "ctag-pool", query.getResultType());
+ assertEquals("dependent", true, query.isDependent());
}
@@ -175,42 +149,24 @@ public class GraphTraversalTest extends DataLinkSetup {
*/
@Test
public void namingExceptions() throws UnsupportedEncodingException, AAIException {
- URI uri = UriBuilder.fromPath("network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags/cvlan-tag/655").build();
+ URI uri = UriBuilder.fromPath("network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags/cvlan-tag/655")
+ .build();
QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri);
- GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start()
- .has("vnf-id", "key1").has("aai-node-type", "vce")
- .in("org.onap.relationships.inventory.BelongsTo")
- .has("aai-node-type", "port-group")
+ GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start().has("vnf-id", "key1").has("aai-node-type", "vce")
+ .in("org.onap.relationships.inventory.BelongsTo").has("aai-node-type", "port-group")
.has("interface-id", "key2").in("org.onap.relationships.inventory.BelongsTo")
- .has("aai-node-type", "cvlan-tag")
- .has("cvlan-tag", 655);
- GraphTraversal<Vertex, Vertex> expectedParent = __.<Vertex>start()
- .has("vnf-id", "key1").has("aai-node-type", "vce")
- .in("org.onap.relationships.inventory.BelongsTo")
- .has("aai-node-type", "port-group")
- .has("interface-id", "key2");
- assertEquals(
- "gremlin query should be " + expected.toString(),
- expected.toString(),
+ .has("aai-node-type", "cvlan-tag").has("cvlan-tag", 655);
+ GraphTraversal<Vertex, Vertex> expectedParent = __.<Vertex>start().has("vnf-id", "key1")
+ .has("aai-node-type", "vce").in("org.onap.relationships.inventory.BelongsTo")
+ .has("aai-node-type", "port-group").has("interface-id", "key2");
+ assertEquals("gremlin query should be " + expected.toString(), expected.toString(),
query.getQueryBuilder().getQuery().toString());
- assertEquals(
- "parent gremlin query should be equal the query for port group",
- expectedParent.toString(),
+ assertEquals("parent gremlin query should be equal the query for port group", expectedParent.toString(),
query.getQueryBuilder().getParentQuery().getQuery().toString());
- assertEquals(
- "result type should be cvlan-tag",
- "cvlan-tag",
- query.getResultType());
- assertEquals(
- "result type should be port-group",
- "port-group",
- query.getParentResultType());
- assertEquals(
- "contaner type should be empty",
- "",
- query.getContainerType());
- assertEquals("dependent",true, query.isDependent());
-
+ assertEquals("result type should be cvlan-tag", "cvlan-tag", query.getResultType());
+ assertEquals("result type should be port-group", "port-group", query.getParentResultType());
+ assertEquals("contaner type should be empty", "", query.getContainerType());
+ assertEquals("dependent", true, query.isDependent());
}
@@ -225,39 +181,21 @@ public class GraphTraversalTest extends DataLinkSetup {
public void getAll() throws UnsupportedEncodingException, AAIException {
URI uri = UriBuilder.fromPath("network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags").build();
QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri);
- GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start()
- .has("vnf-id", "key1").has("aai-node-type", "vce")
- .in("org.onap.relationships.inventory.BelongsTo")
- .has("aai-node-type", "port-group")
+ GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start().has("vnf-id", "key1").has("aai-node-type", "vce")
+ .in("org.onap.relationships.inventory.BelongsTo").has("aai-node-type", "port-group")
.has("interface-id", "key2").in("org.onap.relationships.inventory.BelongsTo")
.has("aai-node-type", "cvlan-tag");
- GraphTraversal<Vertex, Vertex> expectedParent = __.<Vertex>start()
- .has("vnf-id", "key1").has("aai-node-type", "vce")
- .in("org.onap.relationships.inventory.BelongsTo")
- .has("aai-node-type", "port-group")
- .has("interface-id", "key2");
- assertEquals(
- "gremlin query should be " + expected.toString(),
- expected.toString(),
+ GraphTraversal<Vertex, Vertex> expectedParent = __.<Vertex>start().has("vnf-id", "key1")
+ .has("aai-node-type", "vce").in("org.onap.relationships.inventory.BelongsTo")
+ .has("aai-node-type", "port-group").has("interface-id", "key2");
+ assertEquals("gremlin query should be " + expected.toString(), expected.toString(),
query.getQueryBuilder().getQuery().toString());
- assertEquals(
- "parent gremlin query should be equal the query for port group",
- expectedParent.toString(),
+ assertEquals("parent gremlin query should be equal the query for port group", expectedParent.toString(),
query.getQueryBuilder().getParentQuery().getQuery().toString());
- assertEquals(
- "result type should be port-group",
- "port-group",
- query.getParentResultType());
- assertEquals(
- "result type should be cvlan-tag",
- "cvlan-tag",
- query.getResultType());
- assertEquals(
- "container type should be cvlan-tags",
- "cvlan-tags",
- query.getContainerType());
- assertEquals("dependent",true, query.isDependent());
-
+ assertEquals("result type should be port-group", "port-group", query.getParentResultType());
+ assertEquals("result type should be cvlan-tag", "cvlan-tag", query.getResultType());
+ assertEquals("container type should be cvlan-tags", "cvlan-tags", query.getContainerType());
+ assertEquals("dependent", true, query.isDependent());
}
@@ -265,36 +203,19 @@ public class GraphTraversalTest extends DataLinkSetup {
public void getAllParent() throws UnsupportedEncodingException, AAIException {
URI uri = UriBuilder.fromPath("cloud-infrastructure/pservers").build();
QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri);
- GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start()
- .has("aai-node-type", "pserver");
- GraphTraversal<Vertex, Vertex> expectedParent = __.<Vertex>start()
- .has("aai-node-type", "pserver");
- assertEquals(
- "gremlin query should be " + expected.toString(),
- expected.toString(),
+ GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start().has("aai-node-type", "pserver");
+ GraphTraversal<Vertex, Vertex> expectedParent = __.<Vertex>start().has("aai-node-type", "pserver");
+ assertEquals("gremlin query should be " + expected.toString(), expected.toString(),
query.getQueryBuilder().getQuery().toString());
- assertEquals(
- "parent gremlin query should be equal the query for pserver",
- expectedParent.toString(),
+ assertEquals("parent gremlin query should be equal the query for pserver", expectedParent.toString(),
query.getQueryBuilder().getParentQuery().getQuery().toString());
- assertEquals(
- "parent result type should be empty",
- "",
- query.getParentResultType());
- assertEquals(
- "result type should be pserver",
- "pserver",
- query.getResultType());
- assertEquals(
- "container type should be pservers",
- "pservers",
- query.getContainerType());
- assertEquals("dependent",false, query.isDependent());
-
+ assertEquals("parent result type should be empty", "", query.getParentResultType());
+ assertEquals("result type should be pserver", "pserver", query.getResultType());
+ assertEquals("container type should be pservers", "pservers", query.getContainerType());
+ assertEquals("dependent", false, query.isDependent());
}
-
/**
* Gets the via query param.
*
@@ -304,86 +225,58 @@ public class GraphTraversalTest extends DataLinkSetup {
*/
@Test
public void getViaQueryParam() throws UnsupportedEncodingException, AAIException {
- URI uri = UriBuilder.fromPath("cloud-infrastructure/cloud-regions/cloud-region/mycloudowner/mycloudregionid/tenants/tenant").build();
+ URI uri = UriBuilder
+ .fromPath("cloud-infrastructure/cloud-regions/cloud-region/mycloudowner/mycloudregionid/tenants/tenant")
+ .build();
MultivaluedMap<String, String> map = new MultivaluedHashMap<>();
map.putSingle("tenant-name", "Tenant1");
QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri, map);
- GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start()
- .has("cloud-owner", "mycloudowner").has("cloud-region-id", "mycloudregionid")
- .has("aai-node-type", "cloud-region")
- .in("org.onap.relationships.inventory.BelongsTo")
- .has("aai-node-type", "tenant")
- .has("tenant-name", "Tenant1");
-
- GraphTraversal<Vertex, Vertex> expectedParent = __.<Vertex>start()
- .has("cloud-owner", "mycloudowner").has("cloud-region-id", "mycloudregionid")
- .has("aai-node-type", "cloud-region");
-
- assertEquals(
- "gremlin query should be " + expected.toString(),
- expected.toString(),
+ GraphTraversal<Vertex, Vertex> expected =
+ __.<Vertex>start().has("cloud-owner", "mycloudowner").has("cloud-region-id", "mycloudregionid")
+ .has("aai-node-type", "cloud-region").in("org.onap.relationships.inventory.BelongsTo")
+ .has("aai-node-type", "tenant").has("tenant-name", "Tenant1");
+
+ GraphTraversal<Vertex, Vertex> expectedParent = __.<Vertex>start().has("cloud-owner", "mycloudowner")
+ .has("cloud-region-id", "mycloudregionid").has("aai-node-type", "cloud-region");
+
+ assertEquals("gremlin query should be " + expected.toString(), expected.toString(),
query.getQueryBuilder().getQuery().toString());
- assertEquals(
- "parent gremlin query should be equal the query for cloud-region",
- expectedParent.toString(),
+ assertEquals("parent gremlin query should be equal the query for cloud-region", expectedParent.toString(),
query.getQueryBuilder().getParentQuery().getQuery().toString());
- assertEquals(
- "result type should be cloud-region",
- "cloud-region",
- query.getParentResultType());
- assertEquals(
- "result type should be tenant",
- "tenant",
- query.getResultType());
- assertEquals(
- "container type should be empty",
- "",
- query.getContainerType());
- assertEquals("dependent",true, query.isDependent());
+ assertEquals("result type should be cloud-region", "cloud-region", query.getParentResultType());
+ assertEquals("result type should be tenant", "tenant", query.getResultType());
+ assertEquals("container type should be empty", "", query.getContainerType());
+ assertEquals("dependent", true, query.isDependent());
}
@Test
public void getViaDuplicateQueryParam() throws UnsupportedEncodingException, AAIException {
- URI uri = UriBuilder.fromPath("cloud-infrastructure/cloud-regions/cloud-region/mycloudowner/mycloudregionid/tenants/tenant").build();
+ URI uri = UriBuilder
+ .fromPath("cloud-infrastructure/cloud-regions/cloud-region/mycloudowner/mycloudregionid/tenants/tenant")
+ .build();
MultivaluedMap<String, String> map = new MultivaluedHashMap<>();
List<String> values = new ArrayList<>();
values.add("Tenant1");
values.add("Tenant2");
map.put("tenant-name", values);
QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri, map);
- GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start()
- .has("cloud-owner", "mycloudowner").has("cloud-region-id", "mycloudregionid")
- .has("aai-node-type", "cloud-region")
- .in("org.onap.relationships.inventory.BelongsTo")
- .has("aai-node-type", "tenant")
- .has("tenant-name", P.within(values));
-
- GraphTraversal<Vertex, Vertex> expectedParent = __.<Vertex>start()
- .has("cloud-owner", "mycloudowner").has("cloud-region-id", "mycloudregionid")
- .has("aai-node-type", "cloud-region");
-
- assertEquals(
- "gremlin query should be " + expected.toString(),
- expected.toString(),
+ GraphTraversal<Vertex, Vertex> expected =
+ __.<Vertex>start().has("cloud-owner", "mycloudowner").has("cloud-region-id", "mycloudregionid")
+ .has("aai-node-type", "cloud-region").in("org.onap.relationships.inventory.BelongsTo")
+ .has("aai-node-type", "tenant").has("tenant-name", P.within(values));
+
+ GraphTraversal<Vertex, Vertex> expectedParent = __.<Vertex>start().has("cloud-owner", "mycloudowner")
+ .has("cloud-region-id", "mycloudregionid").has("aai-node-type", "cloud-region");
+
+ assertEquals("gremlin query should be " + expected.toString(), expected.toString(),
query.getQueryBuilder().getQuery().toString());
- assertEquals(
- "parent gremlin query should be equal the query for cloud-region",
- expectedParent.toString(),
+ assertEquals("parent gremlin query should be equal the query for cloud-region", expectedParent.toString(),
query.getQueryBuilder().getParentQuery().getQuery().toString());
- assertEquals(
- "result type should be cloud-region",
- "cloud-region",
- query.getParentResultType());
- assertEquals(
- "result type should be tenant",
- "tenant",
- query.getResultType());
- assertEquals(
- "container type should be empty",
- "",
- query.getContainerType());
- assertEquals("dependent",true, query.isDependent());
+ assertEquals("result type should be cloud-region", "cloud-region", query.getParentResultType());
+ assertEquals("result type should be tenant", "tenant", query.getResultType());
+ assertEquals("container type should be empty", "", query.getContainerType());
+ assertEquals("dependent", true, query.isDependent());
}
@@ -400,34 +293,19 @@ public class GraphTraversalTest extends DataLinkSetup {
MultivaluedMap<String, String> map = new MultivaluedHashMap<>();
map.putSingle("prov-status", "up");
QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri, map);
- GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start()
- .has("aai-node-type", "vnfc")
- .has("prov-status", "up");
+ GraphTraversal<Vertex, Vertex> expected =
+ __.<Vertex>start().has("aai-node-type", "vnfc").has("prov-status", "up");
- GraphTraversal<Vertex, Vertex> expectedParent = __.<Vertex>start()
- .has("aai-node-type", "vnfc");
+ GraphTraversal<Vertex, Vertex> expectedParent = __.<Vertex>start().has("aai-node-type", "vnfc");
- assertEquals(
- "gremlin query should be " + expected.toString(),
- expected.toString(),
+ assertEquals("gremlin query should be " + expected.toString(), expected.toString(),
query.getQueryBuilder().getQuery().toString());
- assertEquals(
- "parent",
- expectedParent.toString(),
+ assertEquals("parent", expectedParent.toString(),
query.getQueryBuilder().getParentQuery().getQuery().toString());
- assertEquals(
- "parent result type should be empty",
- "",
- query.getParentResultType());
- assertEquals(
- "result type should be vnfc",
- "vnfc",
- query.getResultType());
- assertEquals(
- "container type should be empty",
- "vnfcs",
- query.getContainerType());
- assertEquals("dependent",true, query.isDependent());
+ assertEquals("parent result type should be empty", "", query.getParentResultType());
+ assertEquals("result type should be vnfc", "vnfc", query.getResultType());
+ assertEquals("container type should be empty", "vnfcs", query.getContainerType());
+ assertEquals("dependent", true, query.isDependent());
}
@@ -445,40 +323,21 @@ public class GraphTraversalTest extends DataLinkSetup {
map.putSingle("cvlan-tag", "333");
QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri, map);
- GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start()
- .has("vnf-id", "key1").has("aai-node-type", "vce")
- .in("org.onap.relationships.inventory.BelongsTo")
- .has("aai-node-type", "port-group")
+ GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start().has("vnf-id", "key1").has("aai-node-type", "vce")
+ .in("org.onap.relationships.inventory.BelongsTo").has("aai-node-type", "port-group")
.has("interface-id", "key2").in("org.onap.relationships.inventory.BelongsTo")
- .has("aai-node-type", "cvlan-tag")
- .has("cvlan-tag", 333);
- GraphTraversal<Vertex, Vertex> expectedParent = __.<Vertex>start()
- .has("vnf-id", "key1").has("aai-node-type", "vce")
- .in("org.onap.relationships.inventory.BelongsTo")
- .has("aai-node-type", "port-group")
- .has("interface-id", "key2");
- assertEquals(
- "gremlin query should be " + expected.toString(),
- expected.toString(),
+ .has("aai-node-type", "cvlan-tag").has("cvlan-tag", 333);
+ GraphTraversal<Vertex, Vertex> expectedParent = __.<Vertex>start().has("vnf-id", "key1")
+ .has("aai-node-type", "vce").in("org.onap.relationships.inventory.BelongsTo")
+ .has("aai-node-type", "port-group").has("interface-id", "key2");
+ assertEquals("gremlin query should be " + expected.toString(), expected.toString(),
query.getQueryBuilder().getQuery().toString());
- assertEquals(
- "parent gremlin query should be equal the query for port group",
- expectedParent.toString(),
+ assertEquals("parent gremlin query should be equal the query for port group", expectedParent.toString(),
query.getQueryBuilder().getParentQuery().getQuery().toString());
- assertEquals(
- "result type should be port-group",
- "port-group",
- query.getParentResultType());
- assertEquals(
- "result type should be cvlan-tag",
- "cvlan-tag",
- query.getResultType());
- assertEquals(
- "container type should be cvlan-tags",
- "cvlan-tags",
- query.getContainerType());
- assertEquals("dependent",true, query.isDependent());
-
+ assertEquals("result type should be port-group", "port-group", query.getParentResultType());
+ assertEquals("result type should be cvlan-tag", "cvlan-tag", query.getResultType());
+ assertEquals("container type should be cvlan-tags", "cvlan-tags", query.getContainerType());
+ assertEquals("dependent", true, query.isDependent());
}
@@ -494,29 +353,18 @@ public class GraphTraversalTest extends DataLinkSetup {
QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri);
- GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start()
- .has("vnf-id", "key1").has(AAIProperties.NODE_TYPE, P.within("vce", "generic-vnf"));
+ GraphTraversal<Vertex, Vertex> expected =
+ __.<Vertex>start().has("vnf-id", "key1").has(AAIProperties.NODE_TYPE, P.within("vce", "generic-vnf"));
GraphTraversal<Vertex, Vertex> expectedParent = expected;
- assertEquals(
- "gremlin query should be " + expected.toString(),
- expected.toString(),
+ assertEquals("gremlin query should be " + expected.toString(), expected.toString(),
query.getQueryBuilder().getQuery().toString());
- assertEquals(
- "parent gremlin query should be equal the query for port group",
- expectedParent.toString(),
+ assertEquals("parent gremlin query should be equal the query for port group", expectedParent.toString(),
query.getQueryBuilder().getParentQuery().getQuery().toString());
- assertEquals(
- "result type should be empty",
- "",
- query.getParentResultType());
- assertEquals(
- "result type should be vnf",
- "vnf",
- query.getResultType());
-
- assertEquals("dependent",false, query.isDependent());
+ assertEquals("result type should be empty", "", query.getParentResultType());
+ assertEquals("result type should be vnf", "vnf", query.getResultType());
+ assertEquals("dependent", false, query.isDependent());
}
@@ -540,30 +388,21 @@ public class GraphTraversalTest extends DataLinkSetup {
QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri);
- GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start()
- .has("vnf-id", "key1").has(AAIProperties.NODE_TYPE, P.within("vce", "generic-vnf"))
- .union(__.in("org.onap.relationships.inventory.BelongsTo").has(AAIProperties.NODE_TYPE, "vf-module")).has("vf-module-id", "key2");
+ GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start().has("vnf-id", "key1")
+ .has(AAIProperties.NODE_TYPE, P.within("vce", "generic-vnf"))
+ .union(__.in("org.onap.relationships.inventory.BelongsTo").has(AAIProperties.NODE_TYPE, "vf-module"))
+ .has("vf-module-id", "key2");
- GraphTraversal<Vertex, Vertex> expectedParent = __.<Vertex>start()
- .has("vnf-id", "key1").has(AAIProperties.NODE_TYPE, P.within("vce", "generic-vnf"));
- assertEquals(
- "gremlin query should be " + expected.toString(),
- expected.toString(),
+ GraphTraversal<Vertex, Vertex> expectedParent =
+ __.<Vertex>start().has("vnf-id", "key1").has(AAIProperties.NODE_TYPE, P.within("vce", "generic-vnf"));
+ assertEquals("gremlin query should be " + expected.toString(), expected.toString(),
query.getQueryBuilder().getQuery().toString());
- assertEquals(
- "parent gremlin query should be equal the query for ",
- expectedParent.toString(),
+ assertEquals("parent gremlin query should be equal the query for ", expectedParent.toString(),
query.getQueryBuilder().getParentQuery().getQuery().toString());
- assertEquals(
- "result type should be vnf",
- "vnf",
- query.getParentResultType());
- assertEquals(
- "result type should be vf-module",
- "vf-module",
- query.getResultType());
+ assertEquals("result type should be vnf", "vnf", query.getParentResultType());
+ assertEquals("result type should be vf-module", "vf-module", query.getResultType());
- assertEquals("dependent",true, query.isDependent());
+ assertEquals("dependent", true, query.isDependent());
}
@@ -603,34 +442,19 @@ public class GraphTraversalTest extends DataLinkSetup {
values.add("start");
map.put("prov-status", values);
QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri, map);
- GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start()
- .has("aai-node-type", "vnfc")
- .has("prov-status", P.within(values));
+ GraphTraversal<Vertex, Vertex> expected =
+ __.<Vertex>start().has("aai-node-type", "vnfc").has("prov-status", P.within(values));
- GraphTraversal<Vertex, Vertex> expectedParent = __.<Vertex>start()
- .has("aai-node-type", "vnfc");
+ GraphTraversal<Vertex, Vertex> expectedParent = __.<Vertex>start().has("aai-node-type", "vnfc");
- assertEquals(
- "gremlin query should be " + expected.toString(),
- expected.toString(),
+ assertEquals("gremlin query should be " + expected.toString(), expected.toString(),
query.getQueryBuilder().getQuery().toString());
- assertEquals(
- "parent",
- expectedParent.toString(),
+ assertEquals("parent", expectedParent.toString(),
query.getQueryBuilder().getParentQuery().getQuery().toString());
- assertEquals(
- "parent result type should be empty",
- "",
- query.getParentResultType());
- assertEquals(
- "result type should be vnfc",
- "vnfc",
- query.getResultType());
- assertEquals(
- "container type should be empty",
- "vnfcs",
- query.getContainerType());
- assertEquals("dependent",true, query.isDependent());
+ assertEquals("parent result type should be empty", "", query.getParentResultType());
+ assertEquals("result type should be vnfc", "vnfc", query.getResultType());
+ assertEquals("container type should be empty", "vnfcs", query.getContainerType());
+ assertEquals("dependent", true, query.isDependent());
}
@@ -640,31 +464,18 @@ public class GraphTraversalTest extends DataLinkSetup {
MultivaluedMap<String, String> map = new MultivaluedHashMap<>();
map.putSingle("persona-model-customization-id", "key2");
QueryParser query = dbEngineDepthVersion.getQueryBuilder().createQueryFromURI(uri, map);
- GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start()
- .has("aai-node-type", "generic-vnf")
- .has("model-customization-id", "key2");
- GraphTraversal<Vertex, Vertex> expectedParent = __.<Vertex>start()
- .has("aai-node-type", "generic-vnf");
-
- assertEquals(
- "gremlin query should be " + expected.toString(),
- expected.toString(),
+ GraphTraversal<Vertex, Vertex> expected =
+ __.<Vertex>start().has("aai-node-type", "generic-vnf").has("model-customization-id", "key2");
+ GraphTraversal<Vertex, Vertex> expectedParent = __.<Vertex>start().has("aai-node-type", "generic-vnf");
+
+ assertEquals("gremlin query should be " + expected.toString(), expected.toString(),
query.getQueryBuilder().getQuery().toString());
- assertEquals(
- "parent",
- expectedParent.toString(),
+ assertEquals("parent", expectedParent.toString(),
query.getQueryBuilder().getParentQuery().getQuery().toString());
- assertEquals(
- "result type should be",
- "generic-vnf",
- query.getResultType());
- assertEquals(
- "result type should be empty",
- "",
- query.getParentResultType());
- assertEquals("dependent",true, query.isDependent());
-
+ assertEquals("result type should be", "generic-vnf", query.getResultType());
+ assertEquals("result type should be empty", "", query.getParentResultType());
+ assertEquals("dependent", true, query.isDependent());
}
@@ -674,30 +485,19 @@ public class GraphTraversalTest extends DataLinkSetup {
MultivaluedMap<String, String> map = new MultivaluedHashMap<>();
map.putSingle("global-route-target", "key2");
QueryParser query = dbEngineDepthVersion.getQueryBuilder().createQueryFromURI(uri, map);
- GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start()
- .has("aai-node-type", "vpn-binding")
- .where(__.in("org.onap.relationships.inventory.BelongsTo").has(AAIProperties.NODE_TYPE, "route-target").has("global-route-target", "key2"));
- GraphTraversal<Vertex, Vertex> expectedParent = __.<Vertex>start()
- .has("aai-node-type", "vpn-binding");
-
- assertEquals(
- "gremlin query should be " + expected.toString(),
- expected.toString(),
+ GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start().has("aai-node-type", "vpn-binding")
+ .where(__.in("org.onap.relationships.inventory.BelongsTo").has(AAIProperties.NODE_TYPE, "route-target")
+ .has("global-route-target", "key2"));
+ GraphTraversal<Vertex, Vertex> expectedParent = __.<Vertex>start().has("aai-node-type", "vpn-binding");
+
+ assertEquals("gremlin query should be " + expected.toString(), expected.toString(),
query.getQueryBuilder().getQuery().toString());
- assertEquals(
- "parent",
- expectedParent.toString(),
+ assertEquals("parent", expectedParent.toString(),
query.getQueryBuilder().getParentQuery().getQuery().toString());
- assertEquals(
- "result type should be",
- "vpn-binding",
- query.getResultType());
- assertEquals(
- "result type should be empty",
- "",
- query.getParentResultType());
- assertEquals("dependent",true, query.isDependent());
+ assertEquals("result type should be", "vpn-binding", query.getResultType());
+ assertEquals("result type should be empty", "", query.getParentResultType());
+ assertEquals("dependent", true, query.isDependent());
}
@Test
@@ -705,107 +505,70 @@ public class GraphTraversalTest extends DataLinkSetup {
URI uri = UriBuilder.fromPath("cloud-infrastructure/complexes/complex/key1/related-to/pservers").build();
QueryParser query = dbEngineDepthVersion.getQueryBuilder().createQueryFromURI(uri);
- GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start()
- .has("physical-location-id", "key1")
- .has("aai-node-type", "complex")
- .in("org.onap.relationships.inventory.LocatedIn").has("aai-node-type", "pserver");
- GraphTraversal<Vertex, Vertex> expectedParent = __.<Vertex>start()
- .has("physical-location-id", "key1")
- .has("aai-node-type", "complex");
-
- assertEquals(
- "gremlin query should be " + expected.toString(),
- expected.toString(),
+ GraphTraversal<Vertex, Vertex> expected =
+ __.<Vertex>start().has("physical-location-id", "key1").has("aai-node-type", "complex")
+ .in("org.onap.relationships.inventory.LocatedIn").has("aai-node-type", "pserver");
+ GraphTraversal<Vertex, Vertex> expectedParent =
+ __.<Vertex>start().has("physical-location-id", "key1").has("aai-node-type", "complex");
+
+ assertEquals("gremlin query should be " + expected.toString(), expected.toString(),
query.getQueryBuilder().getQuery().toString());
- assertEquals(
- "parent",
- expectedParent.toString(),
+ assertEquals("parent", expectedParent.toString(),
query.getQueryBuilder().getParentQuery().getQuery().toString());
- assertEquals(
- "result type should be",
- "pserver",
- query.getResultType());
- assertEquals(
- "result type should be",
- "complex",
- query.getParentResultType());
- //this is controversial but we're not allowing writes on this currently
- assertEquals("dependent",true, query.isDependent());
+ assertEquals("result type should be", "pserver", query.getResultType());
+ assertEquals("result type should be", "complex", query.getParentResultType());
+ // this is controversial but we're not allowing writes on this currently
+ assertEquals("dependent", true, query.isDependent());
}
@Test
public void specificCousin() throws UnsupportedEncodingException, AAIException {
- URI uri = UriBuilder.fromPath("cloud-infrastructure/complexes/complex/key1/related-to/pservers/pserver/key2").build();
+ URI uri = UriBuilder.fromPath("cloud-infrastructure/complexes/complex/key1/related-to/pservers/pserver/key2")
+ .build();
QueryParser query = dbEngineDepthVersion.getQueryBuilder().createQueryFromURI(uri);
- GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start()
- .has("physical-location-id", "key1")
- .has("aai-node-type", "complex")
- .in("org.onap.relationships.inventory.LocatedIn").has("aai-node-type", "pserver")
- .has("hostname", "key2");
- GraphTraversal<Vertex, Vertex> expectedParent = __.<Vertex>start()
- .has("physical-location-id", "key1")
- .has("aai-node-type", "complex");
-
- assertEquals(
- "gremlin query should be " + expected.toString(),
- expected.toString(),
+ GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start().has("physical-location-id", "key1")
+ .has("aai-node-type", "complex").in("org.onap.relationships.inventory.LocatedIn")
+ .has("aai-node-type", "pserver").has("hostname", "key2");
+ GraphTraversal<Vertex, Vertex> expectedParent =
+ __.<Vertex>start().has("physical-location-id", "key1").has("aai-node-type", "complex");
+
+ assertEquals("gremlin query should be " + expected.toString(), expected.toString(),
query.getQueryBuilder().getQuery().toString());
- assertEquals(
- "parent",
- expectedParent.toString(),
+ assertEquals("parent", expectedParent.toString(),
query.getQueryBuilder().getParentQuery().getQuery().toString());
- assertEquals(
- "result type should be",
- "pserver",
- query.getResultType());
- assertEquals(
- "result type should be",
- "complex",
- query.getParentResultType());
- //this is controversial but we're not allowing writes on this currently
- assertEquals("dependent",true, query.isDependent());
+ assertEquals("result type should be", "pserver", query.getResultType());
+ assertEquals("result type should be", "complex", query.getParentResultType());
+ // this is controversial but we're not allowing writes on this currently
+ assertEquals("dependent", true, query.isDependent());
}
@Test
public void doubleSpecificCousin() throws UnsupportedEncodingException, AAIException {
- URI uri = UriBuilder.fromPath("cloud-infrastructure/complexes/complex/key1/related-to/pservers/pserver/key2/related-to/vservers/vserver/key3").build();
+ URI uri = UriBuilder.fromPath(
+ "cloud-infrastructure/complexes/complex/key1/related-to/pservers/pserver/key2/related-to/vservers/vserver/key3")
+ .build();
QueryParser query = dbEngineDepthVersion.getQueryBuilder().createQueryFromURI(uri);
- GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start()
- .has("physical-location-id", "key1")
- .has("aai-node-type", "complex")
- .in("org.onap.relationships.inventory.LocatedIn").has("aai-node-type", "pserver")
- .has("hostname", "key2")
- .in("tosca.relationships.HostedOn").has("aai-node-type", "vserver")
- .has("vserver-id", "key3");
- GraphTraversal<Vertex, Vertex> expectedParent = __.<Vertex>start()
- .has("physical-location-id", "key1")
- .has("aai-node-type", "complex")
- .in("org.onap.relationships.inventory.LocatedIn").has("aai-node-type", "pserver")
- .has("hostname", "key2");
-
- assertEquals(
- "gremlin query should be " + expected.toString(),
- expected.toString(),
+ GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start().has("physical-location-id", "key1")
+ .has("aai-node-type", "complex").in("org.onap.relationships.inventory.LocatedIn")
+ .has("aai-node-type", "pserver").has("hostname", "key2").in("tosca.relationships.HostedOn")
+ .has("aai-node-type", "vserver").has("vserver-id", "key3");
+ GraphTraversal<Vertex, Vertex> expectedParent = __.<Vertex>start().has("physical-location-id", "key1")
+ .has("aai-node-type", "complex").in("org.onap.relationships.inventory.LocatedIn")
+ .has("aai-node-type", "pserver").has("hostname", "key2");
+
+ assertEquals("gremlin query should be " + expected.toString(), expected.toString(),
query.getQueryBuilder().getQuery().toString());
- assertEquals(
- "parent",
- expectedParent.toString(),
+ assertEquals("parent", expectedParent.toString(),
query.getQueryBuilder().getParentQuery().getQuery().toString());
- assertEquals(
- "result type should be",
- "vserver",
- query.getResultType());
- assertEquals(
- "result type should be",
- "pserver",
- query.getParentResultType());
- //this is controversial but we're not allowing writes on this currently
- assertEquals("dependent",true, query.isDependent());
+ assertEquals("result type should be", "vserver", query.getResultType());
+ assertEquals("result type should be", "pserver", query.getParentResultType());
+ // this is controversial but we're not allowing writes on this currently
+ assertEquals("dependent", true, query.isDependent());
}
@Test
diff --git a/aai-core/src/test/java/org/onap/aai/parsers/query/LegacyQueryTest.java b/aai-core/src/test/java/org/onap/aai/parsers/query/LegacyQueryTest.java
index 8272f775..4cdc55fa 100644
--- a/aai-core/src/test/java/org/onap/aai/parsers/query/LegacyQueryTest.java
+++ b/aai-core/src/test/java/org/onap/aai/parsers/query/LegacyQueryTest.java
@@ -17,42 +17,39 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.parsers.query;
+import static org.junit.Assert.assertEquals;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URI;
+
+import javax.ws.rs.core.UriBuilder;
+import javax.xml.bind.JAXBException;
+
import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext;
import org.junit.Ignore;
import org.junit.Test;
import org.onap.aai.AAISetup;
import org.onap.aai.exceptions.AAIException;
-
import org.onap.aai.introspection.ModelType;
-import org.onap.aai.serialization.engines.QueryStyle;
import org.onap.aai.serialization.engines.JanusGraphDBEngine;
+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.UriBuilder;
-import javax.xml.bind.JAXBException;
-import java.io.UnsupportedEncodingException;
-import java.net.URI;
-
-import static org.junit.Assert.assertEquals;
-
-
@Ignore
public class LegacyQueryTest extends AAISetup {
-
private TransactionalGraphEngine dbEngine;
private SchemaVersion version;
private DynamicJAXBContext context = nodeIngestor.getContextForVersion(version);
- public void setup(){
+ public void setup() {
version = new SchemaVersion("v10");
- dbEngine =
- new JanusGraphDBEngine(QueryStyle.GREMLIN_TRAVERSAL,
- loaderFactory.createLoaderForVersion(ModelType.MOXY, version),
- false);
+ dbEngine = new JanusGraphDBEngine(QueryStyle.GREMLIN_TRAVERSAL,
+ loaderFactory.createLoaderForVersion(ModelType.MOXY, version), false);
}
/**
@@ -64,26 +61,17 @@ public class LegacyQueryTest extends AAISetup {
*/
@Test
public void parentQuery() throws JAXBException, UnsupportedEncodingException, AAIException {
-
+
URI uri = UriBuilder.fromPath("cloud-infrastructure/pservers/pserver/key1").build();
QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri);
- String expected =
- ".has('hostname', 'key1').has('aai-node-type', 'pserver')";
- assertEquals(
- "gremlin query should be " + expected,
- expected,
- query.getQueryBuilder().getQuery());
- assertEquals(
- "parent gremlin query should be equal to normal query",
- expected,
+ String expected = ".has('hostname', 'key1').has('aai-node-type', 'pserver')";
+ assertEquals("gremlin query should be " + expected, expected, query.getQueryBuilder().getQuery());
+ assertEquals("parent gremlin query should be equal to normal query", expected,
query.getQueryBuilder().getParentQuery().getQuery());
- assertEquals(
- "result type should be pserver",
- "pserver",
- query.getResultType());
-
+ assertEquals("result type should be pserver", "pserver", query.getResultType());
+
}
/**
@@ -95,29 +83,19 @@ public class LegacyQueryTest extends AAISetup {
*/
@Test
public void childQuery() throws JAXBException, UnsupportedEncodingException, AAIException {
- URI uri = UriBuilder.fromPath("cloud-infrastructure/pservers/pserver/key1/lag-interfaces/lag-interface/key2").build();
+ URI uri = UriBuilder.fromPath("cloud-infrastructure/pservers/pserver/key1/lag-interfaces/lag-interface/key2")
+ .build();
QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri);
- String expected =
- ".has('hostname', 'key1').has('aai-node-type', 'pserver')"
- + ".out('hasLAGInterface').has('aai-node-type', 'lag-interface')"
- + ".has('interface-name', 'key2')";
- String parentExpected =
- ".has('hostname', 'key1').has('aai-node-type', 'pserver')";
- assertEquals(
- "gremlin query should be for node",
- expected,
- query.getQueryBuilder().getQuery());
- assertEquals(
- "parent gremlin query should be for parent",
- parentExpected,
+ String expected = ".has('hostname', 'key1').has('aai-node-type', 'pserver')"
+ + ".out('hasLAGInterface').has('aai-node-type', 'lag-interface')" + ".has('interface-name', 'key2')";
+ String parentExpected = ".has('hostname', 'key1').has('aai-node-type', 'pserver')";
+ assertEquals("gremlin query should be for node", expected, query.getQueryBuilder().getQuery());
+ assertEquals("parent gremlin query should be for parent", parentExpected,
query.getQueryBuilder().getParentQuery().getQuery());
- assertEquals(
- "result type should be lag-interface",
- "lag-interface",
- query.getResultType());
+ assertEquals("result type should be lag-interface", "lag-interface", query.getResultType());
}
-
+
/**
* Naming exceptions.
*
@@ -127,32 +105,23 @@ public class LegacyQueryTest extends AAISetup {
*/
@Test
public void namingExceptions() throws JAXBException, UnsupportedEncodingException, AAIException {
- URI uri = UriBuilder.fromPath("network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags/cvlan-tag/655").build();
-
+ URI uri = UriBuilder.fromPath("network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags/cvlan-tag/655")
+ .build();
+
QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri);
- String expected =
- ".has('vnf-id', 'key1').has('aai-node-type', 'vce')"
+ String expected = ".has('vnf-id', 'key1').has('aai-node-type', 'vce')"
+ ".in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'port-group')"
+ ".has('interface-id', 'key2')"
+ ".in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'cvlan-tag')"
+ ".has('cvlan-tag', 655)";
- String expectedParent =
- ".has('vnf-id', 'key1').has('aai-node-type', 'vce')"
- + ".in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'port-group')"
- + ".has('interface-id', 'key2')";
- assertEquals(
- "gremlin query should be " + expected,
- expected,
- query.getQueryBuilder().getQuery());
- assertEquals(
- "parent gremlin query should be equal the query for port group",
- expectedParent,
+ String expectedParent = ".has('vnf-id', 'key1').has('aai-node-type', 'vce')"
+ + ".in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'port-group')"
+ + ".has('interface-id', 'key2')";
+ assertEquals("gremlin query should be " + expected, expected, query.getQueryBuilder().getQuery());
+ assertEquals("parent gremlin query should be equal the query for port group", expectedParent,
query.getQueryBuilder().getParentQuery().getQuery());
- assertEquals(
- "result type should be cvlan-tag",
- "cvlan-tag",
- query.getResultType());
-
+ assertEquals("result type should be cvlan-tag", "cvlan-tag", query.getResultType());
+
}
-
+
}
diff --git a/aai-core/src/test/java/org/onap/aai/parsers/query/RelationshipGremlinQueryTest.java b/aai-core/src/test/java/org/onap/aai/parsers/query/RelationshipGremlinQueryTest.java
index 045f6b30..96a22d4e 100644
--- a/aai-core/src/test/java/org/onap/aai/parsers/query/RelationshipGremlinQueryTest.java
+++ b/aai-core/src/test/java/org/onap/aai/parsers/query/RelationshipGremlinQueryTest.java
@@ -17,8 +17,19 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.parsers.query;
+import static org.hamcrest.CoreMatchers.containsString;
+import static org.junit.Assert.assertEquals;
+
+import java.io.StringReader;
+import java.io.UnsupportedEncodingException;
+
+import javax.xml.bind.JAXBException;
+import javax.xml.bind.Unmarshaller;
+import javax.xml.transform.stream.StreamSource;
+
import org.eclipse.persistence.dynamic.DynamicEntity;
import org.eclipse.persistence.jaxb.UnmarshallerProperties;
import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext;
@@ -31,20 +42,11 @@ import org.onap.aai.AAISetup;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.introspection.*;
import org.onap.aai.nodes.NodeIngestor;
-import org.onap.aai.setup.SchemaVersion;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.onap.aai.serialization.engines.QueryStyle;
import org.onap.aai.serialization.engines.JanusGraphDBEngine;
+import org.onap.aai.serialization.engines.QueryStyle;
import org.onap.aai.serialization.engines.TransactionalGraphEngine;
-
-import javax.xml.bind.JAXBException;
-import javax.xml.bind.Unmarshaller;
-import javax.xml.transform.stream.StreamSource;
-import java.io.StringReader;
-import java.io.UnsupportedEncodingException;
-
-import static org.hamcrest.CoreMatchers.containsString;
-import static org.junit.Assert.assertEquals;
+import org.onap.aai.setup.SchemaVersion;
+import org.springframework.beans.factory.annotation.Autowired;
@Ignore
public class RelationshipGremlinQueryTest extends AAISetup {
@@ -59,12 +61,10 @@ public class RelationshipGremlinQueryTest extends AAISetup {
public ExpectedException thrown = ExpectedException.none();
@Before
- public void setup(){
+ public void setup() {
version = new SchemaVersion("v10");
- dbEngine =
- new JanusGraphDBEngine(QueryStyle.GREMLIN_TRAVERSAL,
- loaderFactory.createLoaderForVersion(ModelType.MOXY, version),
- false);
+ dbEngine = new JanusGraphDBEngine(QueryStyle.GREMLIN_TRAVERSAL,
+ loaderFactory.createLoaderForVersion(ModelType.MOXY, version), false);
}
/**
@@ -77,14 +77,8 @@ public class RelationshipGremlinQueryTest extends AAISetup {
@Test
public void parentQuery() throws JAXBException, UnsupportedEncodingException, AAIException {
- String content =
- "{"
- + "\"related-to\" : \"pserver\","
- + "\"relationship-data\" : [{"
- + "\"relationship-key\" : \"pserver.hostname\","
- + "\"relationship-value\" : \"key1\""
- + "}]"
- + "}";
+ String content = "{" + "\"related-to\" : \"pserver\"," + "\"relationship-data\" : [{"
+ + "\"relationship-key\" : \"pserver.hostname\"," + "\"relationship-value\" : \"key1\"" + "}]" + "}";
Unmarshaller unmarshaller = context.createUnmarshaller();
unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json");
@@ -92,25 +86,17 @@ public class RelationshipGremlinQueryTest extends AAISetup {
unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true);
Object obj = context.newDynamicEntity("Relationship");
- DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue();
+ DynamicEntity entity = (DynamicEntity) unmarshaller
+ .unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue();
Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity);
QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj);
- String expected =
- ".has('hostname', 'key1').has('aai-node-type', 'pserver')";
- assertEquals(
- "gremlin query should be " + expected,
- expected,
- query.getQueryBuilder().getQuery());
- assertEquals(
- "parent gremlin query should be equal to normal query",
- expected,
+ String expected = ".has('hostname', 'key1').has('aai-node-type', 'pserver')";
+ assertEquals("gremlin query should be " + expected, expected, query.getQueryBuilder().getQuery());
+ assertEquals("parent gremlin query should be equal to normal query", expected,
query.getQueryBuilder().getParentQuery().getQuery());
- assertEquals(
- "result type should be pserver",
- "pserver",
- query.getResultType());
+ assertEquals("result type should be pserver", "pserver", query.getResultType());
}
@@ -123,17 +109,10 @@ public class RelationshipGremlinQueryTest extends AAISetup {
*/
@Test
public void childQuery() throws JAXBException, UnsupportedEncodingException, AAIException {
- String content =
- "{"
- + "\"related-to\" : \"lag-interface\","
- + "\"relationship-data\" : [{"
- + "\"relationship-key\" : \"pserver.hostname\","
- + "\"relationship-value\" : \"key1\""
- + "}, {"
- + "\"relationship-key\" : \"lag-interface.interface-name\","
- + "\"relationship-value\" : \"key2\""
- + "}]"
- + "}";
+ String content = "{" + "\"related-to\" : \"lag-interface\"," + "\"relationship-data\" : [{"
+ + "\"relationship-key\" : \"pserver.hostname\"," + "\"relationship-value\" : \"key1\"" + "}, {"
+ + "\"relationship-key\" : \"lag-interface.interface-name\"," + "\"relationship-value\" : \"key2\""
+ + "}]" + "}";
Unmarshaller unmarshaller = context.createUnmarshaller();
unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json");
@@ -141,27 +120,20 @@ public class RelationshipGremlinQueryTest extends AAISetup {
unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true);
Object obj = context.newDynamicEntity("Relationship");
- DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue();
+ DynamicEntity entity = (DynamicEntity) unmarshaller
+ .unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue();
Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity);
QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj);
- String expected = ".has('hostname', 'key1').has('aai-node-type', 'pserver').in('tosca.relationships.BindsTo').has('aai-node-type', 'lag-interface')"
- + ".has('interface-name', 'key2')";
- String parentExpected =
- ".has('hostname', 'key1').has('aai-node-type', 'pserver')";
- assertEquals(
- "gremlin query should be for node",
- expected,
- query.getQueryBuilder().getQuery());
- assertEquals(
- "parent gremlin query should be for parent",
- parentExpected,
+ String expected =
+ ".has('hostname', 'key1').has('aai-node-type', 'pserver').in('tosca.relationships.BindsTo').has('aai-node-type', 'lag-interface')"
+ + ".has('interface-name', 'key2')";
+ String parentExpected = ".has('hostname', 'key1').has('aai-node-type', 'pserver')";
+ assertEquals("gremlin query should be for node", expected, query.getQueryBuilder().getQuery());
+ assertEquals("parent gremlin query should be for parent", parentExpected,
query.getQueryBuilder().getParentQuery().getQuery());
- assertEquals(
- "result type should be lag-interface",
- "lag-interface",
- query.getResultType());
+ assertEquals("result type should be lag-interface", "lag-interface", query.getResultType());
}
/**
@@ -173,20 +145,10 @@ public class RelationshipGremlinQueryTest extends AAISetup {
*/
@Test
public void namingExceptions() throws JAXBException, UnsupportedEncodingException, AAIException {
- String content =
- "{"
- + "\"related-to\" : \"cvlan-tag\","
- + "\"relationship-data\" : [{"
- + "\"relationship-key\" : \"vce.vnf-id\","
- + "\"relationship-value\" : \"key1\""
- + "}, {"
- + "\"relationship-key\" : \"port-group.interface-id\","
- + "\"relationship-value\" : \"key2\""
- + "},{"
- + "\"relationship-key\" : \"cvlan-tag.cvlan-tag\","
- + "\"relationship-value\" : \"655\""
- + "}]"
- + "}";
+ String content = "{" + "\"related-to\" : \"cvlan-tag\"," + "\"relationship-data\" : [{"
+ + "\"relationship-key\" : \"vce.vnf-id\"," + "\"relationship-value\" : \"key1\"" + "}, {"
+ + "\"relationship-key\" : \"port-group.interface-id\"," + "\"relationship-value\" : \"key2\"" + "},{"
+ + "\"relationship-key\" : \"cvlan-tag.cvlan-tag\"," + "\"relationship-value\" : \"655\"" + "}]" + "}";
Unmarshaller unmarshaller = context.createUnmarshaller();
unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json");
@@ -194,31 +156,22 @@ public class RelationshipGremlinQueryTest extends AAISetup {
unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true);
Object obj = context.newDynamicEntity("Relationship");
- DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue();
+ DynamicEntity entity = (DynamicEntity) unmarshaller
+ .unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue();
Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity);
QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj);
- String expected =
- ".has('vnf-id', 'key1').has('aai-node-type', 'vce')"
+ String expected = ".has('vnf-id', 'key1').has('aai-node-type', 'vce')"
+ ".in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'port-group')"
+ ".has('interface-id', 'key2').in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'cvlan-tag')"
+ ".has('cvlan-tag', 655)";
- String expectedParent =
- ".has('vnf-id', 'key1').has('aai-node-type', 'vce')"
- + ".in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'port-group')"
- + ".has('interface-id', 'key2')";
- assertEquals(
- "gremlin query should be " + expected,
- expected,
- query.getQueryBuilder().getQuery());
- assertEquals(
- "parent gremlin query should be equal the query for port group",
- expectedParent,
+ String expectedParent = ".has('vnf-id', 'key1').has('aai-node-type', 'vce')"
+ + ".in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'port-group')"
+ + ".has('interface-id', 'key2')";
+ assertEquals("gremlin query should be " + expected, expected, query.getQueryBuilder().getQuery());
+ assertEquals("parent gremlin query should be equal the query for port group", expectedParent,
query.getQueryBuilder().getParentQuery().getQuery());
- assertEquals(
- "result type should be cvlan-tag",
- "cvlan-tag",
- query.getResultType());
+ assertEquals("result type should be cvlan-tag", "cvlan-tag", query.getResultType());
}
@@ -231,25 +184,13 @@ public class RelationshipGremlinQueryTest extends AAISetup {
*/
@Test
public void scrambledRelationship() throws JAXBException, UnsupportedEncodingException, AAIException {
- String content =
- "{"
- + "\"related-to\" : \"l3-interface-ipv4-address-list\","
- + "\"relationship-data\" : [{"
+ String content = "{" + "\"related-to\" : \"l3-interface-ipv4-address-list\"," + "\"relationship-data\" : [{"
+ "\"relationship-key\" : \"l3-interface-ipv4-address-list.l3-interface-ipv4-address\","
- + "\"relationship-value\" : \"key5\""
- + "},{"
- + "\"relationship-key\" : \"lag-interface.interface-name\","
- + "\"relationship-value\" : \"key2\""
- + "},{"
- + "\"relationship-key\" : \"l-interface.interface-name\","
- + "\"relationship-value\" : \"key3\""
- + "},{"
- + "\"relationship-key\" : \"vlan.vlan-interface\","
- + "\"relationship-value\" : \"key4\""
- + "},{"
- + "\"relationship-key\" : \"generic-vnf.vnf-id\","
- + "\"relationship-value\" : \"key1\""
- + "}]"
+ + "\"relationship-value\" : \"key5\"" + "},{"
+ + "\"relationship-key\" : \"lag-interface.interface-name\"," + "\"relationship-value\" : \"key2\""
+ + "},{" + "\"relationship-key\" : \"l-interface.interface-name\"," + "\"relationship-value\" : \"key3\""
+ + "},{" + "\"relationship-key\" : \"vlan.vlan-interface\"," + "\"relationship-value\" : \"key4\""
+ + "},{" + "\"relationship-key\" : \"generic-vnf.vnf-id\"," + "\"relationship-value\" : \"key1\"" + "}]"
+ "}";
scrambledRelationshipSpec(content);
}
@@ -263,25 +204,13 @@ public class RelationshipGremlinQueryTest extends AAISetup {
*/
@Test
public void reversedRelationship() throws JAXBException, UnsupportedEncodingException, AAIException {
- String content =
- "{"
- + "\"related-to\" : \"l3-interface-ipv4-address-list\","
- + "\"relationship-data\" : [{"
+ String content = "{" + "\"related-to\" : \"l3-interface-ipv4-address-list\"," + "\"relationship-data\" : [{"
+ "\"relationship-key\" : \"l3-interface-ipv4-address-list.l3-interface-ipv4-address\","
- + "\"relationship-value\" : \"key5\""
- + "},{"
- + "\"relationship-key\" : \"vlan.vlan-interface\","
- + "\"relationship-value\" : \"key4\""
- + "},{"
- + "\"relationship-key\" : \"l-interface.interface-name\","
- + "\"relationship-value\" : \"key3\""
- + "},{"
- + "\"relationship-key\" : \"lag-interface.interface-name\","
- + "\"relationship-value\" : \"key2\""
- + "},{"
- + "\"relationship-key\" : \"generic-vnf.vnf-id\","
- + "\"relationship-value\" : \"key1\""
- + "}]"
+ + "\"relationship-value\" : \"key5\"" + "},{" + "\"relationship-key\" : \"vlan.vlan-interface\","
+ + "\"relationship-value\" : \"key4\"" + "},{" + "\"relationship-key\" : \"l-interface.interface-name\","
+ + "\"relationship-value\" : \"key3\"" + "},{"
+ + "\"relationship-key\" : \"lag-interface.interface-name\"," + "\"relationship-value\" : \"key2\""
+ + "},{" + "\"relationship-key\" : \"generic-vnf.vnf-id\"," + "\"relationship-value\" : \"key1\"" + "}]"
+ "}";
scrambledRelationshipSpec(content);
}
@@ -295,26 +224,13 @@ public class RelationshipGremlinQueryTest extends AAISetup {
*/
@Test
public void orderedAmbiguousRelationship() throws JAXBException, UnsupportedEncodingException, AAIException {
- String content =
- "{"
- + "\"related-to\" : \"l3-interface-ipv4-address-list\","
- + "\"relationship-data\" : [{"
- + "\"relationship-key\" : \"generic-vnf.vnf-id\","
- + "\"relationship-value\" : \"key1\""
- + "},{"
- + "\"relationship-key\" : \"lag-interface.interface-name\","
- + "\"relationship-value\" : \"key2\""
- + "},{"
- + "\"relationship-key\" : \"l-interface.interface-name\","
- + "\"relationship-value\" : \"key3\""
- + "},{"
- + "\"relationship-key\" : \"vlan.vlan-interface\","
- + "\"relationship-value\" : \"key4\""
- + "},{"
- + "\"relationship-key\" : \"l3-interface-ipv4-address-list.l3-interface-ipv4-address\","
- + "\"relationship-value\" : \"key5\""
- + "}]"
- + "}";
+ String content = "{" + "\"related-to\" : \"l3-interface-ipv4-address-list\"," + "\"relationship-data\" : [{"
+ + "\"relationship-key\" : \"generic-vnf.vnf-id\"," + "\"relationship-value\" : \"key1\"" + "},{"
+ + "\"relationship-key\" : \"lag-interface.interface-name\"," + "\"relationship-value\" : \"key2\""
+ + "},{" + "\"relationship-key\" : \"l-interface.interface-name\"," + "\"relationship-value\" : \"key3\""
+ + "},{" + "\"relationship-key\" : \"vlan.vlan-interface\"," + "\"relationship-value\" : \"key4\""
+ + "},{" + "\"relationship-key\" : \"l3-interface-ipv4-address-list.l3-interface-ipv4-address\","
+ + "\"relationship-value\" : \"key5\"" + "}]" + "}";
scrambledRelationshipSpec(content);
}
@@ -326,8 +242,8 @@ public class RelationshipGremlinQueryTest extends AAISetup {
* @throws UnsupportedEncodingException the unsupported encoding exception
* @throws AAIException the AAI exception
*/
- public void scrambledRelationshipSpec(String content) throws JAXBException, UnsupportedEncodingException, AAIException {
-
+ public void scrambledRelationshipSpec(String content)
+ throws JAXBException, UnsupportedEncodingException, AAIException {
Unmarshaller unmarshaller = context.createUnmarshaller();
unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json");
@@ -335,34 +251,26 @@ public class RelationshipGremlinQueryTest extends AAISetup {
unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true);
Object obj = context.newDynamicEntity("Relationship");
- DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue();
+ DynamicEntity entity = (DynamicEntity) unmarshaller
+ .unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue();
Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity);
QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj);
- String expected =
- ".has('vnf-id', 'key1').has('aai-node-type', 'generic-vnf')"
+ String expected = ".has('vnf-id', 'key1').has('aai-node-type', 'generic-vnf')"
+ ".in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'lag-interface')"
+ ".has('interface-name', 'key2').in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'l-interface')"
+ ".has('interface-name', 'key3').out('tosca.relationships.LinksTo').has('aai-node-type', 'vlan')"
+ ".has('vlan-interface', 'key4').in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'l3-interface-ipv4-address-list')"
+ ".has('l3-interface-ipv4-address', 'key5')";
- String expectedParent =
- ".has('vnf-id', 'key1').has('aai-node-type', 'generic-vnf')"
- + ".in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'lag-interface')"
- + ".has('interface-name', 'key2').in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'l-interface')"
- + ".has('interface-name', 'key3').out('tosca.relationships.LinksTo').has('aai-node-type', 'vlan')"
- + ".has('vlan-interface', 'key4')";
- assertEquals(
- "gremlin query should be " + expected,
- expected,
- query.getQueryBuilder().getQuery());
- assertEquals(
- "parent gremlin query should be equal the query for vlan",
- expectedParent,
+ String expectedParent = ".has('vnf-id', 'key1').has('aai-node-type', 'generic-vnf')"
+ + ".in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'lag-interface')"
+ + ".has('interface-name', 'key2').in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'l-interface')"
+ + ".has('interface-name', 'key3').out('tosca.relationships.LinksTo').has('aai-node-type', 'vlan')"
+ + ".has('vlan-interface', 'key4')";
+ assertEquals("gremlin query should be " + expected, expected, query.getQueryBuilder().getQuery());
+ assertEquals("parent gremlin query should be equal the query for vlan", expectedParent,
query.getQueryBuilder().getParentQuery().getQuery());
- assertEquals(
- "result type should be l3-interface-ipv4-address-list",
- "l3-interface-ipv4-address-list",
+ assertEquals("result type should be l3-interface-ipv4-address-list", "l3-interface-ipv4-address-list",
query.getResultType());
}
@@ -376,21 +284,12 @@ public class RelationshipGremlinQueryTest extends AAISetup {
*/
@Test
public void shortCircuit() throws JAXBException, UnsupportedEncodingException, AAIException {
- String content =
- "{"
- + "\"related-to\" : \"cvlan-tag\","
+ String content = "{" + "\"related-to\" : \"cvlan-tag\","
+ "\"related-link\" : \"http://mock-system-name.com:8443/aai/v6/network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags/cvlan-tag/655\","
- + "\"relationship-data\" : [{"
- + "\"relationship-key\" : \"vce.vnf-id\","
- + "\"relationship-value\" : \"key1\""
- + "}, {"
- + "\"relationship-key\" : \"port-group.interface-id\","
- + "\"relationship-value\" : \"key2\""
- + "},{"
- + "\"relationship-key\" : \"cvlan-tag.cvlan-tag\","
- + "\"relationship-value\" : \"655\""
- + "}]"
- + "}";
+ + "\"relationship-data\" : [{" + "\"relationship-key\" : \"vce.vnf-id\","
+ + "\"relationship-value\" : \"key1\"" + "}, {" + "\"relationship-key\" : \"port-group.interface-id\","
+ + "\"relationship-value\" : \"key2\"" + "},{" + "\"relationship-key\" : \"cvlan-tag.cvlan-tag\","
+ + "\"relationship-value\" : \"655\"" + "}]" + "}";
Unmarshaller unmarshaller = context.createUnmarshaller();
unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json");
@@ -398,39 +297,28 @@ public class RelationshipGremlinQueryTest extends AAISetup {
unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true);
Object obj = context.newDynamicEntity("Relationship");
- DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue();
+ DynamicEntity entity = (DynamicEntity) unmarshaller
+ .unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue();
Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity);
QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj);
- String expected =
- ".has('vnf-id', 'key1').has('aai-node-type', 'vce')"
+ String expected = ".has('vnf-id', 'key1').has('aai-node-type', 'vce')"
+ ".in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'port-group')"
+ ".has('interface-id', 'key2').in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'cvlan-tag')"
+ ".has('cvlan-tag', 655)";
- String expectedParent =
- ".has('vnf-id', 'key1').has('aai-node-type', 'vce')"
- + ".in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'port-group')"
- + ".has('interface-id', 'key2')";
- assertEquals(
- "gremlin query should be " + expected,
- expected,
- query.getQueryBuilder().getQuery());
- assertEquals(
- "parent gremlin query should be equal the query for port group",
- expectedParent,
+ String expectedParent = ".has('vnf-id', 'key1').has('aai-node-type', 'vce')"
+ + ".in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'port-group')"
+ + ".has('interface-id', 'key2')";
+ assertEquals("gremlin query should be " + expected, expected, query.getQueryBuilder().getQuery());
+ assertEquals("parent gremlin query should be equal the query for port group", expectedParent,
query.getQueryBuilder().getParentQuery().getQuery());
- assertEquals(
- "result type should be cvlan-tag",
- "cvlan-tag",
- query.getResultType());
+ assertEquals("result type should be cvlan-tag", "cvlan-tag", query.getResultType());
}
@Test
public void shorterCircuit() throws JAXBException, UnsupportedEncodingException, AAIException {
- String content =
- "{"
- + "\"related-to\" : \"cvlan-tag\","
+ String content = "{" + "\"related-to\" : \"cvlan-tag\","
+ "\"related-link\" : \"file:///network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags/cvlan-tag/655\""
+ "}";
@@ -440,31 +328,22 @@ public class RelationshipGremlinQueryTest extends AAISetup {
unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true);
Object obj = context.newDynamicEntity("Relationship");
- DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue();
+ DynamicEntity entity = (DynamicEntity) unmarshaller
+ .unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue();
Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity);
QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj);
- String expected =
- ".has('vnf-id', 'key1').has('aai-node-type', 'vce')"
+ String expected = ".has('vnf-id', 'key1').has('aai-node-type', 'vce')"
+ ".in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'port-group')"
+ ".has('interface-id', 'key2').in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'cvlan-tag')"
+ ".has('cvlan-tag', 655)";
- String expectedParent =
- ".has('vnf-id', 'key1').has('aai-node-type', 'vce')"
- + ".in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'port-group')"
- + ".has('interface-id', 'key2')";
- assertEquals(
- "gremlin query should be " + expected,
- expected,
- query.getQueryBuilder().getQuery());
- assertEquals(
- "parent gremlin query should be equal the query for port group",
- expectedParent,
+ String expectedParent = ".has('vnf-id', 'key1').has('aai-node-type', 'vce')"
+ + ".in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'port-group')"
+ + ".has('interface-id', 'key2')";
+ assertEquals("gremlin query should be " + expected, expected, query.getQueryBuilder().getQuery());
+ assertEquals("parent gremlin query should be equal the query for port group", expectedParent,
query.getQueryBuilder().getParentQuery().getQuery());
- assertEquals(
- "result type should be cvlan-tag",
- "cvlan-tag",
- query.getResultType());
+ assertEquals("result type should be cvlan-tag", "cvlan-tag", query.getResultType());
}
@@ -477,21 +356,11 @@ public class RelationshipGremlinQueryTest extends AAISetup {
*/
@Test
public void doubleKey() throws JAXBException, UnsupportedEncodingException, AAIException {
- String content =
- "{"
- + "\"related-to\" : \"ctag-pool\","
- + "\"relationship-data\" : [{"
- + "\"relationship-key\" : \"complex.physical-location-id\","
- + "\"relationship-value\" : \"key1\""
- + " }, { "
- + "\"relationship-key\" : \"ctag-pool.target-pe\","
- + " \"relationship-value\" : \"key2\""
- + " },{"
- + "\"relationship-key\" : \"ctag-pool.availability-zone-name\","
- + "\"relationship-value\" : \"key3\""
- + "}]"
- + "}";
-
+ String content = "{" + "\"related-to\" : \"ctag-pool\"," + "\"relationship-data\" : [{"
+ + "\"relationship-key\" : \"complex.physical-location-id\"," + "\"relationship-value\" : \"key1\""
+ + " }, { " + "\"relationship-key\" : \"ctag-pool.target-pe\"," + " \"relationship-value\" : \"key2\""
+ + " },{" + "\"relationship-key\" : \"ctag-pool.availability-zone-name\","
+ + "\"relationship-value\" : \"key3\"" + "}]" + "}";
Unmarshaller unmarshaller = context.createUnmarshaller();
unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json");
@@ -499,31 +368,21 @@ public class RelationshipGremlinQueryTest extends AAISetup {
unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true);
Object obj = context.newDynamicEntity("Relationship");
- DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue();
+ DynamicEntity entity = (DynamicEntity) unmarshaller
+ .unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue();
Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity);
QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj);
- String expected =
- ".has('physical-location-id', 'key1').has('aai-node-type', 'complex')"
+ String expected = ".has('physical-location-id', 'key1').has('aai-node-type', 'complex')"
+ ".in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'ctag-pool')"
- + ".has('target-pe', 'key2')"
- + ".has('availability-zone-name', 'key3')";
- String expectedParent =
- ".has('physical-location-id', 'key1').has('aai-node-type', 'complex')";
-
- assertEquals(
- "gremlin query should be " + expected,
- expected,
- query.getQueryBuilder().getQuery());
- assertEquals(
- "parent gremlin query should be equal the query for port group",
- expectedParent,
+ + ".has('target-pe', 'key2')" + ".has('availability-zone-name', 'key3')";
+ String expectedParent = ".has('physical-location-id', 'key1').has('aai-node-type', 'complex')";
+
+ assertEquals("gremlin query should be " + expected, expected, query.getQueryBuilder().getQuery());
+ assertEquals("parent gremlin query should be equal the query for port group", expectedParent,
query.getQueryBuilder().getParentQuery().getQuery());
- assertEquals(
- "result type should be ctag-pool",
- "ctag-pool",
- query.getResultType());
+ assertEquals("result type should be ctag-pool", "ctag-pool", query.getResultType());
}
@@ -536,15 +395,8 @@ public class RelationshipGremlinQueryTest extends AAISetup {
*/
@Test
public void abstractType() throws JAXBException, UnsupportedEncodingException, AAIException {
- String content =
- "{"
- + "\"related-to\" : \"vnf\","
- + "\"relationship-data\" : [{"
- + "\"relationship-key\" : \"vnf.vnf-id\","
- + "\"relationship-value\" : \"key1\""
- + " }]"
- + "}";
-
+ String content = "{" + "\"related-to\" : \"vnf\"," + "\"relationship-data\" : [{"
+ + "\"relationship-key\" : \"vnf.vnf-id\"," + "\"relationship-value\" : \"key1\"" + " }]" + "}";
Unmarshaller unmarshaller = context.createUnmarshaller();
unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json");
@@ -552,31 +404,20 @@ public class RelationshipGremlinQueryTest extends AAISetup {
unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true);
Object obj = context.newDynamicEntity("Relationship");
- DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue();
+ DynamicEntity entity = (DynamicEntity) unmarshaller
+ .unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue();
Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity);
QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj);
- String expected =
- ".has('vnf-id', 'key1')"
- + ".has('aai-node-type', P.within('vce','generic-vnf'))";
-
- String expectedParent =
- ".has('vnf-id', 'key1')"
- + ".has('aai-node-type', P.within('vce','generic-vnf'))";
-
- assertEquals(
- "gremlin query should be " + expected,
- expected,
- query.getQueryBuilder().getQuery());
- assertEquals(
- "parent gremlin query should be equal the query for port group",
- expectedParent,
+ String expected = ".has('vnf-id', 'key1')" + ".has('aai-node-type', P.within('vce','generic-vnf'))";
+
+ String expectedParent = ".has('vnf-id', 'key1')" + ".has('aai-node-type', P.within('vce','generic-vnf'))";
+
+ assertEquals("gremlin query should be " + expected, expected, query.getQueryBuilder().getQuery());
+ assertEquals("parent gremlin query should be equal the query for port group", expectedParent,
query.getQueryBuilder().getParentQuery().getQuery());
- assertEquals(
- "result type should be vnf",
- "vnf",
- query.getResultType());
+ assertEquals("result type should be vnf", "vnf", query.getResultType());
}
@@ -589,26 +430,14 @@ public class RelationshipGremlinQueryTest extends AAISetup {
*/
@Test
public void invalidNodeName() throws JAXBException, UnsupportedEncodingException, AAIException {
- String content =
- "{"
- + "\"related-to\" : \"l3-interface-ipv4-address-list\","
- + "\"relationship-data\" : [{"
- + "\"relationship-key\" : \"generic-vnf.vnf-id\","
- + "\"relationship-value\" : \"key1\""
- + "},{"
- + "\"relationship-key\" : \"lag-interface.interface-name\","
- + "\"relationship-value\" : \"key2\""
- + "},{"
- + "\"relationship-key\" : \"l-infeaterface.interface-name\","
- + "\"relationship-value\" : \"key3\""
- + "},{"
- + "\"relationship-key\" : \"vlan.vlan-interface\","
- + "\"relationship-value\" : \"key4\""
- + "},{"
+ String content = "{" + "\"related-to\" : \"l3-interface-ipv4-address-list\"," + "\"relationship-data\" : [{"
+ + "\"relationship-key\" : \"generic-vnf.vnf-id\"," + "\"relationship-value\" : \"key1\"" + "},{"
+ + "\"relationship-key\" : \"lag-interface.interface-name\"," + "\"relationship-value\" : \"key2\""
+ + "},{" + "\"relationship-key\" : \"l-infeaterface.interface-name\","
+ + "\"relationship-value\" : \"key3\"" + "},{" + "\"relationship-key\" : \"vlan.vlan-interface\","
+ + "\"relationship-value\" : \"key4\"" + "},{"
+ "\"relationship-key\" : \"l3-interface-ipv4-address-list.l3-interface-ipv4-address\","
- + "\"relationship-value\" : \"key5\""
- + "}]"
- + "}";
+ + "\"relationship-value\" : \"key5\"" + "}]" + "}";
thrown.expect(AAIException.class);
thrown.expectMessage(containsString("invalid object name"));
@@ -618,7 +447,8 @@ public class RelationshipGremlinQueryTest extends AAISetup {
unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true);
Object obj = context.newDynamicEntity("Relationship");
- DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue();
+ DynamicEntity entity = (DynamicEntity) unmarshaller
+ .unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue();
Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity);
dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj);
@@ -634,26 +464,13 @@ public class RelationshipGremlinQueryTest extends AAISetup {
*/
@Test
public void invalidPropertyName() throws JAXBException, UnsupportedEncodingException, AAIException {
- String content =
- "{"
- + "\"related-to\" : \"l3-interface-ipv4-address-list\","
- + "\"relationship-data\" : [{"
- + "\"relationship-key\" : \"generic-vnf.vnf-id\","
- + "\"relationship-value\" : \"key1\""
- + "},{"
- + "\"relationship-key\" : \"lag-interface.intfdaferface-name\","
- + "\"relationship-value\" : \"key2\""
- + "},{"
- + "\"relationship-key\" : \"l-interface.interface-name\","
- + "\"relationship-value\" : \"key3\""
- + "},{"
- + "\"relationship-key\" : \"vlan.vlan-interface\","
- + "\"relationship-value\" : \"key4\""
- + "},{"
- + "\"relationship-key\" : \"l3-interface-ipv4-address-list.l3-interface-ipv4-address\","
- + "\"relationship-value\" : \"key5\""
- + "}]"
- + "}";
+ String content = "{" + "\"related-to\" : \"l3-interface-ipv4-address-list\"," + "\"relationship-data\" : [{"
+ + "\"relationship-key\" : \"generic-vnf.vnf-id\"," + "\"relationship-value\" : \"key1\"" + "},{"
+ + "\"relationship-key\" : \"lag-interface.intfdaferface-name\"," + "\"relationship-value\" : \"key2\""
+ + "},{" + "\"relationship-key\" : \"l-interface.interface-name\"," + "\"relationship-value\" : \"key3\""
+ + "},{" + "\"relationship-key\" : \"vlan.vlan-interface\"," + "\"relationship-value\" : \"key4\""
+ + "},{" + "\"relationship-key\" : \"l3-interface-ipv4-address-list.l3-interface-ipv4-address\","
+ + "\"relationship-value\" : \"key5\"" + "}]" + "}";
thrown.expect(AAIException.class);
thrown.expectMessage(containsString("invalid property name"));
@@ -663,7 +480,8 @@ public class RelationshipGremlinQueryTest extends AAISetup {
unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true);
Object obj = context.newDynamicEntity("Relationship");
- DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue();
+ DynamicEntity entity = (DynamicEntity) unmarshaller
+ .unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue();
Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity);
dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj);
diff --git a/aai-core/src/test/java/org/onap/aai/parsers/query/RelationshipQueryTest.java b/aai-core/src/test/java/org/onap/aai/parsers/query/RelationshipQueryTest.java
index 71089c6b..b0f6b240 100644
--- a/aai-core/src/test/java/org/onap/aai/parsers/query/RelationshipQueryTest.java
+++ b/aai-core/src/test/java/org/onap/aai/parsers/query/RelationshipQueryTest.java
@@ -17,8 +17,18 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.parsers.query;
+import static org.junit.Assert.assertEquals;
+
+import java.io.StringReader;
+import java.io.UnsupportedEncodingException;
+
+import javax.xml.bind.JAXBException;
+import javax.xml.bind.Unmarshaller;
+import javax.xml.transform.stream.StreamSource;
+
import org.eclipse.persistence.dynamic.DynamicEntity;
import org.eclipse.persistence.jaxb.UnmarshallerProperties;
import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext;
@@ -28,35 +38,25 @@ import org.junit.Test;
import org.onap.aai.AAISetup;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.introspection.*;
-import org.onap.aai.setup.SchemaVersion;
-import org.onap.aai.serialization.engines.QueryStyle;
import org.onap.aai.serialization.engines.JanusGraphDBEngine;
+import org.onap.aai.serialization.engines.QueryStyle;
import org.onap.aai.serialization.engines.TransactionalGraphEngine;
-
-import javax.xml.bind.JAXBException;
-import javax.xml.bind.Unmarshaller;
-import javax.xml.transform.stream.StreamSource;
-import java.io.StringReader;
-import java.io.UnsupportedEncodingException;
-
-import static org.junit.Assert.assertEquals;
+import org.onap.aai.setup.SchemaVersion;
@Ignore
public class RelationshipQueryTest extends AAISetup {
-
private TransactionalGraphEngine dbEngine;
private SchemaVersion version;
private DynamicJAXBContext context = nodeIngestor.getContextForVersion(version);
@Before
- public void setup(){
+ public void setup() {
version = new SchemaVersion("v10");
- dbEngine =
- new JanusGraphDBEngine(QueryStyle.GREMLIN_TRAVERSAL,
- loaderFactory.createLoaderForVersion(ModelType.MOXY, version),
- false);
+ dbEngine = new JanusGraphDBEngine(QueryStyle.GREMLIN_TRAVERSAL,
+ loaderFactory.createLoaderForVersion(ModelType.MOXY, version), false);
}
+
/**
* Parent query.
*
@@ -67,14 +67,8 @@ public class RelationshipQueryTest extends AAISetup {
@Test
public void parentQuery() throws JAXBException, UnsupportedEncodingException, AAIException {
- String content =
- "{"
- + "\"related-to\" : \"pserver\","
- + "\"relationship-data\" : [{"
- + "\"relationship-key\" : \"pserver.hostname\","
- + "\"relationship-value\" : \"key1\""
- + "}]"
- + "}";
+ String content = "{" + "\"related-to\" : \"pserver\"," + "\"relationship-data\" : [{"
+ + "\"relationship-key\" : \"pserver.hostname\"," + "\"relationship-value\" : \"key1\"" + "}]" + "}";
Unmarshaller unmarshaller = context.createUnmarshaller();
unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json");
@@ -82,25 +76,17 @@ public class RelationshipQueryTest extends AAISetup {
unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true);
Object obj = context.newDynamicEntity("Relationship");
- DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue();
+ DynamicEntity entity = (DynamicEntity) unmarshaller
+ .unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue();
Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity);
QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj);
- String expected =
- ".has('hostname', 'key1').has('aai-node-type', 'pserver')";
- assertEquals(
- "gremlin query should be " + expected,
- expected,
- query.getQueryBuilder().getQuery());
- assertEquals(
- "parent gremlin query should be equal to normal query",
- expected,
+ String expected = ".has('hostname', 'key1').has('aai-node-type', 'pserver')";
+ assertEquals("gremlin query should be " + expected, expected, query.getQueryBuilder().getQuery());
+ assertEquals("parent gremlin query should be equal to normal query", expected,
query.getQueryBuilder().getParentQuery().getQuery());
- assertEquals(
- "result type should be pserver",
- "pserver",
- query.getResultType());
+ assertEquals("result type should be pserver", "pserver", query.getResultType());
}
@@ -114,17 +100,10 @@ public class RelationshipQueryTest extends AAISetup {
@Ignore
@Test
public void childQuery() throws JAXBException, UnsupportedEncodingException, AAIException {
- String content =
- "{"
- + "\"related-to\" : \"lag-interface\","
- + "\"relationship-data\" : [{"
- + "\"relationship-key\" : \"pserver.hostname\","
- + "\"relationship-value\" : \"key1\""
- + "}, {"
- + "\"relationship-key\" : \"lag-interface.interface-name\","
- + "\"relationship-value\" : \"key2\""
- + "}]"
- + "}";
+ String content = "{" + "\"related-to\" : \"lag-interface\"," + "\"relationship-data\" : [{"
+ + "\"relationship-key\" : \"pserver.hostname\"," + "\"relationship-value\" : \"key1\"" + "}, {"
+ + "\"relationship-key\" : \"lag-interface.interface-name\"," + "\"relationship-value\" : \"key2\""
+ + "}]" + "}";
Unmarshaller unmarshaller = context.createUnmarshaller();
unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json");
@@ -132,27 +111,19 @@ public class RelationshipQueryTest extends AAISetup {
unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true);
Object obj = context.newDynamicEntity("Relationship");
- DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue();
+ DynamicEntity entity = (DynamicEntity) unmarshaller
+ .unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue();
Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity);
QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj);
String expected =
".has('hostname', 'key1').has('aai-node-type', 'pserver').out('hasLAGInterface').has('aai-node-type', 'lag-interface')"
- + ".has('interface-name', 'key2')";
- String parentExpected =
- ".has('hostname', 'key1').has('aai-node-type', 'pserver')";
- assertEquals(
- "gremlin query should be for node",
- expected,
- query.getQueryBuilder().getQuery());
- assertEquals(
- "parent gremlin query should be for parent",
- parentExpected,
+ + ".has('interface-name', 'key2')";
+ String parentExpected = ".has('hostname', 'key1').has('aai-node-type', 'pserver')";
+ assertEquals("gremlin query should be for node", expected, query.getQueryBuilder().getQuery());
+ assertEquals("parent gremlin query should be for parent", parentExpected,
query.getQueryBuilder().getParentQuery().getQuery());
- assertEquals(
- "result type should be lag-interface",
- "lag-interface",
- query.getResultType());
+ assertEquals("result type should be lag-interface", "lag-interface", query.getResultType());
}
/**
@@ -165,20 +136,10 @@ public class RelationshipQueryTest extends AAISetup {
@Ignore
@Test
public void namingExceptions() throws JAXBException, UnsupportedEncodingException, AAIException {
- String content =
- "{"
- + "\"related-to\" : \"cvlan-tag\","
- + "\"relationship-data\" : [{"
- + "\"relationship-key\" : \"vce.vnf-id\","
- + "\"relationship-value\" : \"key1\""
- + "}, {"
- + "\"relationship-key\" : \"port-group.interface-id\","
- + "\"relationship-value\" : \"key2\""
- + "},{"
- + "\"relationship-key\" : \"cvlan-tag.cvlan-tag\","
- + "\"relationship-value\" : \"655\""
- + "}]"
- + "}";
+ String content = "{" + "\"related-to\" : \"cvlan-tag\"," + "\"relationship-data\" : [{"
+ + "\"relationship-key\" : \"vce.vnf-id\"," + "\"relationship-value\" : \"key1\"" + "}, {"
+ + "\"relationship-key\" : \"port-group.interface-id\"," + "\"relationship-value\" : \"key2\"" + "},{"
+ + "\"relationship-key\" : \"cvlan-tag.cvlan-tag\"," + "\"relationship-value\" : \"655\"" + "}]" + "}";
Unmarshaller unmarshaller = context.createUnmarshaller();
unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json");
@@ -186,30 +147,23 @@ public class RelationshipQueryTest extends AAISetup {
unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true);
Object obj = context.newDynamicEntity("Relationship");
- DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue();
+ DynamicEntity entity = (DynamicEntity) unmarshaller
+ .unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue();
Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity);
QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj);
String expected =
".has('vnf-id', 'key1').has('aai-node-type', 'vce').in('org.onap.relationships.inventory.BelongsTo')"
- + ".has('aai-node-type', 'port-group').has('interface-id', 'key2').in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'cvlan-tag')"
- + ".has('cvlan-tag', 655)";
+ + ".has('aai-node-type', 'port-group').has('interface-id', 'key2').in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'cvlan-tag')"
+ + ".has('cvlan-tag', 655)";
String expectedParent =
- ".has('vnf-id', 'key1').has('aai-node-type', 'vce').in('org.onap.relationships.inventory.BelongsTo')"
+ ".has('vnf-id', 'key1').has('aai-node-type', 'vce').in('org.onap.relationships.inventory.BelongsTo')"
+ ".has('aai-node-type', 'port-group').has('interface-id', 'key2')";
- assertEquals(
- "gremlin query should be " + expected,
- expected,
- query.getQueryBuilder().getQuery());
- assertEquals(
- "parent gremlin query should be equal the query for port group",
- expectedParent,
+ assertEquals("gremlin query should be " + expected, expected, query.getQueryBuilder().getQuery());
+ assertEquals("parent gremlin query should be equal the query for port group", expectedParent,
query.getQueryBuilder().getParentQuery().getQuery());
- assertEquals(
- "result type should be cvlan-tag",
- "cvlan-tag",
- query.getResultType());
+ assertEquals("result type should be cvlan-tag", "cvlan-tag", query.getResultType());
}
@@ -223,21 +177,11 @@ public class RelationshipQueryTest extends AAISetup {
@Ignore
@Test
public void doubleKey() throws JAXBException, UnsupportedEncodingException, AAIException {
- String content =
- "{"
- + "\"related-to\" : \"ctag-pool\","
- + "\"relationship-data\" : [{"
- + "\"relationship-key\" : \"complex.physical-location-id\","
- + "\"relationship-value\" : \"key1\""
- + " }, { "
- + "\"relationship-key\" : \"ctag-pool.target-pe\","
- + " \"relationship-value\" : \"key2\""
- + " },{"
- + "\"relationship-key\" : \"ctag-pool.availability-zone-name\","
- + "\"relationship-value\" : \"key3\""
- + "}]"
- + "}";
-
+ String content = "{" + "\"related-to\" : \"ctag-pool\"," + "\"relationship-data\" : [{"
+ + "\"relationship-key\" : \"complex.physical-location-id\"," + "\"relationship-value\" : \"key1\""
+ + " }, { " + "\"relationship-key\" : \"ctag-pool.target-pe\"," + " \"relationship-value\" : \"key2\""
+ + " },{" + "\"relationship-key\" : \"ctag-pool.availability-zone-name\","
+ + "\"relationship-value\" : \"key3\"" + "}]" + "}";
Unmarshaller unmarshaller = context.createUnmarshaller();
unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json");
@@ -245,31 +189,21 @@ public class RelationshipQueryTest extends AAISetup {
unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true);
Object obj = context.newDynamicEntity("Relationship");
- DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue();
+ DynamicEntity entity = (DynamicEntity) unmarshaller
+ .unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue();
Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity);
QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj);
- String expected =
- ".has('physical-location-id', 'key1').has('aai-node-type', 'complex')"
+ String expected = ".has('physical-location-id', 'key1').has('aai-node-type', 'complex')"
+ ".in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'ctag-pool')"
- + ".has('target-pe', 'key2')"
- + ".has('availability-zone-name', 'key3')";
- String expectedParent =
- ".has('physical-location-id', 'key1').has('aai-node-type', 'complex')";
-
- assertEquals(
- "gremlin query should be " + expected,
- expected,
- query.getQueryBuilder().getQuery());
- assertEquals(
- "parent gremlin query should be equal the query for port group",
- expectedParent,
+ + ".has('target-pe', 'key2')" + ".has('availability-zone-name', 'key3')";
+ String expectedParent = ".has('physical-location-id', 'key1').has('aai-node-type', 'complex')";
+
+ assertEquals("gremlin query should be " + expected, expected, query.getQueryBuilder().getQuery());
+ assertEquals("parent gremlin query should be equal the query for port group", expectedParent,
query.getQueryBuilder().getParentQuery().getQuery());
- assertEquals(
- "result type should be ctag-pool",
- "ctag-pool",
- query.getResultType());
+ assertEquals("result type should be ctag-pool", "ctag-pool", query.getResultType());
}
diff --git a/aai-core/src/test/java/org/onap/aai/parsers/query/UniqueRelationshipQueryTest.java b/aai-core/src/test/java/org/onap/aai/parsers/query/UniqueRelationshipQueryTest.java
index 319f0b88..68fc4376 100644
--- a/aai-core/src/test/java/org/onap/aai/parsers/query/UniqueRelationshipQueryTest.java
+++ b/aai-core/src/test/java/org/onap/aai/parsers/query/UniqueRelationshipQueryTest.java
@@ -17,8 +17,18 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.parsers.query;
+import static org.junit.Assert.assertEquals;
+
+import java.io.StringReader;
+import java.io.UnsupportedEncodingException;
+
+import javax.xml.bind.JAXBException;
+import javax.xml.bind.Unmarshaller;
+import javax.xml.transform.stream.StreamSource;
+
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__;
import org.apache.tinkerpop.gremlin.structure.Vertex;
@@ -32,28 +42,20 @@ import org.onap.aai.AAISetup;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.introspection.*;
import org.onap.aai.nodes.NodeIngestor;
-import org.onap.aai.setup.SchemaVersion;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.onap.aai.serialization.engines.QueryStyle;
import org.onap.aai.serialization.engines.JanusGraphDBEngine;
+import org.onap.aai.serialization.engines.QueryStyle;
import org.onap.aai.serialization.engines.TransactionalGraphEngine;
-
-import javax.xml.bind.JAXBException;
-import javax.xml.bind.Unmarshaller;
-import javax.xml.transform.stream.StreamSource;
-import java.io.StringReader;
-import java.io.UnsupportedEncodingException;
-
-import static org.junit.Assert.assertEquals;
+import org.onap.aai.setup.SchemaVersion;
+import org.springframework.beans.factory.annotation.Autowired;
@Ignore
public class UniqueRelationshipQueryTest extends AAISetup {
@Autowired
- private NodeIngestor ingestor ;
+ private NodeIngestor ingestor;
private TransactionalGraphEngine dbEngine;
- private SchemaVersion version ;
+ private SchemaVersion version;
private DynamicJAXBContext context = ingestor.getContextForVersion(version);
private Unmarshaller unmarshaller = null;
@@ -66,8 +68,7 @@ public class UniqueRelationshipQueryTest extends AAISetup {
public void setup() throws JAXBException {
version = new SchemaVersion("v10");
dbEngine = new JanusGraphDBEngine(QueryStyle.GREMLIN_UNIQUE,
- loaderFactory.createLoaderForVersion(ModelType.MOXY, version),
- false);
+ loaderFactory.createLoaderForVersion(ModelType.MOXY, version), false);
unmarshaller = context.createUnmarshaller();
unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json");
unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false);
@@ -84,24 +85,18 @@ public class UniqueRelationshipQueryTest extends AAISetup {
@Test
public void parentQuery() throws JAXBException, UnsupportedEncodingException, AAIException {
- String content =
- "{"
- + "\"related-to\" : \"pserver\","
- + "\"relationship-data\" : [{"
- + "\"relationship-key\" : \"pserver.hostname\","
- + "\"relationship-value\" : \"key1\""
- + "}]"
- + "}";
+ String content = "{" + "\"related-to\" : \"pserver\"," + "\"relationship-data\" : [{"
+ + "\"relationship-key\" : \"pserver.hostname\"," + "\"relationship-value\" : \"key1\"" + "}]" + "}";
Object obj = context.newDynamicEntity("Relationship");
- DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue();
+ DynamicEntity entity = (DynamicEntity) unmarshaller
+ .unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue();
Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity);
QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj);
String key = "pserver/key1";
- GraphTraversal<Vertex, Vertex> expected =
- __.<Vertex>start().has("aai-unique-key", key);
+ GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start().has("aai-unique-key", key);
String resultType = "pserver";
String containerType = "";
@@ -118,30 +113,22 @@ public class UniqueRelationshipQueryTest extends AAISetup {
*/
@Test
public void childQuery() throws JAXBException, UnsupportedEncodingException, AAIException {
- String content =
- "{"
- + "\"related-to\" : \"lag-interface\","
- + "\"relationship-data\" : [{"
- + "\"relationship-key\" : \"pserver.hostname\","
- + "\"relationship-value\" : \"key1\""
- + "}, {"
- + "\"relationship-key\" : \"lag-interface.interface-name\","
- + "\"relationship-value\" : \"key2\""
- + "}]"
- + "}";
+ String content = "{" + "\"related-to\" : \"lag-interface\"," + "\"relationship-data\" : [{"
+ + "\"relationship-key\" : \"pserver.hostname\"," + "\"relationship-value\" : \"key1\"" + "}, {"
+ + "\"relationship-key\" : \"lag-interface.interface-name\"," + "\"relationship-value\" : \"key2\""
+ + "}]" + "}";
Object obj = context.newDynamicEntity("Relationship");
- DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue();
+ DynamicEntity entity = (DynamicEntity) unmarshaller
+ .unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue();
Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity);
QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj);
String key = "pserver/key1/lag-interface/key2";
- GraphTraversal<Vertex, Vertex> expected =
- __.<Vertex>start().has("aai-unique-key", key);
- GraphTraversal<Vertex, Vertex> parentExpected =
- __.<Vertex>start().has("aai-unique-key", "pserver/key1");
+ GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start().has("aai-unique-key", key);
+ GraphTraversal<Vertex, Vertex> parentExpected = __.<Vertex>start().has("aai-unique-key", "pserver/key1");
String resultType = "lag-interface";
String containerType = "";
@@ -157,30 +144,20 @@ public class UniqueRelationshipQueryTest extends AAISetup {
*/
@Test
public void namingExceptions() throws JAXBException, UnsupportedEncodingException, AAIException {
- String content =
- "{"
- + "\"related-to\" : \"cvlan-tag\","
- + "\"relationship-data\" : [{"
- + "\"relationship-key\" : \"vce.vnf-id\","
- + "\"relationship-value\" : \"key1\""
- + "}, {"
- + "\"relationship-key\" : \"port-group.interface-id\","
- + "\"relationship-value\" : \"key2\""
- + "},{"
- + "\"relationship-key\" : \"cvlan-tag.cvlan-tag\","
- + "\"relationship-value\" : \"655\""
- + "}]"
- + "}";
+ String content = "{" + "\"related-to\" : \"cvlan-tag\"," + "\"relationship-data\" : [{"
+ + "\"relationship-key\" : \"vce.vnf-id\"," + "\"relationship-value\" : \"key1\"" + "}, {"
+ + "\"relationship-key\" : \"port-group.interface-id\"," + "\"relationship-value\" : \"key2\"" + "},{"
+ + "\"relationship-key\" : \"cvlan-tag.cvlan-tag\"," + "\"relationship-value\" : \"655\"" + "}]" + "}";
Object obj = context.newDynamicEntity("Relationship");
- DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue();
+ DynamicEntity entity = (DynamicEntity) unmarshaller
+ .unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue();
Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity);
QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj);
String key = "vce/key1/port-group/key2/cvlan-tag/655";
- GraphTraversal<Vertex, Vertex> expected =
- __.<Vertex>start().has("aai-unique-key", key);
+ GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start().has("aai-unique-key", key);
GraphTraversal<Vertex, Vertex> parentExpected =
__.<Vertex>start().has("aai-unique-key", "vce/key1/port-group/key2");
String resultType = "cvlan-tag";
@@ -199,28 +176,21 @@ public class UniqueRelationshipQueryTest extends AAISetup {
*/
@Test
public void doubleKey() throws JAXBException, UnsupportedEncodingException, AAIException {
- String content =
- "{"
- + "\"related-to\" : \"service-capability\","
- + "\"relationship-data\" : [{"
- + "\"relationship-key\" : \"service-capability.service-type\","
- + "\"relationship-value\" : \"key1\""
- + " }, { "
- + "\"relationship-key\" : \"service-capability.vnf-type\","
- + " \"relationship-value\" : \"key2\""
- + " }]"
- + "}";
+ String content = "{" + "\"related-to\" : \"service-capability\"," + "\"relationship-data\" : [{"
+ + "\"relationship-key\" : \"service-capability.service-type\"," + "\"relationship-value\" : \"key1\""
+ + " }, { " + "\"relationship-key\" : \"service-capability.vnf-type\","
+ + " \"relationship-value\" : \"key2\"" + " }]" + "}";
Object obj = context.newDynamicEntity("Relationship");
- DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue();
+ DynamicEntity entity = (DynamicEntity) unmarshaller
+ .unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue();
Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity);
QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj);
String key = "service-capability/key1/key2";
- GraphTraversal<Vertex, Vertex> expected =
- __.<Vertex>start().has("aai-unique-key", key);
+ GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start().has("aai-unique-key", key);
GraphTraversal<Vertex, Vertex> parentExpected =
__.<Vertex>start().has("aai-unique-key", "service-capability/key1/key2");
String resultType = "service-capability";
@@ -239,31 +209,24 @@ public class UniqueRelationshipQueryTest extends AAISetup {
*/
@Test
public void shortCircuit() throws JAXBException, UnsupportedEncodingException, AAIException {
- String content =
- "{"
- + "\"related-to\" : \"cvlan-tag\","
+ String content = "{" + "\"related-to\" : \"cvlan-tag\","
+ "\"related-link\" : \"http://mock-system-name.com:8443/aai/v6/network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags/cvlan-tag/655\","
- + "\"relationship-data\" : [{"
- + "\"relationship-key\" : \"vce.hostname\","
- + "\"relationship-value\" : \"key1\""
- + "}, {"
- + "\"relationship-key\" : \"port-group.interface-name\","
- + "\"relationship-value\" : \"key2\""
- + "},{"
- + "\"relationship-key\" : \"cvlan-tag.-name\","
- + "\"relationship-value\" : \"655\""
- + "}]"
- + "}";
+ + "\"relationship-data\" : [{" + "\"relationship-key\" : \"vce.hostname\","
+ + "\"relationship-value\" : \"key1\"" + "}, {" + "\"relationship-key\" : \"port-group.interface-name\","
+ + "\"relationship-value\" : \"key2\"" + "},{" + "\"relationship-key\" : \"cvlan-tag.-name\","
+ + "\"relationship-value\" : \"655\"" + "}]" + "}";
Object obj = context.newDynamicEntity("Relationship");
- DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue();
+ DynamicEntity entity = (DynamicEntity) unmarshaller
+ .unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue();
Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity);
QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj);
String key = "vce/key1/port-group/key2/cvlan-tag/655";
GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start().has("aai-unique-key", key);
- GraphTraversal<Vertex, Vertex> parentExpected = __.<Vertex>start().has("aai-unique-key", "vce/key1/port-group/key2");
+ GraphTraversal<Vertex, Vertex> parentExpected =
+ __.<Vertex>start().has("aai-unique-key", "vce/key1/port-group/key2");
String resultType = "cvlan-tag";
String containerType = "";
@@ -280,22 +243,12 @@ public class UniqueRelationshipQueryTest extends AAISetup {
* @param resultType the result type
* @param containerType the container type
*/
- public void testSet(QueryParser query, GraphTraversal<Vertex, Vertex> expected, GraphTraversal<Vertex, Vertex> parentExpected, String resultType, String containerType) {
- assertEquals(
- "gremlin query should be " + expected,
- expected,
- query.getQueryBuilder().getQuery());
- assertEquals(
- "parent gremlin query should be " + parentExpected,
- parentExpected,
+ public void testSet(QueryParser query, GraphTraversal<Vertex, Vertex> expected,
+ GraphTraversal<Vertex, Vertex> parentExpected, String resultType, String containerType) {
+ assertEquals("gremlin query should be " + expected, expected, query.getQueryBuilder().getQuery());
+ assertEquals("parent gremlin query should be " + parentExpected, parentExpected,
query.getParentQueryBuilder().getParentQuery());
- assertEquals(
- "result type should be " + resultType,
- resultType,
- query.getResultType());
- assertEquals(
- "container type should be " + containerType,
- containerType,
- query.getContainerType());
+ assertEquals("result type should be " + resultType, resultType, query.getResultType());
+ assertEquals("container type should be " + containerType, containerType, query.getContainerType());
}
}
diff --git a/aai-core/src/test/java/org/onap/aai/parsers/query/UniqueURIQueryTest.java b/aai-core/src/test/java/org/onap/aai/parsers/query/UniqueURIQueryTest.java
index 631574b4..1782c817 100644
--- a/aai-core/src/test/java/org/onap/aai/parsers/query/UniqueURIQueryTest.java
+++ b/aai-core/src/test/java/org/onap/aai/parsers/query/UniqueURIQueryTest.java
@@ -17,8 +17,16 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.parsers.query;
+import static org.junit.Assert.assertEquals;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URI;
+
+import javax.ws.rs.core.UriBuilder;
+
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__;
import org.apache.tinkerpop.gremlin.structure.Vertex;
@@ -27,23 +35,15 @@ import org.junit.Ignore;
import org.junit.Test;
import org.onap.aai.AAISetup;
import org.onap.aai.exceptions.AAIException;
-
import org.onap.aai.introspection.ModelType;
-import org.onap.aai.setup.SchemaVersion;
-import org.onap.aai.serialization.engines.QueryStyle;
import org.onap.aai.serialization.engines.JanusGraphDBEngine;
+import org.onap.aai.serialization.engines.QueryStyle;
import org.onap.aai.serialization.engines.TransactionalGraphEngine;
-
-import javax.ws.rs.core.UriBuilder;
-import java.io.UnsupportedEncodingException;
-import java.net.URI;
-
-import static org.junit.Assert.assertEquals;
+import org.onap.aai.setup.SchemaVersion;
@Ignore
public class UniqueURIQueryTest extends AAISetup {
-
private TransactionalGraphEngine dbEngine;
private SchemaVersion version;
private DynamicJAXBContext context = nodeIngestor.getContextForVersion(version);
@@ -58,8 +58,7 @@ public class UniqueURIQueryTest extends AAISetup {
public void parentQuery() throws UnsupportedEncodingException, AAIException {
version = new SchemaVersion("v10");
dbEngine = new JanusGraphDBEngine(QueryStyle.GREMLIN_UNIQUE,
- loaderFactory.createLoaderForVersion(ModelType.MOXY, version),
- false);
+ loaderFactory.createLoaderForVersion(ModelType.MOXY, version), false);
URI uri = UriBuilder.fromPath("cloud-infrastructure/complexes/complex/key1").build();
String key = "complex/key1";
QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri);
@@ -99,12 +98,13 @@ public class UniqueURIQueryTest extends AAISetup {
*/
@Test
public void childQuery() throws UnsupportedEncodingException, AAIException {
- URI uri = UriBuilder.fromPath("cloud-infrastructure/complexes/complex/key1/ctag-pools/ctag-pool/key2/key3").build();
+ URI uri = UriBuilder.fromPath("cloud-infrastructure/complexes/complex/key1/ctag-pools/ctag-pool/key2/key3")
+ .build();
QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri);
String parentKey = "complex/key1";
String key = parentKey + "/ctag-pool/key2/key3";
GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start().has("aai-unique-key", key);
- GraphTraversal<Vertex, Vertex> parentExpected = __.<Vertex>start().has("aai-unique-key", parentKey);
+ GraphTraversal<Vertex, Vertex> parentExpected = __.<Vertex>start().has("aai-unique-key", parentKey);
String parentResultType = "complex";
String resultType = "ctag-pool";
String containerType = "";
@@ -121,7 +121,8 @@ public class UniqueURIQueryTest extends AAISetup {
*/
@Test
public void namingExceptions() throws UnsupportedEncodingException, AAIException {
- URI uri = UriBuilder.fromPath("network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags/cvlan-tag/655").build();
+ URI uri = UriBuilder.fromPath("network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags/cvlan-tag/655")
+ .build();
QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri);
String parentKey = "vce/key1/port-group/key2";
String key = parentKey + "/cvlan-tag/655";
@@ -148,8 +149,9 @@ public class UniqueURIQueryTest extends AAISetup {
String parentKey = "vce/key1/port-group/key2";
URI uri = UriBuilder.fromPath(parentURI + "/cvlan-tags").build();
QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri);
- GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start().has("aai-unique-key", parentKey).in("org.onap.relationships.inventory.BelongsTo").has("aai-node-type", "cvlan-tag");
- GraphTraversal<Vertex, Vertex> parentExpected = __.<Vertex>start().has("aai-unique-key",parentKey);
+ GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start().has("aai-unique-key", parentKey)
+ .in("org.onap.relationships.inventory.BelongsTo").has("aai-node-type", "cvlan-tag");
+ GraphTraversal<Vertex, Vertex> parentExpected = __.<Vertex>start().has("aai-unique-key", parentKey);
String parentResultType = "port-group";
String resultType = "cvlan-tag";
String containerType = "cvlan-tags";
@@ -168,26 +170,14 @@ public class UniqueURIQueryTest extends AAISetup {
* @param resultType the result type
* @param containerType the container type
*/
- public void testSet(QueryParser query, GraphTraversal<Vertex, Vertex> expected, GraphTraversal<Vertex, Vertex> parentExpected, String parentResultType, String resultType, String containerType) {
- assertEquals(
- "gremlin query should be " + expected,
- expected,
- query.getQueryBuilder().getQuery());
- assertEquals(
- "parent gremlin query should be " + parentExpected,
- parentExpected,
+ public void testSet(QueryParser query, GraphTraversal<Vertex, Vertex> expected,
+ GraphTraversal<Vertex, Vertex> parentExpected, String parentResultType, String resultType,
+ String containerType) {
+ assertEquals("gremlin query should be " + expected, expected, query.getQueryBuilder().getQuery());
+ assertEquals("parent gremlin query should be " + parentExpected, parentExpected,
query.getQueryBuilder().getParentQuery().getQuery());
- assertEquals(
- "parent result type should be " + parentResultType,
- parentResultType,
- query.getParentResultType());
- assertEquals(
- "result type should be " + resultType,
- resultType,
- query.getResultType());
- assertEquals(
- "container type should be " + containerType,
- containerType,
- query.getContainerType());
+ assertEquals("parent result type should be " + parentResultType, parentResultType, query.getParentResultType());
+ assertEquals("result type should be " + resultType, resultType, query.getResultType());
+ assertEquals("container type should be " + containerType, containerType, query.getContainerType());
}
}
diff --git a/aai-core/src/test/java/org/onap/aai/parsers/relationship/RelationshipToURITest.java b/aai-core/src/test/java/org/onap/aai/parsers/relationship/RelationshipToURITest.java
index 42f1fd44..ea872d4e 100644
--- a/aai-core/src/test/java/org/onap/aai/parsers/relationship/RelationshipToURITest.java
+++ b/aai-core/src/test/java/org/onap/aai/parsers/relationship/RelationshipToURITest.java
@@ -17,8 +17,18 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.parsers.relationship;
+import static org.hamcrest.Matchers.hasProperty;
+import static org.hamcrest.Matchers.is;
+import static org.junit.Assert.assertEquals;
+
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.net.URI;
+import java.net.URISyntaxException;
+
import org.apache.commons.io.IOUtils;
import org.junit.Ignore;
import org.junit.Rule;
@@ -32,38 +42,28 @@ import org.onap.aai.parsers.exceptions.AmbiguousMapAAIException;
import org.onap.aai.setup.SchemaVersion;
import org.springframework.test.annotation.DirtiesContext;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.net.URI;
-import java.net.URISyntaxException;
-
-import static org.hamcrest.Matchers.hasProperty;
-import static org.hamcrest.Matchers.is;
-import static org.junit.Assert.assertEquals;
-
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
public class RelationshipToURITest extends AAISetup {
private final ModelType modelType = ModelType.MOXY;
private final SchemaVersion version10 = new SchemaVersion("v10");
-
-
+
@Rule
public ExpectedException thrown = ExpectedException.none();
-
+
@Test
public void onlyLink() throws AAIException, URISyntaxException, IOException {
Loader loader = loaderFactory.createLoaderForVersion(modelType, version10);
Introspector obj = loader.unmarshal("relationship", this.getJsonString("only-related-link.json"));
URI expected = new URI("/aai/v10/network/generic-vnfs/generic-vnf/key1");
-
+
RelationshipToURI parse = new RelationshipToURI(loader, obj);
-
+
URI uri = parse.getUri();
-
+
assertEquals("related-link is equal", expected.getPath(), uri.getPath());
}
-
+
@Test
public void onlyData() throws AAIException, URISyntaxException, IOException {
Loader loader = loaderFactory.createLoaderForVersion(modelType, version10);
@@ -71,71 +71,68 @@ public class RelationshipToURITest extends AAISetup {
URI expected = new URI("/network/generic-vnfs/generic-vnf/key1");
RelationshipToURI parse = new RelationshipToURI(loader, obj);
-
+
URI uri = parse.getUri();
-
+
assertEquals("related-link is equal", expected, uri);
}
-
+
@Test
public void failV10() throws AAIException, URISyntaxException, IOException {
Loader loader = loaderFactory.createLoaderForVersion(modelType, version10);
Introspector obj = loader.unmarshal("relationship", this.getJsonString("both-failv10-successv9.json"));
URI expected = new URI("/aai/v10/network/generic-vnfs/generic-vnf/key1");
-
+
thrown.expect(AAIIdentityMapParseException.class);
thrown.expect(hasProperty("code", is("AAI_3000")));
RelationshipToURI parse = new RelationshipToURI(loader, obj);
URI uri = parse.getUri();
-
+
}
-
+
@Test
public void failNothingToParse() throws AAIException, URISyntaxException, IOException {
Loader loader = loaderFactory.createLoaderForVersion(modelType, version10);
Introspector obj = loader.unmarshal("relationship", this.getJsonString("nothing-to-parse.json"));
URI expected = new URI("/aai/v10/network/generic-vnfs/generic-vnf/key1");
-
+
thrown.expect(AAIIdentityMapParseException.class);
thrown.expect(hasProperty("code", is("AAI_3000")));
RelationshipToURI parse = new RelationshipToURI(loader, obj);
-
+
URI uri = parse.getUri();
-
+
}
-
+
@Test
public void successV10() throws AAIException, URISyntaxException, IOException {
Loader loader = loaderFactory.createLoaderForVersion(modelType, version10);
Introspector obj = loader.unmarshal("relationship", this.getJsonString("both-successv10-failv9.json"));
URI expected = new URI("/aai/v10/network/generic-vnfs/generic-vnf/key1");
-
+
RelationshipToURI parse = new RelationshipToURI(loader, obj);
-
URI uri = parse.getUri();
-
+
assertEquals("related-link is equal", expected, uri);
-
}
-
+
@Test
public void ambiguousRelationship() throws AAIException, URISyntaxException, IOException {
Loader loader = loaderFactory.createLoaderForVersion(modelType, version10);
Introspector obj = loader.unmarshal("relationship", this.getJsonString("ambiguous-relationship.json"));
URI expected = new URI("/aai/v10/network/generic-vnfs/generic-vnf/key1");
-
+
thrown.expect(AmbiguousMapAAIException.class);
thrown.expect(hasProperty("code", is("AAI_6146")));
-
+
RelationshipToURI parse = new RelationshipToURI(loader, obj);
-
+
URI uri = parse.getUri();
-
+
assertEquals("related-link is equal", expected, uri);
-
}
@Ignore
@@ -144,54 +141,53 @@ public class RelationshipToURITest extends AAISetup {
Loader loader = loaderFactory.createLoaderForVersion(modelType, version10);
Introspector obj = loader.unmarshal("relationship", this.getJsonString("too-many-items-relationship.json"));
URI expected = new URI("/network/generic-vnfs/generic-vnf/key1/l-interfaces/l-interface/key2");
-
+
RelationshipToURI parse = new RelationshipToURI(loader, obj);
URI uri = parse.getUri();
-
+
assertEquals("related-link is equal", expected.toString(), uri.toString());
-
+
}
-
+
@Test
public void twoTopLevelNodes() throws AAIException, URISyntaxException, IOException {
Loader loader = loaderFactory.createLoaderForVersion(modelType, version10);
Introspector obj = loader.unmarshal("relationship", this.getJsonString("two-top-level-relationship.json"));
URI expected = new URI("/network/generic-vnfs/generic-vnf/key1/l-interfaces/l-interface/key2");
-
+
thrown.expect(AmbiguousMapAAIException.class);
thrown.expect(hasProperty("code", is("AAI_6146")));
-
+
RelationshipToURI parse = new RelationshipToURI(loader, obj);
-
+
URI uri = parse.getUri();
-
+
assertEquals("related-link is equal", expected, uri);
-
+
}
-
+
@Test
public void topLevelWithTwoKeys() throws AAIException, URISyntaxException, IOException {
Loader loader = loaderFactory.createLoaderForVersion(modelType, version10);
Introspector obj = loader.unmarshal("relationship", this.getJsonString("top-level-two-keys-relationship.json"));
- URI expected = new URI("/cloud-infrastructure/cloud-regions/cloud-region/key1/key2/availability-zones/availability-zone/key3");
-
+ URI expected = new URI(
+ "/cloud-infrastructure/cloud-regions/cloud-region/key1/key2/availability-zones/availability-zone/key3");
+
RelationshipToURI parse = new RelationshipToURI(loader, obj);
-
+
URI uri = parse.getUri();
-
+
assertEquals("related-link is equal", expected.toString(), uri.toString());
-
+
}
-
-
+
private String getJsonString(String filename) throws IOException {
-
-
+
FileInputStream is = new FileInputStream("src/test/resources/bundleconfig-local/etc/relationship/" + filename);
- String s = IOUtils.toString(is, "UTF-8");
+ String s = IOUtils.toString(is, "UTF-8");
IOUtils.closeQuietly(is);
-
+
return s;
}
}
diff --git a/aai-core/src/test/java/org/onap/aai/parsers/uri/URIParserTest.java b/aai-core/src/test/java/org/onap/aai/parsers/uri/URIParserTest.java
index aab124f3..111772d2 100644
--- a/aai-core/src/test/java/org/onap/aai/parsers/uri/URIParserTest.java
+++ b/aai-core/src/test/java/org/onap/aai/parsers/uri/URIParserTest.java
@@ -17,8 +17,19 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.parsers.uri;
+import static org.hamcrest.Matchers.hasProperty;
+import static org.hamcrest.Matchers.is;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URI;
+
+import javax.annotation.PostConstruct;
+import javax.ws.rs.core.UriBuilder;
+import javax.xml.bind.JAXBException;
+
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
@@ -28,22 +39,13 @@ import org.onap.aai.introspection.Loader;
import org.onap.aai.introspection.ModelType;
import org.onap.aai.setup.SchemaVersion;
-import javax.annotation.PostConstruct;
-import javax.ws.rs.core.UriBuilder;
-import javax.xml.bind.JAXBException;
-import java.io.UnsupportedEncodingException;
-import java.net.URI;
-
-import static org.hamcrest.Matchers.hasProperty;
-import static org.hamcrest.Matchers.is;
-
public class URIParserTest extends AAISetup {
- private Loader loader ;
+ private Loader loader;
@Rule
public ExpectedException thrown = ExpectedException.none();
-
+
/**
* Invalid path.
*
@@ -53,20 +55,25 @@ public class URIParserTest extends AAISetup {
* @throws UnsupportedEncodingException the unsupported encoding exception
*/
@PostConstruct
- public void createLoader(){
+ public void createLoader() {
loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, new SchemaVersion("v10"));
}
@Test
- public void invalidPath() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException {
- URI uri = UriBuilder.fromPath("/aai/" + loader.getVersion() + "/network/tenants/tenant/key1/vservers/vserver/key2/l-interfaces/l-interface/key3").build();
-
+ public void invalidPath()
+ throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException {
+ URI uri =
+ UriBuilder
+ .fromPath("/aai/" + loader.getVersion()
+ + "/network/tenants/tenant/key1/vservers/vserver/key2/l-interfaces/l-interface/key3")
+ .build();
+
thrown.expect(AAIException.class);
- thrown.expect(hasProperty("code", is("AAI_3001")));
-
+ thrown.expect(hasProperty("code", is("AAI_3001")));
+
new URIToDBKey(loader, uri);
}
-
+
/**
* Invalid path no name space.
*
@@ -76,15 +83,17 @@ public class URIParserTest extends AAISetup {
* @throws UnsupportedEncodingException the unsupported encoding exception
*/
@Test
- public void invalidPathNoNameSpace() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException {
- URI uri = UriBuilder.fromPath("/aai/" + loader.getVersion() + "/tenants/tenant/key1/vservers/vserver/key2/l-interfaces/l-interface/key3").build();
-
+ public void invalidPathNoNameSpace()
+ throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException {
+ URI uri = UriBuilder.fromPath("/aai/" + loader.getVersion()
+ + "/tenants/tenant/key1/vservers/vserver/key2/l-interfaces/l-interface/key3").build();
+
thrown.expect(AAIException.class);
- thrown.expect(hasProperty("code", is("AAI_3000")));
-
+ thrown.expect(hasProperty("code", is("AAI_3000")));
+
new URIToDBKey(loader, uri);
}
-
+
/**
* Invalid path partial.
*
@@ -94,12 +103,13 @@ public class URIParserTest extends AAISetup {
* @throws UnsupportedEncodingException the unsupported encoding exception
*/
@Test
- public void invalidPathPartial() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException {
+ public void invalidPathPartial()
+ throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException {
URI uri = UriBuilder.fromPath("vservers/vserver/key2/l-interfaces/l-interface/key3").build();
-
+
thrown.expect(AAIException.class);
thrown.expect(hasProperty("code", is("AAI_3000")));
-
+
new URIToDBKey(loader, uri);
}
}
diff --git a/aai-core/src/test/java/org/onap/aai/parsers/uri/URIToDBKeyTest.java b/aai-core/src/test/java/org/onap/aai/parsers/uri/URIToDBKeyTest.java
index 757fbc1f..f19e2681 100644
--- a/aai-core/src/test/java/org/onap/aai/parsers/uri/URIToDBKeyTest.java
+++ b/aai-core/src/test/java/org/onap/aai/parsers/uri/URIToDBKeyTest.java
@@ -17,35 +17,36 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.parsers.uri;
+import static org.hamcrest.Matchers.hasProperty;
+import static org.hamcrest.Matchers.is;
+import static org.junit.Assert.assertEquals;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URI;
+
+import javax.annotation.PostConstruct;
+import javax.ws.rs.core.UriBuilder;
+import javax.xml.bind.JAXBException;
+
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.onap.aai.AAISetup;
-import org.onap.aai.exceptions.AAIException;
-import org.onap.aai.parsers.exceptions.DoesNotStartWithValidNamespaceException;
import org.onap.aai.db.props.AAIProperties;
+import org.onap.aai.exceptions.AAIException;
import org.onap.aai.introspection.*;
-
-import javax.annotation.PostConstruct;
-import javax.ws.rs.core.UriBuilder;
-import javax.xml.bind.JAXBException;
-import java.io.UnsupportedEncodingException;
-import java.net.URI;
-
-import static org.hamcrest.Matchers.hasProperty;
-import static org.hamcrest.Matchers.is;
-import static org.junit.Assert.assertEquals;
-
+import org.onap.aai.parsers.exceptions.DoesNotStartWithValidNamespaceException;
public class URIToDBKeyTest extends AAISetup {
- private Loader loader ;
+ private Loader loader;
@Rule
public ExpectedException thrown = ExpectedException.none();
-
+
/**
* Uri.
*
@@ -55,22 +56,24 @@ public class URIToDBKeyTest extends AAISetup {
* @throws UnsupportedEncodingException the unsupported encoding exception
*/
@PostConstruct
- public void createLoader(){
+ public void createLoader() {
loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getDefaultVersion());
}
-
+
@Test
public void uri() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException {
- URI uri = UriBuilder.fromPath("/aai/" + loader.getVersion() + "/cloud-infrastructure/cloud-regions/cloud-region/cloudOwner-key/cloudRegion-key/tenants/tenant/tenantId-key/vservers/vserver/vserverId-key/l-interfaces/l-interface/key3").build();
+ URI uri = UriBuilder.fromPath("/aai/" + loader.getVersion()
+ + "/cloud-infrastructure/cloud-regions/cloud-region/cloudOwner-key/cloudRegion-key/tenants/tenant/tenantId-key/vservers/vserver/vserverId-key/l-interfaces/l-interface/key3")
+ .build();
URIToDBKey parse = new URIToDBKey(loader, uri);
Object result = parse.getResult();
String expected = "cloud-region/tenant/vserver/l-interface";
-
+
assertEquals("blah", expected, result);
-
+
}
-
+
/**
* Uri no version.
*
@@ -80,17 +83,19 @@ public class URIToDBKeyTest extends AAISetup {
* @throws UnsupportedEncodingException the unsupported encoding exception
*/
@Test
- public void uriNoVersion() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException {
- URI uri = UriBuilder.fromPath("/cloud-infrastructure/cloud-regions/cloud-region/cloudOwner-key/cloudRegion-key/tenants/tenant/tenantId-key/vservers/vserver/vserverId-key/l-interfaces/l-interface/key3").build();
+ public void uriNoVersion()
+ throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException {
+ URI uri = UriBuilder.fromPath(
+ "/cloud-infrastructure/cloud-regions/cloud-region/cloudOwner-key/cloudRegion-key/tenants/tenant/tenantId-key/vservers/vserver/vserverId-key/l-interfaces/l-interface/key3")
+ .build();
URIToDBKey parse = new URIToDBKey(loader, uri);
Object result = parse.getResult();
-
+
String expected = "cloud-region/tenant/vserver/l-interface";
-
+
assertEquals("blah", expected, result);
-
+
}
-
/**
* Bad URI.
@@ -102,14 +107,16 @@ public class URIToDBKeyTest extends AAISetup {
*/
@Test
public void badURI() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException {
- URI uri = UriBuilder.fromPath("/aai/" + loader.getVersion() + "/cloud-infrastructure/tenants/tenant/key1/vservers/vserver/key2/l-interadsfaces/l-interface/key3").build();
-
+ URI uri = UriBuilder.fromPath("/aai/" + loader.getVersion()
+ + "/cloud-infrastructure/tenants/tenant/key1/vservers/vserver/key2/l-interadsfaces/l-interface/key3")
+ .build();
+
thrown.expect(AAIException.class);
- thrown.expect(hasProperty("code", is("AAI_3001")));
-
+ thrown.expect(hasProperty("code", is("AAI_3001")));
+
new URIToDBKey(loader, uri);
}
-
+
/**
* NotValid namespace.
*
@@ -119,13 +126,15 @@ public class URIToDBKeyTest extends AAISetup {
* @throws UnsupportedEncodingException the unsupported encoding exception
*/
@Test
- public void notValidNamespace() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException {
- URI uri = UriBuilder.fromPath("/cloud-region/cloud-regions/cloud-region/cloudOwner-key/cloudRegion-key/tenants/tenant/tenantId-key/vservers/vserver/vserverId-key/l-interfaces/l-interface/key3").build();
+ public void notValidNamespace()
+ throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException {
+ URI uri = UriBuilder.fromPath(
+ "/cloud-region/cloud-regions/cloud-region/cloudOwner-key/cloudRegion-key/tenants/tenant/tenantId-key/vservers/vserver/vserverId-key/l-interfaces/l-interface/key3")
+ .build();
thrown.expect(DoesNotStartWithValidNamespaceException.class);
URIToDBKey parse = new URIToDBKey(loader, uri);
}
-
-
+
/**
* No valid tokens.
*
@@ -135,15 +144,16 @@ public class URIToDBKeyTest extends AAISetup {
* @throws UnsupportedEncodingException the unsupported encoding exception
*/
@Test
- public void noValidTokens() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException {
+ public void noValidTokens()
+ throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException {
URI uri = UriBuilder.fromPath("/aai/" + loader.getVersion() + "/cloud/blah/blah").build();
-
+
thrown.expect(AAIException.class);
- thrown.expect(hasProperty("code", is("AAI_3000")));
-
+ thrown.expect(hasProperty("code", is("AAI_3000")));
+
new URIToDBKey(loader, uri);
}
-
+
/**
* Starts with valid namespace.
*
@@ -153,17 +163,20 @@ public class URIToDBKeyTest extends AAISetup {
* @throws UnsupportedEncodingException the unsupported encoding exception
*/
@Test
- public void startsWithValidNamespace() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException {
- URI uri = UriBuilder.fromPath("/aai/" + loader.getVersion() + "/cloud-infrastructure/cloud-regions/cloud-region/cloudOwner-key/cloudRegion-key/tenants/tenant/tenantId-key/vservers/vserver/vserverId-key/l-interfaces/l-interface/key3").build();
-
+ public void startsWithValidNamespace()
+ throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException {
+ URI uri = UriBuilder.fromPath("/aai/" + loader.getVersion()
+ + "/cloud-infrastructure/cloud-regions/cloud-region/cloudOwner-key/cloudRegion-key/tenants/tenant/tenantId-key/vservers/vserver/vserverId-key/l-interfaces/l-interface/key3")
+ .build();
+
URIToDBKey parse = new URIToDBKey(loader, uri);
Object result = parse.getResult();
String expected = "cloud-region/tenant/vserver/l-interface";
-
+
assertEquals("blah", expected, result);
}
-
+
/**
* Naming exceptions.
*
@@ -173,14 +186,15 @@ public class URIToDBKeyTest extends AAISetup {
*/
@Test
public void namingExceptions() throws IllegalArgumentException, AAIException, UnsupportedEncodingException {
- URI uri = UriBuilder.fromPath("network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags/cvlan-tag/655").build();
+ URI uri = UriBuilder.fromPath("network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags/cvlan-tag/655")
+ .build();
URIToDBKey parse = new URIToDBKey(loader, uri);
Object result = parse.getResult();
String expected = "vce/port-group/cvlan-tag";
-
+
assertEquals("blah", expected, result);
-
+
}
-
+
}
diff --git a/aai-core/src/test/java/org/onap/aai/parsers/uri/URIToExtensionInformationTest.java b/aai-core/src/test/java/org/onap/aai/parsers/uri/URIToExtensionInformationTest.java
index cb365bb7..7d7d284d 100644
--- a/aai-core/src/test/java/org/onap/aai/parsers/uri/URIToExtensionInformationTest.java
+++ b/aai-core/src/test/java/org/onap/aai/parsers/uri/URIToExtensionInformationTest.java
@@ -17,8 +17,18 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.parsers.uri;
+import static org.junit.Assert.assertEquals;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URI;
+
+import javax.annotation.PostConstruct;
+import javax.ws.rs.core.UriBuilder;
+import javax.xml.bind.JAXBException;
+
import org.junit.Test;
import org.onap.aai.AAISetup;
import org.onap.aai.exceptions.AAIException;
@@ -27,19 +37,10 @@ import org.onap.aai.introspection.ModelType;
import org.onap.aai.restcore.HttpMethod;
import org.onap.aai.setup.SchemaVersion;
-import javax.annotation.PostConstruct;
-import javax.ws.rs.core.UriBuilder;
-import javax.xml.bind.JAXBException;
-import java.io.UnsupportedEncodingException;
-import java.net.URI;
-
-import static org.junit.Assert.assertEquals;
-
public class URIToExtensionInformationTest extends AAISetup {
-
- private Loader specificLoader ;
-
+ private Loader specificLoader;
+
/**
* Vservers V 7.
*
@@ -48,20 +49,25 @@ public class URIToExtensionInformationTest extends AAISetup {
* @throws IllegalArgumentException the illegal argument exception
* @throws UnsupportedEncodingException the unsupported encoding exception
*/
-
+
@PostConstruct
- public void createLoader(){
+ public void createLoader() {
specificLoader = loaderFactory.createLoaderForVersion(ModelType.MOXY, new SchemaVersion("v10"));
}
-
+
@Test
- public void vserversV8() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException {
- URI uri = UriBuilder.fromPath("/aai/" + specificLoader.getVersion() + "/cloud-infrastructure/cloud-regions/cloud-region/testOwner1/testRegion1/tenants/tenant/key1/vservers/vserver/key2").build();
+ public void vserversV8()
+ throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException {
+ URI uri = UriBuilder.fromPath("/aai/" + specificLoader.getVersion()
+ + "/cloud-infrastructure/cloud-regions/cloud-region/testOwner1/testRegion1/tenants/tenant/key1/vservers/vserver/key2")
+ .build();
URIToExtensionInformation parse = new URIToExtensionInformation(specificLoader, uri);
-
+
String namespace = "cloudInfrastructure";
- String preMethodName = "DynamicAddCloudInfrastructureCloudRegionsCloudRegionTenantsTenantVserversVserverPreProc";
- String postMethodName = "DynamicAddCloudInfrastructureCloudRegionsCloudRegionTenantsTenantVserversVserverPostProc";
+ String preMethodName =
+ "DynamicAddCloudInfrastructureCloudRegionsCloudRegionTenantsTenantVserversVserverPreProc";
+ String postMethodName =
+ "DynamicAddCloudInfrastructureCloudRegionsCloudRegionTenantsTenantVserversVserverPostProc";
String topLevel = "CloudRegion";
testSpec(parse, HttpMethod.PUT, namespace, preMethodName, postMethodName, topLevel);
@@ -77,12 +83,12 @@ public class URIToExtensionInformationTest extends AAISetup {
* @param postMethodName the post method name
* @param topLevel the top level
*/
- private void testSpec(URIToExtensionInformation info, HttpMethod httpMethod, String namespace, String preMethodName, String postMethodName, String topLevel) {
-
+ private void testSpec(URIToExtensionInformation info, HttpMethod httpMethod, String namespace, String preMethodName,
+ String postMethodName, String topLevel) {
String namespaceResult = info.getNamespace();
String methodNameResult = info.getMethodName(httpMethod, true);
-
+
assertEquals("namespace", namespace, namespaceResult);
assertEquals("preprocess method name", preMethodName, methodNameResult);
methodNameResult = info.getMethodName(httpMethod, false);
@@ -90,9 +96,8 @@ public class URIToExtensionInformationTest extends AAISetup {
assertEquals("postprocess method name", postMethodName, methodNameResult);
String topLevelResult = info.getTopObject();
-
+
assertEquals("topLevel", topLevel, topLevelResult);
}
-
-
+
}
diff --git a/aai-core/src/test/java/org/onap/aai/parsers/uri/URIToObjectTest.java b/aai-core/src/test/java/org/onap/aai/parsers/uri/URIToObjectTest.java
index 2bf1e35e..c28d5a7b 100644
--- a/aai-core/src/test/java/org/onap/aai/parsers/uri/URIToObjectTest.java
+++ b/aai-core/src/test/java/org/onap/aai/parsers/uri/URIToObjectTest.java
@@ -17,10 +17,20 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.parsers.uri;
-import org.onap.aai.schema.enums.ObjectMetadata;
-import org.onap.aai.setup.SchemaVersion;
+import static org.hamcrest.Matchers.hasProperty;
+import static org.hamcrest.Matchers.is;
+import static org.junit.Assert.assertEquals;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URI;
+import java.util.HashMap;
+
+import javax.annotation.PostConstruct;
+import javax.ws.rs.core.UriBuilder;
+import javax.xml.bind.JAXBException;
import org.junit.Ignore;
import org.junit.Rule;
@@ -31,25 +41,16 @@ import org.onap.aai.db.props.AAIProperties;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.introspection.*;
import org.onap.aai.introspection.exceptions.AAIUnknownObjectException;
+import org.onap.aai.schema.enums.ObjectMetadata;
+import org.onap.aai.setup.SchemaVersion;
import org.springframework.test.annotation.DirtiesContext;
-import javax.annotation.PostConstruct;
-import javax.ws.rs.core.UriBuilder;
-import javax.xml.bind.JAXBException;
-import java.io.UnsupportedEncodingException;
-import java.net.URI;
-import java.util.HashMap;
-
-import static org.hamcrest.Matchers.hasProperty;
-import static org.hamcrest.Matchers.is;
-import static org.junit.Assert.assertEquals;
-
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
public class URIToObjectTest extends AAISetup {
- private SchemaVersion version ;
+ private SchemaVersion version;
private SchemaVersion currentVersion;
- private Loader loader ;
+ private Loader loader;
@Rule
public ExpectedException thrown = ExpectedException.none();
@@ -63,7 +64,7 @@ public class URIToObjectTest extends AAISetup {
* @throws UnsupportedEncodingException the unsupported encoding exception
*/
@PostConstruct
- public void createLoader(){
+ public void createLoader() {
version = schemaVersions.getRelatedLinkVersion();
currentVersion = schemaVersions.getDefaultVersion();
loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getRelatedLinkVersion());
@@ -71,10 +72,13 @@ public class URIToObjectTest extends AAISetup {
@Test
public void uri() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException {
- URI uri = UriBuilder.fromPath("/aai/" + loader.getVersion() + "/cloud-infrastructure/cloud-regions/cloud-region/mycloudowner/mycloudregionid/tenants/tenant/key1/vservers/vserver/key2/l-interfaces/l-interface/key3").build();
+ URI uri = UriBuilder.fromPath("/aai/" + loader.getVersion()
+ + "/cloud-infrastructure/cloud-regions/cloud-region/mycloudowner/mycloudregionid/tenants/tenant/key1/vservers/vserver/key2/l-interfaces/l-interface/key3")
+ .build();
URIToObject parse = new URIToObject(loader, uri);
Introspector result = parse.getTopEntity();
- String expected = "{\"cloud-owner\":\"mycloudowner\",\"cloud-region-id\":\"mycloudregionid\",\"tenants\":{\"tenant\":[{\"tenant-id\":\"key1\",\"vservers\":{\"vserver\":[{\"vserver-id\":\"key2\",\"l-interfaces\":{\"l-interface\":[{\"interface-name\":\"key3\"}]}}]}}]}}";
+ String expected =
+ "{\"cloud-owner\":\"mycloudowner\",\"cloud-region-id\":\"mycloudregionid\",\"tenants\":{\"tenant\":[{\"tenant-id\":\"key1\",\"vservers\":{\"vserver\":[{\"vserver-id\":\"key2\",\"l-interfaces\":{\"l-interface\":[{\"interface-name\":\"key3\"}]}}]}}]}}";
String topEntity = "cloud-region";
String entity = "l-interface";
@@ -92,8 +96,11 @@ public class URIToObjectTest extends AAISetup {
* @throws AAIUnknownObjectException
*/
@Test
- public void uriNoVersion() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException, AAIUnknownObjectException {
- URI uri = UriBuilder.fromPath("/cloud-infrastructure/cloud-regions/cloud-region/mycloudowner/mycloudregionid/tenants/tenant/key1/vservers/vserver/key2/l-interfaces/l-interface/key3").build();
+ public void uriNoVersion() throws JAXBException, AAIException, IllegalArgumentException,
+ UnsupportedEncodingException, AAIUnknownObjectException {
+ URI uri = UriBuilder.fromPath(
+ "/cloud-infrastructure/cloud-regions/cloud-region/mycloudowner/mycloudregionid/tenants/tenant/key1/vservers/vserver/key2/l-interfaces/l-interface/key3")
+ .build();
HashMap<String, Introspector> relatedObjects = new HashMap<>();
Introspector tenantObj = this.loader.introspectorFromName("tenant");
tenantObj.setValue("tenant-id", "key1");
@@ -106,16 +113,15 @@ public class URIToObjectTest extends AAISetup {
URIToObject parse = new URIToObject(loader, uri, relatedObjects);
Introspector result = parse.getTopEntity();
- String expected = "{\"cloud-owner\":\"mycloudowner\",\"cloud-region-id\":\"mycloudregionid\",\"tenants\":{\"tenant\":[{\"tenant-id\":\"key1\",\"tenant-name\":\"name1\",\"vservers\":{\"vserver\":[{\"vserver-id\":\"key2\",\"vserver-name\":\"name2\",\"l-interfaces\":{\"l-interface\":[{\"interface-name\":\"key3\"}]}}]}}]}}";
+ String expected =
+ "{\"cloud-owner\":\"mycloudowner\",\"cloud-region-id\":\"mycloudregionid\",\"tenants\":{\"tenant\":[{\"tenant-id\":\"key1\",\"tenant-name\":\"name1\",\"vservers\":{\"vserver\":[{\"vserver-id\":\"key2\",\"vserver-name\":\"name2\",\"l-interfaces\":{\"l-interface\":[{\"interface-name\":\"key3\"}]}}]}}]}}";
String topEntity = "cloud-region";
String entity = "l-interface";
testSet(result.marshal(false), parse, expected, topEntity, entity, version);
-
}
-
/**
* Bad URI.
*
@@ -126,10 +132,12 @@ public class URIToObjectTest extends AAISetup {
*/
@Test
public void badURI() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException {
- URI uri = UriBuilder.fromPath("/aai/" + loader.getVersion() + "/cloud-infrastructure/cloud-regions/cloud-region/mycloudowner/mycloudregionid/tenants/tenant/key1/vservers/vserver/key2/l-interadsfaces/l-interface/key3").build();
+ URI uri = UriBuilder.fromPath("/aai/" + loader.getVersion()
+ + "/cloud-infrastructure/cloud-regions/cloud-region/mycloudowner/mycloudregionid/tenants/tenant/key1/vservers/vserver/key2/l-interadsfaces/l-interface/key3")
+ .build();
thrown.expect(AAIException.class);
- thrown.expect(hasProperty("code", is("AAI_3000")));
+ thrown.expect(hasProperty("code", is("AAI_3000")));
new URIToObject(loader, uri);
}
@@ -143,11 +151,15 @@ public class URIToObjectTest extends AAISetup {
* @throws UnsupportedEncodingException the unsupported encoding exception
*/
@Test
- public void startsWithValidNamespace() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException {
- URI uri = UriBuilder.fromPath("/cloud-infrastructure/cloud-regions/cloud-region/mycloudowner/mycloudregionid/tenants/tenant/key1/vservers/vserver/key2/l-interfaces/l-interface/key3").build();
+ public void startsWithValidNamespace()
+ throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException {
+ URI uri = UriBuilder.fromPath(
+ "/cloud-infrastructure/cloud-regions/cloud-region/mycloudowner/mycloudregionid/tenants/tenant/key1/vservers/vserver/key2/l-interfaces/l-interface/key3")
+ .build();
URIToObject parse = new URIToObject(loader, uri);
Introspector result = parse.getTopEntity();
- String expected = "{\"cloud-owner\":\"mycloudowner\",\"cloud-region-id\":\"mycloudregionid\",\"tenants\":{\"tenant\":[{\"tenant-id\":\"key1\",\"vservers\":{\"vserver\":[{\"vserver-id\":\"key2\",\"l-interfaces\":{\"l-interface\":[{\"interface-name\":\"key3\"}]}}]}}]}}";
+ String expected =
+ "{\"cloud-owner\":\"mycloudowner\",\"cloud-region-id\":\"mycloudregionid\",\"tenants\":{\"tenant\":[{\"tenant-id\":\"key1\",\"vservers\":{\"vserver\":[{\"vserver-id\":\"key2\",\"l-interfaces\":{\"l-interface\":[{\"interface-name\":\"key3\"}]}}]}}]}}";
String topEntity = "cloud-region";
String entity = "l-interface";
@@ -163,7 +175,8 @@ public class URIToObjectTest extends AAISetup {
* @throws UnsupportedEncodingException the unsupported encoding exception
*/
@Test
- public void singleTopLevel() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException {
+ public void singleTopLevel()
+ throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException {
URI uri = UriBuilder.fromPath("/network/generic-vnfs/generic-vnf/key1").build();
URIToObject parse = new URIToObject(loader, uri);
Introspector result = parse.getTopEntity();
@@ -186,11 +199,14 @@ public class URIToObjectTest extends AAISetup {
*/
@Test
@Ignore
- public void namingExceptions() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException {
- URI uri = UriBuilder.fromPath("network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags/cvlan-tag/655").build();
+ public void namingExceptions()
+ throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException {
+ URI uri = UriBuilder.fromPath("network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags/cvlan-tag/655")
+ .build();
URIToObject parse = new URIToObject(loader, uri);
Introspector result = parse.getTopEntity();
- String expected = "{\"vnf-id\":\"key1\",\"port-groups\":{\"port-group\":[{\"interface-id\":\"key2\",\"cvlan-tags\":{\"cvlan-tag-entry\":[{\"cvlan-tag\":655}]}}]}}";
+ String expected =
+ "{\"vnf-id\":\"key1\",\"port-groups\":{\"port-group\":[{\"interface-id\":\"key2\",\"cvlan-tags\":{\"cvlan-tag-entry\":[{\"cvlan-tag\":655}]}}]}}";
String topEntity = "vce";
String entity = "cvlan-tag";
@@ -208,18 +224,22 @@ public class URIToObjectTest extends AAISetup {
@Test
@Ignore
public void noListObject() throws IllegalArgumentException, UnsupportedEncodingException, AAIException {
- URI uri = UriBuilder.fromPath("/aai/v6/network/vpls-pes/vpls-pe/0e6189fd-9257-49b9-a3be-d7ba980ccfc9/lag-interfaces/lag-interface/8ae5aa76-d597-4382-b219-04f266fe5e37/l-interfaces/l-interface/9e141d03-467b-437f-b4eb-b3133ec1e205/l3-interface-ipv4-address-list/8f19f0ea-a81f-488e-8d5c-9b7b53696c11").build();
+ URI uri = UriBuilder.fromPath(
+ "/aai/v6/network/vpls-pes/vpls-pe/0e6189fd-9257-49b9-a3be-d7ba980ccfc9/lag-interfaces/lag-interface/8ae5aa76-d597-4382-b219-04f266fe5e37/l-interfaces/l-interface/9e141d03-467b-437f-b4eb-b3133ec1e205/l3-interface-ipv4-address-list/8f19f0ea-a81f-488e-8d5c-9b7b53696c11")
+ .build();
URIToObject parse = new URIToObject(loader, uri);
Introspector result = parse.getTopEntity();
String topEntity = "vpls-pe";
String entity = "l3-interface-ipv4-address-list";
- String expected = "{\"equipment-name\":\"0e6189fd-9257-49b9-a3be-d7ba980ccfc9\",\"lag-interfaces\":{\"lag-interface\":[{\"interface-name\":\"8ae5aa76-d597-4382-b219-04f266fe5e37\",\"l-interfaces\":{\"l-interface\":[{\"interface-name\":\"9e141d03-467b-437f-b4eb-b3133ec1e205\",\"l3-interface-ipv4-address-list\":[{\"l3-interface-ipv4-address\":\"8f19f0ea-a81f-488e-8d5c-9b7b53696c11\"}]}]}}]}}";
+ String expected =
+ "{\"equipment-name\":\"0e6189fd-9257-49b9-a3be-d7ba980ccfc9\",\"lag-interfaces\":{\"lag-interface\":[{\"interface-name\":\"8ae5aa76-d597-4382-b219-04f266fe5e37\",\"l-interfaces\":{\"l-interface\":[{\"interface-name\":\"9e141d03-467b-437f-b4eb-b3133ec1e205\",\"l3-interface-ipv4-address-list\":[{\"l3-interface-ipv4-address\":\"8f19f0ea-a81f-488e-8d5c-9b7b53696c11\"}]}]}}]}}";
testSet(result.marshal(false), parse, expected, topEntity, entity, version);
}
@Test
- public void relativePath() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException {
+ public void relativePath()
+ throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException {
URI uri = UriBuilder.fromPath("./l-interfaces/l-interface/key1").build();
URIToObject parse = new URIToObject(loader, uri);
Introspector result = parse.getEntity();
@@ -242,7 +262,8 @@ public class URIToObjectTest extends AAISetup {
* @param entity the entity
* @param version the version
*/
- public void testSet(String json, URIToObject parse, String expected, String topEntity, String entity, SchemaVersion version) {
+ public void testSet(String json, URIToObject parse, String expected, String topEntity, String entity,
+ SchemaVersion version) {
assertEquals("blah", expected, json);
assertEquals("top entity", topEntity, parse.getTopEntityName());
diff --git a/aai-core/src/test/java/org/onap/aai/parsers/uri/URIToRelationshipObjectTest.java b/aai-core/src/test/java/org/onap/aai/parsers/uri/URIToRelationshipObjectTest.java
index 4d0ec6ca..e983d007 100644
--- a/aai-core/src/test/java/org/onap/aai/parsers/uri/URIToRelationshipObjectTest.java
+++ b/aai-core/src/test/java/org/onap/aai/parsers/uri/URIToRelationshipObjectTest.java
@@ -17,8 +17,22 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.parsers.uri;
+import static org.hamcrest.Matchers.hasProperty;
+import static org.hamcrest.Matchers.is;
+import static org.junit.Assert.assertTrue;
+
+import java.io.UnsupportedEncodingException;
+import java.net.MalformedURLException;
+import java.net.URI;
+import java.net.URISyntaxException;
+
+import javax.annotation.PostConstruct;
+import javax.ws.rs.core.UriBuilder;
+import javax.xml.bind.JAXBException;
+
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
@@ -27,31 +41,20 @@ import org.onap.aai.exceptions.AAIException;
import org.onap.aai.introspection.*;
import org.onap.aai.setup.SchemaVersion;
-import javax.annotation.PostConstruct;
-import javax.ws.rs.core.UriBuilder;
-import javax.xml.bind.JAXBException;
-import java.io.UnsupportedEncodingException;
-import java.net.MalformedURLException;
-import java.net.URI;
-import java.net.URISyntaxException;
-
-import static org.hamcrest.Matchers.hasProperty;
-import static org.hamcrest.Matchers.is;
-import static org.junit.Assert.assertTrue;
-
public class URIToRelationshipObjectTest extends AAISetup {
- private SchemaVersion latest ;
+ private SchemaVersion latest;
private Loader loader;
@Rule
public ExpectedException thrown = ExpectedException.none();
@PostConstruct
- public void createLoader(){
+ public void createLoader() {
latest = schemaVersions.getDefaultVersion();
loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, latest);
}
+
/**
* Uri.
*
@@ -59,20 +62,24 @@ public class URIToRelationshipObjectTest extends AAISetup {
* @throws AAIException the AAI exception
* @throws IllegalArgumentException the illegal argument exception
* @throws UnsupportedEncodingException the unsupported encoding exception
- * @throws URISyntaxException
+ * @throws URISyntaxException
* @throws MalformedURLException the malformed URL exception
*/
@Test
- public void uri() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException, URISyntaxException {
-
- URI uri = UriBuilder.fromPath("/aai/" + loader.getVersion() + "/cloud-infrastructure/cloud-regions/cloud-region/mycloudregionowner/mycloudregionid/tenants/tenant/key1/vservers/vserver/key2/l-interfaces/l-interface/key3").build();
+ public void uri() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException,
+ URISyntaxException {
+
+ URI uri = UriBuilder.fromPath("/aai/" + loader.getVersion()
+ + "/cloud-infrastructure/cloud-regions/cloud-region/mycloudregionowner/mycloudregionid/tenants/tenant/key1/vservers/vserver/key2/l-interfaces/l-interface/key3")
+ .build();
URIToRelationshipObject parse = new URIToRelationshipObject(loader, uri);
Introspector result = parse.getResult();
- String expected = "\\{\"related-to\":\"l-interface\",\"related-link\":\"/aai/" + latest + "/cloud-infrastructure/cloud-regions/cloud-region/mycloudregionowner/mycloudregionid/tenants/tenant/key1/vservers/vserver/key2/l-interfaces/l-interface/key3\",\"relationship-data\":\\[\\{\"relationship-key\":\"cloud-region.cloud-owner\",\"relationship-value\":\"mycloudregionowner\"\\},\\{\"relationship-key\":\"cloud-region.cloud-region-id\",\"relationship-value\":\"mycloudregionid\"\\},\\{\"relationship-key\":\"tenant.tenant-id\",\"relationship-value\":\"key1\"\\},\\{\"relationship-key\":\"vserver.vserver-id\",\"relationship-value\":\"key2\"\\},\\{\"relationship-key\":\"l-interface.interface-name\",\"relationship-value\":\"key3\"\\}\\]\\}";
+ String expected = "\\{\"related-to\":\"l-interface\",\"related-link\":\"/aai/" + latest
+ + "/cloud-infrastructure/cloud-regions/cloud-region/mycloudregionowner/mycloudregionid/tenants/tenant/key1/vservers/vserver/key2/l-interfaces/l-interface/key3\",\"relationship-data\":\\[\\{\"relationship-key\":\"cloud-region.cloud-owner\",\"relationship-value\":\"mycloudregionowner\"\\},\\{\"relationship-key\":\"cloud-region.cloud-region-id\",\"relationship-value\":\"mycloudregionid\"\\},\\{\"relationship-key\":\"tenant.tenant-id\",\"relationship-value\":\"key1\"\\},\\{\"relationship-key\":\"vserver.vserver-id\",\"relationship-value\":\"key2\"\\},\\{\"relationship-key\":\"l-interface.interface-name\",\"relationship-value\":\"key3\"\\}\\]\\}";
assertTrue("blah", result.marshal(false).matches(expected));
-
+
}
-
+
/**
* Uri no version.
*
@@ -80,18 +87,21 @@ public class URIToRelationshipObjectTest extends AAISetup {
* @throws AAIException the AAI exception
* @throws IllegalArgumentException the illegal argument exception
* @throws UnsupportedEncodingException the unsupported encoding exception
- * @throws URISyntaxException
+ * @throws URISyntaxException
* @throws MalformedURLException the malformed URL exception
*/
@Test
- public void uriNoVersion() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException, URISyntaxException {
- URI uri = UriBuilder.fromPath("/cloud-infrastructure/cloud-regions/cloud-region/mycloudregionowner/mycloudregionid/tenants/tenant/key1/vservers/vserver/key2/l-interfaces/l-interface/key3").build();
+ public void uriNoVersion() throws JAXBException, AAIException, IllegalArgumentException,
+ UnsupportedEncodingException, URISyntaxException {
+ URI uri = UriBuilder.fromPath(
+ "/cloud-infrastructure/cloud-regions/cloud-region/mycloudregionowner/mycloudregionid/tenants/tenant/key1/vservers/vserver/key2/l-interfaces/l-interface/key3")
+ .build();
URIToRelationshipObject parse = new URIToRelationshipObject(loader, uri);
Introspector result = parse.getResult();
- String expected = "\\{\"related-to\":\"l-interface\",\"related-link\":\"/aai/" + latest + "/cloud-infrastructure/cloud-regions/cloud-region/mycloudregionowner/mycloudregionid/tenants/tenant/key1/vservers/vserver/key2/l-interfaces/l-interface/key3\",\"relationship-data\":\\[\\{\"relationship-key\":\"cloud-region.cloud-owner\",\"relationship-value\":\"mycloudregionowner\"\\},\\{\"relationship-key\":\"cloud-region.cloud-region-id\",\"relationship-value\":\"mycloudregionid\"\\},\\{\"relationship-key\":\"tenant.tenant-id\",\"relationship-value\":\"key1\"\\},\\{\"relationship-key\":\"vserver.vserver-id\",\"relationship-value\":\"key2\"\\},\\{\"relationship-key\":\"l-interface.interface-name\",\"relationship-value\":\"key3\"\\}\\]\\}";
+ String expected = "\\{\"related-to\":\"l-interface\",\"related-link\":\"/aai/" + latest
+ + "/cloud-infrastructure/cloud-regions/cloud-region/mycloudregionowner/mycloudregionid/tenants/tenant/key1/vservers/vserver/key2/l-interfaces/l-interface/key3\",\"relationship-data\":\\[\\{\"relationship-key\":\"cloud-region.cloud-owner\",\"relationship-value\":\"mycloudregionowner\"\\},\\{\"relationship-key\":\"cloud-region.cloud-region-id\",\"relationship-value\":\"mycloudregionid\"\\},\\{\"relationship-key\":\"tenant.tenant-id\",\"relationship-value\":\"key1\"\\},\\{\"relationship-key\":\"vserver.vserver-id\",\"relationship-value\":\"key2\"\\},\\{\"relationship-key\":\"l-interface.interface-name\",\"relationship-value\":\"key3\"\\}\\]\\}";
assertTrue("blah", result.marshal(false).matches(expected));
-
}
/**
@@ -101,19 +111,25 @@ public class URIToRelationshipObjectTest extends AAISetup {
* @throws AAIException the AAI exception
* @throws IllegalArgumentException the illegal argument exception
* @throws UnsupportedEncodingException the unsupported encoding exception
- * @throws URISyntaxException
+ * @throws URISyntaxException
* @throws MalformedURLException the malformed URL exception
*/
@Test
- public void doubleKeyRelationship() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException, URISyntaxException {
- URI uri = UriBuilder.fromPath("/aai/" + latest + "/cloud-infrastructure/complexes/complex/key1/ctag-pools/ctag-pool/key2/key3/").build();
+ public void doubleKeyRelationship() throws JAXBException, AAIException, IllegalArgumentException,
+ UnsupportedEncodingException, URISyntaxException {
+ URI uri =
+ UriBuilder
+ .fromPath("/aai/" + latest
+ + "/cloud-infrastructure/complexes/complex/key1/ctag-pools/ctag-pool/key2/key3/")
+ .build();
URIToRelationshipObject parse = new URIToRelationshipObject(loader, uri);
Introspector result = parse.getResult();
- String expected = "\\{\"related-to\":\"ctag-pool\",\"related-link\":\"/aai/" + latest + "/cloud-infrastructure/complexes/complex/key1/ctag-pools/ctag-pool/key2/key3\",\"relationship-data\":\\[\\{\"relationship-key\":\"complex.physical-location-id\",\"relationship-value\":\"key1\"\\},\\{\"relationship-key\":\"ctag-pool.target-pe\",\"relationship-value\":\"key2\"\\},\\{\"relationship-key\":\"ctag-pool.availability-zone-name\",\"relationship-value\":\"key3\"\\}\\]\\}";
+ String expected = "\\{\"related-to\":\"ctag-pool\",\"related-link\":\"/aai/" + latest
+ + "/cloud-infrastructure/complexes/complex/key1/ctag-pools/ctag-pool/key2/key3\",\"relationship-data\":\\[\\{\"relationship-key\":\"complex.physical-location-id\",\"relationship-value\":\"key1\"\\},\\{\"relationship-key\":\"ctag-pool.target-pe\",\"relationship-value\":\"key2\"\\},\\{\"relationship-key\":\"ctag-pool.availability-zone-name\",\"relationship-value\":\"key3\"\\}\\]\\}";
assertTrue("blah", result.marshal(false).matches(expected));
}
-
+
/**
* Uri with non string key.
*
@@ -121,17 +137,24 @@ public class URIToRelationshipObjectTest extends AAISetup {
* @throws AAIException the AAI exception
* @throws IllegalArgumentException the illegal argument exception
* @throws UnsupportedEncodingException the unsupported encoding exception
- * @throws URISyntaxException
+ * @throws URISyntaxException
* @throws MalformedURLException the malformed URL exception
*/
@Test
- public void uriWithNonStringKey() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException, URISyntaxException {
- URI uri = UriBuilder.fromPath("/aai/" + latest + "/network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags/cvlan-tag/144").build();
+ public void uriWithNonStringKey() throws JAXBException, AAIException, IllegalArgumentException,
+ UnsupportedEncodingException, URISyntaxException {
+ URI uri =
+ UriBuilder
+ .fromPath("/aai/" + latest
+ + "/network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags/cvlan-tag/144")
+ .build();
URIToRelationshipObject parse = new URIToRelationshipObject(loader, uri);
Introspector result = parse.getResult();
- String expected = "\\{\"related-to\":\"cvlan-tag\",\"related-link\":\"/aai/" + latest + "/network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags/cvlan-tag/144\",\"relationship-data\":\\[\\{\"relationship-key\":\"vce.vnf-id\",\"relationship-value\":\"key1\"\\},\\{\"relationship-key\":\"port-group.interface-id\",\"relationship-value\":\"key2\"\\},\\{\"relationship-key\":\"cvlan-tag.cvlan-tag\",\"relationship-value\":\"144\"\\}\\]\\}";
+ String expected = "\\{\"related-to\":\"cvlan-tag\",\"related-link\":\"/aai/" + latest
+ + "/network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags/cvlan-tag/144\",\"relationship-data\":\\[\\{\"relationship-key\":\"vce.vnf-id\",\"relationship-value\":\"key1\"\\},\\{\"relationship-key\":\"port-group.interface-id\",\"relationship-value\":\"key2\"\\},\\{\"relationship-key\":\"cvlan-tag.cvlan-tag\",\"relationship-value\":\"144\"\\}\\]\\}";
assertTrue("blah", result.marshal(false).matches(expected));
}
+
/**
* Bad URI.
*
@@ -142,12 +165,14 @@ public class URIToRelationshipObjectTest extends AAISetup {
*/
@Test
public void badURI() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException {
- URI uri = UriBuilder.fromPath("/aai/" + loader.getVersion() + "/cloud-infrastructure/cloud-regions/cloud-region/mycloudregionowner/mycloudregionid/tenants/tenant/key1/vservers/vserver/key2/l-interadsfaces/l-interface/key3").build();
-
+ URI uri = UriBuilder.fromPath("/aai/" + loader.getVersion()
+ + "/cloud-infrastructure/cloud-regions/cloud-region/mycloudregionowner/mycloudregionid/tenants/tenant/key1/vservers/vserver/key2/l-interadsfaces/l-interface/key3")
+ .build();
+
thrown.expect(AAIException.class);
- thrown.expect(hasProperty("code", is("AAI_3000")));
-
+ thrown.expect(hasProperty("code", is("AAI_3000")));
+
URIToObject parse = new URIToObject(loader, uri);
-
+
}
}
diff --git a/aai-core/src/test/java/org/onap/aai/query/builder/ExcludeQueryTest.java b/aai-core/src/test/java/org/onap/aai/query/builder/ExcludeQueryTest.java
index e466de49..2d6e2291 100644
--- a/aai-core/src/test/java/org/onap/aai/query/builder/ExcludeQueryTest.java
+++ b/aai-core/src/test/java/org/onap/aai/query/builder/ExcludeQueryTest.java
@@ -17,8 +17,14 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.query.builder;
+import static org.junit.Assert.assertTrue;
+
+import java.util.ArrayList;
+import java.util.List;
+
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.T;
@@ -28,68 +34,64 @@ import org.junit.Before;
import org.junit.Test;
import org.onap.aai.AAISetup;
import org.onap.aai.db.props.AAIProperties;
+import org.onap.aai.edges.enums.EdgeType;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.introspection.Loader;
import org.onap.aai.introspection.ModelType;
-/*
- * import org.onap.aai.serialization.db.EdgeRules;
-
-import org.onap.aai.serialization.db.EdgeType;
- */
import org.onap.aai.serialization.db.EdgeSerializer;
import org.springframework.beans.factory.annotation.Autowired;
-import org.onap.aai.edges.enums.EdgeType;
import org.springframework.test.annotation.DirtiesContext;
-import java.util.ArrayList;
-import java.util.List;
-
-import static org.junit.Assert.assertTrue;
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
public class ExcludeQueryTest extends AAISetup {
@Autowired
EdgeSerializer edgeSer;
-
+
private Loader loader;
-
+
@Before
public void setup() throws Exception {
loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getDefaultVersion());
}
-
- private QueryBuilder<Vertex> buildTestQuery(QueryBuilder<Vertex> qb) throws AAIException{
- return qb.createEdgeTraversal(EdgeType.TREE, "cloud-region","availability-zone").getVerticesExcludeByProperty("hypervisor-type", "hypervisortype-11").store("x").cap("x").unfold().dedup();
+
+ private QueryBuilder<Vertex> buildTestQuery(QueryBuilder<Vertex> qb) throws AAIException {
+ return qb.createEdgeTraversal(EdgeType.TREE, "cloud-region", "availability-zone")
+ .getVerticesExcludeByProperty("hypervisor-type", "hypervisortype-11").store("x").cap("x").unfold()
+ .dedup();
}
-
+
@Test
public void gremlinQueryExcludeTest() throws AAIException {
Graph graph = TinkerGraph.open();
GraphTraversalSource g = graph.traversal();
-
- 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 availibityzone11 = graph.addVertex(T.label, "availability-zone", T.id, "11", "aai-node-type", "availability-zone", "availability-zone-name", "az-name-11", "hypervisor-type", "hypervisortype-11");
-
-
- 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 availibityzone12 = graph.addVertex(T.label, "availability-zone", T.id, "12", "aai-node-type", "availability-zone", "availability-zone-name", "az-name-12", "hypervisor-type", "hypervisortype-12");
-
+
+ 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 availibityzone11 = graph.addVertex(T.label, "availability-zone", T.id, "11", "aai-node-type",
+ "availability-zone", "availability-zone-name", "az-name-11", "hypervisor-type", "hypervisortype-11");
+
+ 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 availibityzone12 = graph.addVertex(T.label, "availability-zone", T.id, "12", "aai-node-type",
+ "availability-zone", "availability-zone-name", "az-name-12", "hypervisor-type", "hypervisortype-12");
+
edgeSer.addTreeEdge(g, cloudregion, availibityzone);
edgeSer.addTreeEdge(g, cloudregion, availibityzone11);
-
-
-
+
edgeSer.addTreeEdge(g, cloudregion1, availibityzone1);
edgeSer.addTreeEdge(g, cloudregion1, availibityzone12);
-
+
List<Vertex> expected = new ArrayList<>();
expected.add(availibityzone);
-
- GremlinTraversal<Vertex> qb = new GremlinTraversal<>(loader, g, cloudregion);
+
+ GremlinTraversal<Vertex> qb = new GremlinTraversal<>(loader, g, cloudregion);
QueryBuilder q = buildTestQuery(qb);
-
+
List<Vertex> results = q.toList();
assertTrue("results match", expected.containsAll(results) && results.containsAll(expected));
@@ -99,39 +101,36 @@ public class ExcludeQueryTest extends AAISetup {
public void traversalQueryExcludeTest() throws AAIException {
Graph graph = TinkerGraph.open();
GraphTraversalSource g = graph.traversal();
-
-
- 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 availibityzone11 = graph.addVertex(T.label, "availability-zone", T.id, "11", "aai-node-type", "availability-zone", "availability-zone-name", "az-name-11", "hypervisor-type", "hypervisortype-11");
-
-
- 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 availibityzone12 = graph.addVertex(T.label, "availability-zone", T.id, "12", "aai-node-type", "availability-zone", "availability-zone-name", "az-name-12", "hypervisor-type", "hypervisortype-12");
-
+
+ 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 availibityzone11 = graph.addVertex(T.label, "availability-zone", T.id, "11", "aai-node-type",
+ "availability-zone", "availability-zone-name", "az-name-11", "hypervisor-type", "hypervisortype-11");
+
+ 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 availibityzone12 = graph.addVertex(T.label, "availability-zone", T.id, "12", "aai-node-type",
+ "availability-zone", "availability-zone-name", "az-name-12", "hypervisor-type", "hypervisortype-12");
+
edgeSer.addTreeEdge(g, cloudregion, availibityzone);
edgeSer.addTreeEdge(g, cloudregion, availibityzone11);
-
-
-
+
edgeSer.addTreeEdge(g, cloudregion1, availibityzone1);
edgeSer.addTreeEdge(g, cloudregion1, availibityzone12);
-
+
List<Vertex> expected = new ArrayList<>();
expected.add(availibityzone);
-
-
-
-
- TraversalQuery<Vertex> qb = new TraversalQuery<>(loader, g, cloudregion);
+
+ TraversalQuery<Vertex> qb = new TraversalQuery<>(loader, g, cloudregion);
QueryBuilder<Vertex> q = buildTestQuery(qb);
-
+
List<Vertex> results = q.toList();
assertTrue("results match", expected.containsAll(results) && results.containsAll(expected));
}
-
-
}
diff --git a/aai-core/src/test/java/org/onap/aai/query/builder/GremlinTraversalTest.java b/aai-core/src/test/java/org/onap/aai/query/builder/GremlinTraversalTest.java
index 7873fc1b..6be9dc05 100644
--- a/aai-core/src/test/java/org/onap/aai/query/builder/GremlinTraversalTest.java
+++ b/aai-core/src/test/java/org/onap/aai/query/builder/GremlinTraversalTest.java
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.query.builder;
import org.apache.tinkerpop.gremlin.process.traversal.Path;
@@ -25,30 +26,31 @@ import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.onap.aai.db.props.AAIProperties;
import org.onap.aai.introspection.ModelType;
+
public class GremlinTraversalTest extends QueryBuilderTestAbstraction {
-
+
@Override
protected QueryBuilder<Edge> getNewEdgeTraversalWithTestEdgeRules(Vertex v) {
loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getDefaultVersion());
return new GremlinTraversal<>(loader, g, v);
}
-
+
@Override
protected QueryBuilder<Edge> getNewEdgeTraversalWithTestEdgeRules() {
loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getDefaultVersion());
return new GremlinTraversal<>(loader, g);
}
-
+
@Override
protected QueryBuilder<Vertex> getNewVertexTraversalWithTestEdgeRules(Vertex v) {
return new GremlinTraversal<>(loader, g, v);
}
-
+
@Override
protected QueryBuilder<Vertex> getNewVertexTraversalWithTestEdgeRules() {
return new GremlinTraversal<>(loader, g);
}
-
+
@Override
protected QueryBuilder<Tree> getNewTreeTraversalWithTestEdgeRules(Vertex v) {
return new GremlinTraversal<>(loader, g, v);
@@ -69,5 +71,4 @@ public class GremlinTraversalTest extends QueryBuilderTestAbstraction {
return new GremlinTraversal<>(loader, g);
}
-
}
diff --git a/aai-core/src/test/java/org/onap/aai/query/builder/QueryBuilderTestAbstraction.java b/aai-core/src/test/java/org/onap/aai/query/builder/QueryBuilderTestAbstraction.java
index b26c0b05..0e527493 100644
--- a/aai-core/src/test/java/org/onap/aai/query/builder/QueryBuilderTestAbstraction.java
+++ b/aai-core/src/test/java/org/onap/aai/query/builder/QueryBuilderTestAbstraction.java
@@ -17,8 +17,18 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.query.builder;
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
+import static org.junit.Assert.*;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
import org.apache.tinkerpop.gremlin.process.traversal.Path;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.process.traversal.step.util.BulkSet;
@@ -32,14 +42,15 @@ import org.junit.runner.RunWith;
import org.onap.aai.config.ConfigConfiguration;
import org.onap.aai.config.IntrospectionConfig;
import org.onap.aai.config.SpringContextAware;
+import org.onap.aai.db.props.AAIProperties;
+import org.onap.aai.edges.EdgeIngestor;
+import org.onap.aai.edges.enums.EdgeType;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.introspection.Loader;
import org.onap.aai.introspection.LoaderFactory;
import org.onap.aai.introspection.ModelType;
import org.onap.aai.nodes.NodeIngestor;
import org.onap.aai.serialization.db.EdgeSerializer;
-import org.onap.aai.edges.EdgeIngestor;
-import org.onap.aai.edges.enums.EdgeType;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
import org.onap.aai.serialization.queryformats.QueryFormatTestHelper;
import org.onap.aai.setup.SchemaLocationsBean;
@@ -50,37 +61,18 @@ import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-import org.onap.aai.db.props.AAIProperties;
-
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
-import static org.junit.Assert.*;
@RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration(classes = {
- ConfigConfiguration.class,
- QueryTestsConfigTranslator.class,
- NodeIngestor.class,
- EdgeIngestor.class,
- EdgeSerializer.class,
- SpringContextAware.class,
- IntrospectionConfig.class
-})
+@ContextConfiguration(
+ classes = {ConfigConfiguration.class, QueryTestsConfigTranslator.class, NodeIngestor.class, EdgeIngestor.class,
+ EdgeSerializer.class, SpringContextAware.class, IntrospectionConfig.class})
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
-@TestPropertySource(properties = {
- "schema.translator.list = config",
- "schema.nodes.location=src/test/resources/onap/oxm",
- "schema.edges.location=src/test/resources/onap/dbedgerules"
-})
+@TestPropertySource(
+ properties = {"schema.translator.list = config", "schema.nodes.location=src/test/resources/onap/oxm",
+ "schema.edges.location=src/test/resources/onap/dbedgerules"})
public abstract class QueryBuilderTestAbstraction {
- protected Loader loader;
+ protected Loader loader;
protected static Graph graph;
protected GraphTraversalSource g;
@@ -93,12 +85,12 @@ public abstract class QueryBuilderTestAbstraction {
@Autowired
protected LoaderFactory loaderFactory;
-
@BeforeClass
public static void setup() throws Exception {
System.setProperty("AJSC_HOME", ".");
System.setProperty("BUNDLECONFIG_DIR", "src/test/resources/bundleconfig-local");
- QueryFormatTestHelper.setFinalStatic(AAIConstants.class.getField("AAI_HOME_ETC_OXM"), "src/test/resources/bundleconfig-local/etc/oxm/");
+ QueryFormatTestHelper.setFinalStatic(AAIConstants.class.getField("AAI_HOME_ETC_OXM"),
+ "src/test/resources/bundleconfig-local/etc/oxm/");
graph = JanusGraphFactory.build().set("storage.backend", "inmemory").open();
}
@@ -106,7 +98,6 @@ public abstract class QueryBuilderTestAbstraction {
public void configure() throws Exception {
loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getDefaultVersion());
-
g = graph.traversal();
}
@@ -123,8 +114,8 @@ public abstract class QueryBuilderTestAbstraction {
@Test
public void createEdgeGVnfToVnfcTraversal() throws AAIException {
- Vertex gvnf = g.addV("aai-node-type","generic-vnf","vnf-id","myvnf").next();
- Vertex vnfc = g.addV("aai-node-type","vnfc","vnfc-name","a-name").next();
+ Vertex gvnf = g.addV("aai-node-type", "generic-vnf", "vnf-id", "myvnf").next();
+ Vertex vnfc = g.addV("aai-node-type", "vnfc", "vnfc-name", "a-name").next();
testEdgeSer.addEdge(g, gvnf, vnfc, "uses");
QueryBuilder<Vertex> tQ = getNewVertexTraversalWithTestEdgeRules(gvnf);
@@ -132,14 +123,13 @@ public abstract class QueryBuilderTestAbstraction {
assertEquals(vnfc, tQ.next());
-
}
@Test
public void createEdgeLinterfaceToLogicalLinkTraversal() throws AAIException {
- Vertex lInterface = g.addV("aai-node-type","l-interface","interface-name","l-interface-a").next();
- Vertex logicalLink = g.addV("aai-node-type","logical-link","link-name","logical-link-a").next();
+ Vertex lInterface = g.addV("aai-node-type", "l-interface", "interface-name", "l-interface-a").next();
+ Vertex logicalLink = g.addV("aai-node-type", "logical-link", "link-name", "logical-link-a").next();
testEdgeSer.addEdge(g, lInterface, logicalLink, "sourceLInterface");
QueryBuilder<Vertex> tQ = getNewVertexTraversalWithTestEdgeRules(lInterface);
@@ -149,21 +139,22 @@ public abstract class QueryBuilderTestAbstraction {
assertEquals(logicalLink, next);
-
}
@SuppressWarnings("rawtypes")
@Test
public void createEdgeLinterfaceToLogicalLinkTraversal_tree() throws AAIException {
- Vertex lInterface = g.addV("aai-node-type","l-interface","interface-name","l-interface-a").next();
- Vertex logicalLink = g.addV("aai-node-type","logical-link","link-name","logical-link-a").next();
+ Vertex lInterface = g.addV("aai-node-type", "l-interface", "interface-name", "l-interface-a").next();
+ Vertex logicalLink = g.addV("aai-node-type", "logical-link", "link-name", "logical-link-a").next();
testEdgeSer.addEdge(g, lInterface, logicalLink, "sourceLInterface");
QueryBuilder<Tree> tQ = getNewTreeTraversalWithTestEdgeRules(lInterface).createEdgeTraversal(EdgeType.COUSIN,
- loader.introspectorFromName("l-interface" ), loader.introspectorFromName("logical-link")).tree();
+ loader.introspectorFromName("l-interface"), loader.introspectorFromName("logical-link")).tree();
- Vertex lInterfaceExpected = graph.traversal().V().has("aai-node-type","l-interface").has("interface-name","l-interface-a").next();
- Vertex logicalLinkExpected = graph.traversal().V().has("aai-node-type", "logical-link").has("link-name","logical-link-a").next();
+ Vertex lInterfaceExpected =
+ graph.traversal().V().has("aai-node-type", "l-interface").has("interface-name", "l-interface-a").next();
+ Vertex logicalLinkExpected =
+ graph.traversal().V().has("aai-node-type", "logical-link").has("link-name", "logical-link-a").next();
Tree tree = tQ.next();
assertTrue(tree.containsKey(lInterfaceExpected));
assertTrue(((Tree) tree.get(lInterfaceExpected)).containsKey(logicalLinkExpected));
@@ -172,15 +163,18 @@ public abstract class QueryBuilderTestAbstraction {
@SuppressWarnings("rawtypes")
@Test
public void createEdgeLinterfaceToLogicalLinkTraversal_Path() throws AAIException {
- Vertex pInterface = g.addV("aai-node-type","p-interface","interface-name","p-interface-a").next();
- Vertex lInterface = g.addV("aai-node-type","l-interface","interface-name","l-interface-a").next();
- Vertex logicalLink = g.addV("aai-node-type","logical-link","link-name","logical-link-a").next();
+ Vertex pInterface = g.addV("aai-node-type", "p-interface", "interface-name", "p-interface-a").next();
+ Vertex lInterface = g.addV("aai-node-type", "l-interface", "interface-name", "l-interface-a").next();
+ Vertex logicalLink = g.addV("aai-node-type", "logical-link", "link-name", "logical-link-a").next();
testEdgeSer.addEdge(g, lInterface, logicalLink);
testEdgeSer.addTreeEdge(g, pInterface, lInterface);
- QueryBuilder<Path> tQ = getNewPathTraversalWithTestEdgeRules(pInterface).createEdgeTraversal(EdgeType.TREE,
- loader.introspectorFromName("p-interface" ), loader.introspectorFromName("l-interface")).createEdgeTraversal(EdgeType.COUSIN,
- loader.introspectorFromName("l-interface" ), loader.introspectorFromName("logical-link")).path();
+ QueryBuilder<Path> tQ = getNewPathTraversalWithTestEdgeRules(pInterface)
+ .createEdgeTraversal(EdgeType.TREE, loader.introspectorFromName("p-interface"),
+ loader.introspectorFromName("l-interface"))
+ .createEdgeTraversal(EdgeType.COUSIN, loader.introspectorFromName("l-interface"),
+ loader.introspectorFromName("logical-link"))
+ .path();
Path path = tQ.next();
assertThat(path.objects(), contains(pInterface, lInterface, logicalLink));
@@ -189,8 +183,8 @@ public abstract class QueryBuilderTestAbstraction {
@SuppressWarnings("rawtypes")
@Test
public void parentVertexTest() throws AAIException {
- Vertex pInterface = g.addV("aai-node-type","p-interface","interface-name","p-interface-a").next();
- Vertex lInterface = g.addV("aai-node-type","l-interface","interface-name","l-interface-a").next();
+ Vertex pInterface = g.addV("aai-node-type", "p-interface", "interface-name", "p-interface-a").next();
+ Vertex lInterface = g.addV("aai-node-type", "l-interface", "interface-name", "l-interface-a").next();
testEdgeSer.addTreeEdge(g, pInterface, lInterface);
@@ -200,29 +194,28 @@ public abstract class QueryBuilderTestAbstraction {
assertThat(parent, is(pInterface));
}
-
@Test
public void createEdgeLinterfaceToLogicalLinkIntrospectorTraversal() throws AAIException {
- Vertex lInterface = g.addV("aai-node-type","l-interface","interface-name","l-interface-a").next();
- Vertex logicalLink = g.addV("aai-node-type","logical-link","link-name","logical-link-a").next();
+ Vertex lInterface = g.addV("aai-node-type", "l-interface", "interface-name", "l-interface-a").next();
+ Vertex logicalLink = g.addV("aai-node-type", "logical-link", "link-name", "logical-link-a").next();
testEdgeSer.addEdge(g, lInterface, logicalLink, "sourceLInterface");
QueryBuilder<Vertex> tQ = getNewVertexTraversalWithTestEdgeRules(lInterface);
- tQ.createEdgeTraversal(EdgeType.COUSIN, loader.introspectorFromName("l-interface"), loader.introspectorFromName("logical-link"));
+ tQ.createEdgeTraversal(EdgeType.COUSIN, loader.introspectorFromName("l-interface"),
+ loader.introspectorFromName("logical-link"));
Vertex next = tQ.next();
assertEquals(logicalLink, next);
-
}
@Test
public void createEdgeLinterfaceToLogicalLinkVertexToIntrospectorTraversal() throws AAIException {
- Vertex lInterface = g.addV("aai-node-type","l-interface","interface-name","l-interface-a").next();
- Vertex logicalLink = g.addV("aai-node-type","logical-link","link-name","logical-link-a").next();
+ Vertex lInterface = g.addV("aai-node-type", "l-interface", "interface-name", "l-interface-a").next();
+ Vertex logicalLink = g.addV("aai-node-type", "logical-link", "link-name", "logical-link-a").next();
testEdgeSer.addEdge(g, lInterface, logicalLink, "sourceLInterface");
QueryBuilder<Vertex> tQ = getNewVertexTraversalWithTestEdgeRules(lInterface);
@@ -232,14 +225,13 @@ public abstract class QueryBuilderTestAbstraction {
assertEquals(logicalLink, next);
-
}
@Test
public void edgeToVertexTraversalTest() throws AAIException {
- Vertex gvnf = g.addV("aai-node-type","generic-vnf","vnf-id","gvnf").next();
- Vertex vnfc1 = g.addV("aai-node-type","vnfc","vnfc-name","a-name").next();
+ Vertex gvnf = g.addV("aai-node-type", "generic-vnf", "vnf-id", "gvnf").next();
+ Vertex vnfc1 = g.addV("aai-node-type", "vnfc", "vnfc-name", "a-name").next();
testEdgeSer.addEdge(g, gvnf, vnfc1);
@@ -251,14 +243,13 @@ public abstract class QueryBuilderTestAbstraction {
assertEquals("Has 1 vertexes ", 1, list.size());
assertTrue("Has vertex on the default edge ", list.contains(vnfc1));
-
}
@Test
public void edgeToVertexTraversalSingleOutRuleTest() throws AAIException {
- Vertex vce = g.addV("aai-node-type","vce","vnf-id","vce").next();
- Vertex vnfc1 = g.addV("aai-node-type","vnfc","vnfc-name","a-name").next();
+ Vertex vce = g.addV("aai-node-type", "vce", "vnf-id", "vce").next();
+ Vertex vnfc1 = g.addV("aai-node-type", "vnfc", "vnfc-name", "a-name").next();
testEdgeSer.addEdge(g, vce, vnfc1);
@@ -276,14 +267,13 @@ public abstract class QueryBuilderTestAbstraction {
assertEquals("2 - Has 1 vertexes ", 1, list2.size());
assertTrue("2 - traversal results in vce ", list2.contains(vce));
-
}
@Test
public void edgeToVertexTraversalSingleInRuleTest() throws AAIException {
- Vertex vce = g.addV("aai-node-type","vce","vnf-id","vce").next();
- Vertex pserver = g.addV("aai-node-type","pserver","hostname","a-name").next();
+ Vertex vce = g.addV("aai-node-type", "vce", "vnf-id", "vce").next();
+ Vertex pserver = g.addV("aai-node-type", "pserver", "hostname", "a-name").next();
testEdgeSer.addEdge(g, vce, pserver);
@@ -295,15 +285,14 @@ public abstract class QueryBuilderTestAbstraction {
assertEquals("1 - Has 1 vertexes ", 1, list.size());
assertTrue("1 - traversal results in vnfc ", list.contains(pserver));
-
}
@Test
public void edgeToVertexMultiRuleTraversalTest() throws AAIException {
- Vertex gvnf = g.addV("aai-node-type","generic-vnf","vnf-id","gvnf").next();
- Vertex vnfc1 = g.addV("aai-node-type","vnfc","vnfc-name","a-name").next();
- Vertex vnfc2 = g.addV("aai-node-type","vnfc","vnfc-name","b-name").next();
+ Vertex gvnf = g.addV("aai-node-type", "generic-vnf", "vnf-id", "gvnf").next();
+ Vertex vnfc1 = g.addV("aai-node-type", "vnfc", "vnfc-name", "a-name").next();
+ Vertex vnfc2 = g.addV("aai-node-type", "vnfc", "vnfc-name", "b-name").next();
testEdgeSer.addEdge(g, gvnf, vnfc1);
testEdgeSer.addEdge(g, gvnf, vnfc2, "re-uses");
@@ -317,15 +306,14 @@ public abstract class QueryBuilderTestAbstraction {
assertTrue("Has vertex on the default edge ", list.contains(vnfc1));
assertTrue("Has vertex on the re-uses edge ", list.contains(vnfc2));
-
}
@Test
public void edgeToVertexMultiLabelTest() throws AAIException {
- Vertex gvnf = g.addV("aai-node-type","generic-vnf","vnf-id","gvnf").next();
- Vertex pserver = g.addV("aai-node-type","pserver","hostname","a-name").next();
- Vertex vnfc1 = g.addV("aai-node-type","vnfc","vnfc-name","a-name").next();
+ Vertex gvnf = g.addV("aai-node-type", "generic-vnf", "vnf-id", "gvnf").next();
+ Vertex pserver = g.addV("aai-node-type", "pserver", "hostname", "a-name").next();
+ Vertex vnfc1 = g.addV("aai-node-type", "vnfc", "vnfc-name", "a-name").next();
testEdgeSer.addEdge(g, gvnf, vnfc1);
testEdgeSer.addEdge(g, pserver, vnfc1);
@@ -338,30 +326,28 @@ public abstract class QueryBuilderTestAbstraction {
assertEquals("Has 1 vertexes ", 1, list.size());
assertTrue("Only returns the generic vnf vertex", list.contains(gvnf));
-
}
@Test
public void limitTraversalTest() throws AAIException {
- g.addV("aai-node-type","vnfc","vnfc-name","a-name").next();
- g.addV("aai-node-type","vnfc","vnfc-name","b-name").next();
+ g.addV("aai-node-type", "vnfc", "vnfc-name", "a-name").next();
+ g.addV("aai-node-type", "vnfc", "vnfc-name", "b-name").next();
QueryBuilder<Vertex> tQ = new GremlinTraversal<>(loader, g);
- tQ.getVerticesByProperty("aai-node-type","vnfc").limit(1);
+ tQ.getVerticesByProperty("aai-node-type", "vnfc").limit(1);
List<Vertex> list = tQ.toList();
assertEquals("Has 1 vertexes ", 1, list.size());
-
}
@Test
public void getVertexesByPropertiesTraversalTest() throws AAIException {
- g.addV("aai-node-type","vnfc","vnfc-name","a-name").next();
- g.addV("aai-node-type","vnfc","vnfc-name","b-name").next();
+ g.addV("aai-node-type", "vnfc", "vnfc-name", "a-name").next();
+ g.addV("aai-node-type", "vnfc", "vnfc-name", "b-name").next();
QueryBuilder<Vertex> tQ = new GremlinTraversal<>(loader, g);
tQ.getVerticesByProperty("vnfc-name", Arrays.asList("a-name", "b-name"));
@@ -370,30 +356,28 @@ public abstract class QueryBuilderTestAbstraction {
assertEquals("Has 2 vertexes ", 2, list.size());
-
}
@Test
public void getVertexesByIndexedPropertyTraversalTest() throws AAIException {
- g.addV("aai-node-type","vnfc","vnfc-name","a-name").next();
- g.addV("aai-node-type","vnfc","vnfc-name","b-name").next();
+ g.addV("aai-node-type", "vnfc", "vnfc-name", "a-name").next();
+ g.addV("aai-node-type", "vnfc", "vnfc-name", "b-name").next();
QueryBuilder<Vertex> tQ = new GremlinTraversal<>(loader, g);
- tQ.getVerticesByIndexedProperty("aai-node-type","vnfc");
+ tQ.getVerticesByIndexedProperty("aai-node-type", "vnfc");
List<Vertex> list = tQ.toList();
assertEquals("Has 2 vertexes ", 2, list.size());
-
}
@Test
public void dedupTraversalTest() throws AAIException {
- Vertex gvnf = g.addV("aai-node-type","generic-vnf","vnf-id","gvnf").next();
- Vertex pserver = g.addV("aai-node-type","pserver","hostname","a-name").next();
+ Vertex gvnf = g.addV("aai-node-type", "generic-vnf", "vnf-id", "gvnf").next();
+ Vertex pserver = g.addV("aai-node-type", "pserver", "hostname", "a-name").next();
testEdgeSer.addEdge(g, gvnf, pserver);
testEdgeSer.addEdge(g, gvnf, pserver, "generic-vnf-pserver-B");
@@ -406,14 +390,13 @@ public abstract class QueryBuilderTestAbstraction {
assertEquals("Has 2 vertexes ", 1, list.size());
assertTrue("result has pserver ", list.contains(pserver));
-
}
@Test
public void storeCapTraversalTest() throws AAIException {
- Vertex gvnf = g.addV("aai-node-type","generic-vnf","vnf-id","gvnf").next();
- Vertex pserver = g.addV("aai-node-type","pserver","hostname","a-name").next();
+ Vertex gvnf = g.addV("aai-node-type", "generic-vnf", "vnf-id", "gvnf").next();
+ Vertex pserver = g.addV("aai-node-type", "pserver", "hostname", "a-name").next();
testEdgeSer.addEdge(g, gvnf, pserver);
testEdgeSer.addEdge(g, gvnf, pserver, "generic-vnf-pserver-B");
@@ -424,16 +407,15 @@ public abstract class QueryBuilderTestAbstraction {
List<BulkSet<Vertex>> list = tQ.toList();
assertEquals("Has 2 vertexes ", 1, list.size());
- assertEquals("result has pserver ",pserver, list.get(0).iterator().next());
-
+ assertEquals("result has pserver ", pserver, list.get(0).iterator().next());
}
@Test
public void storeCapUnfoldTraversalTest() throws AAIException {
- Vertex gvnf = g.addV("aai-node-type","generic-vnf","vnf-id","gvnf").next();
- Vertex pserver = g.addV("aai-node-type","pserver","hostname","a-name").next();
+ Vertex gvnf = g.addV("aai-node-type", "generic-vnf", "vnf-id", "gvnf").next();
+ Vertex pserver = g.addV("aai-node-type", "pserver", "hostname", "a-name").next();
testEdgeSer.addEdge(g, gvnf, pserver);
testEdgeSer.addEdge(g, gvnf, pserver, "generic-vnf-pserver-B");
@@ -446,25 +428,24 @@ public abstract class QueryBuilderTestAbstraction {
assertEquals("Has 2 vertexes ", 2, list.size());
assertTrue("result has pserver ", list.contains(pserver));
-
}
@Test
public void nextAndHasNextTraversalTest() throws AAIException {
- Vertex v1 = g.addV("aai-node-type","vnfc","vnfc-name","a-name").next();
- Vertex v2 = g.addV("aai-node-type","vnfc","vnfc-name","b-name").next();
+ Vertex v1 = g.addV("aai-node-type", "vnfc", "vnfc-name", "a-name").next();
+ Vertex v2 = g.addV("aai-node-type", "vnfc", "vnfc-name", "b-name").next();
QueryBuilder<Vertex> tQ = new GremlinTraversal<>(loader, g);
- tQ.getVerticesByProperty("aai-node-type","vnfc");
+ tQ.getVerticesByProperty("aai-node-type", "vnfc");
List<Vertex> list = new ArrayList<>();
- assertTrue("Has next 1 ",tQ.hasNext());
+ assertTrue("Has next 1 ", tQ.hasNext());
list.add(tQ.next());
- assertTrue("Has next 2 ",tQ.hasNext());
+ assertTrue("Has next 2 ", tQ.hasNext());
list.add(tQ.next());
- assertFalse("Has next 3 ",tQ.hasNext());
+ assertFalse("Has next 3 ", tQ.hasNext());
assertTrue("Has all the vertexes", list.contains(v1) && list.remove(v2));
}
@@ -472,8 +453,8 @@ public abstract class QueryBuilderTestAbstraction {
@Test
public void edgeToVertexMultiRuleOutTraversalTest() throws AAIException {
- Vertex gvnf = g.addV("aai-node-type","generic-vnf","vnf-id","gvnf").next();
- Vertex pserver = g.addV("aai-node-type","pserver","hostname","a-name").next();
+ Vertex gvnf = g.addV("aai-node-type", "generic-vnf", "vnf-id", "gvnf").next();
+ Vertex pserver = g.addV("aai-node-type", "pserver", "hostname", "a-name").next();
testEdgeSer.addEdge(g, gvnf, pserver);
testEdgeSer.addEdge(g, gvnf, pserver, "generic-vnf-pserver-B");
@@ -486,14 +467,13 @@ public abstract class QueryBuilderTestAbstraction {
assertEquals("Has 2 vertexes ", 2, list.size());
assertTrue("result has pserver ", list.contains(pserver));
-
}
@Test
public void edgeToVertexMultiRuleInTraversalTest() throws AAIException {
- Vertex gvnf = g.addV("aai-node-type","generic-vnf","vnf-id","gvnf").next();
- Vertex complex = g.addV("aai-node-type","complex","physical-location-id","a-name").next();
+ Vertex gvnf = g.addV("aai-node-type", "generic-vnf", "vnf-id", "gvnf").next();
+ Vertex complex = g.addV("aai-node-type", "complex", "physical-location-id", "a-name").next();
testEdgeSer.addEdge(g, gvnf, complex);
testEdgeSer.addEdge(g, gvnf, complex, "complex-generic-vnf-B");
@@ -506,14 +486,13 @@ public abstract class QueryBuilderTestAbstraction {
assertEquals("Has 2 vertexes ", 2, list.size());
assertTrue("result has pserver ", list.contains(complex));
-
}
@Test
public void edgeTraversalSingleInRuleTest() throws AAIException {
- Vertex vce = g.addV("aai-node-type","vce","vnf-id","vce").next();
- Vertex pserver = g.addV("aai-node-type","pserver","hostname","a-name").next();
+ Vertex vce = g.addV("aai-node-type", "vce", "vnf-id", "vce").next();
+ Vertex pserver = g.addV("aai-node-type", "pserver", "hostname", "a-name").next();
Edge e = testEdgeSer.addEdge(g, vce, pserver);
@@ -525,14 +504,13 @@ public abstract class QueryBuilderTestAbstraction {
assertEquals("1 - Has 1 edge ", 1, list.size());
assertTrue("1 - traversal results in edge ", list.contains(e));
-
}
@Test
public void edgeTraversalSingleOutRuleTest() throws AAIException {
- Vertex vce = g.addV("aai-node-type","vce","vnf-id","vce").next();
- Vertex vnfc1 = g.addV("aai-node-type","vnfc","vnfc-name","a-name").next();
+ Vertex vce = g.addV("aai-node-type", "vce", "vnf-id", "vce").next();
+ Vertex vnfc1 = g.addV("aai-node-type", "vnfc", "vnfc-name", "a-name").next();
Edge e = testEdgeSer.addEdge(g, vce, vnfc1);
@@ -544,14 +522,13 @@ public abstract class QueryBuilderTestAbstraction {
assertEquals("1 - Has 1 edge ", 1, list1.size());
assertTrue("1 - traversal results in edge ", list1.contains(e));
-
}
@Test
public void edgeTraversalMultiRuleOutTraversalTest() throws AAIException {
- Vertex gvnf = g.addV("aai-node-type","generic-vnf","vnf-id","gvnf").next();
- Vertex pserver = g.addV("aai-node-type","pserver","hostname","a-name").next();
+ Vertex gvnf = g.addV("aai-node-type", "generic-vnf", "vnf-id", "gvnf").next();
+ Vertex pserver = g.addV("aai-node-type", "pserver", "hostname", "a-name").next();
Edge e1 = testEdgeSer.addEdge(g, gvnf, pserver);
Edge e2 = testEdgeSer.addEdge(g, gvnf, pserver, "generic-vnf-pserver-B");
@@ -565,14 +542,13 @@ public abstract class QueryBuilderTestAbstraction {
assertTrue("result has default edge ", list.contains(e1));
assertTrue("result has other edge ", list.contains(e2));
-
}
@Test
public void edgeTraversalMultiRuleInTraversalTest() throws AAIException {
- Vertex gvnf = g.addV("aai-node-type","generic-vnf","vnf-id","gvnf").next();
- Vertex complex = g.addV("aai-node-type","complex","physical-location-id","a-name").next();
+ Vertex gvnf = g.addV("aai-node-type", "generic-vnf", "vnf-id", "gvnf").next();
+ Vertex complex = g.addV("aai-node-type", "complex", "physical-location-id", "a-name").next();
Edge e1 = testEdgeSer.addEdge(g, gvnf, complex);
Edge e2 = testEdgeSer.addEdge(g, gvnf, complex, "complex-generic-vnf-B");
@@ -586,15 +562,14 @@ public abstract class QueryBuilderTestAbstraction {
assertTrue("result has default edge ", list.contains(e1));
assertTrue("result has other edge ", list.contains(e2));
-
}
@Test
public void edgeTraversalMultiRuleTraversalTest() throws AAIException {
- Vertex gvnf = g.addV("aai-node-type","generic-vnf","vnf-id","gvnf").next();
- Vertex vnfc1 = g.addV("aai-node-type","vnfc","vnfc-name","a-name").next();
- Vertex vnfc2 = g.addV("aai-node-type","vnfc","vnfc-name","b-name").next();
+ Vertex gvnf = g.addV("aai-node-type", "generic-vnf", "vnf-id", "gvnf").next();
+ Vertex vnfc1 = g.addV("aai-node-type", "vnfc", "vnfc-name", "a-name").next();
+ Vertex vnfc2 = g.addV("aai-node-type", "vnfc", "vnfc-name", "b-name").next();
Edge e1 = testEdgeSer.addEdge(g, gvnf, vnfc1);
Edge e2 = testEdgeSer.addEdge(g, gvnf, vnfc2, "re-uses");
@@ -608,15 +583,14 @@ public abstract class QueryBuilderTestAbstraction {
assertTrue("result has default edge ", list.contains(e1));
assertTrue("result has other edge ", list.contains(e2));
-
}
@Ignore("This test is failing for TraversalQueryTest and Optimized but it passes for GremlinQueryTest")
- @Test (expected = NoEdgeRuleFoundException.class)
+ @Test(expected = NoEdgeRuleFoundException.class)
public void getEdgesBetweenWithLabelsEmptyListTest() throws AAIException {
- Vertex gvnf = g.addV("aai-node-type","generic-vnf","vnf-id","gvnf").next();
- Vertex pserver = g.addV("aai-node-type","pserver","hostname","a-name").next();
+ Vertex gvnf = g.addV("aai-node-type", "generic-vnf", "vnf-id", "gvnf").next();
+ Vertex pserver = g.addV("aai-node-type", "pserver", "hostname", "a-name").next();
testEdgeSer.addEdge(g, gvnf, pserver);
testEdgeSer.addEdge(g, gvnf, pserver, "generic-vnf-pserver-B");
@@ -629,14 +603,15 @@ public abstract class QueryBuilderTestAbstraction {
@Test
public void getEdgesBetweenWithLabelsSingleItemTest() throws AAIException {
- Vertex gvnf = g.addV("aai-node-type","generic-vnf","vnf-id","gvnf").next();
- Vertex pserver = g.addV("aai-node-type","pserver","hostname","a-name").next();
+ Vertex gvnf = g.addV("aai-node-type", "generic-vnf", "vnf-id", "gvnf").next();
+ Vertex pserver = g.addV("aai-node-type", "pserver", "hostname", "a-name").next();
Edge e1 = testEdgeSer.addEdge(g, gvnf, pserver);
Edge e2 = testEdgeSer.addEdge(g, gvnf, pserver, "generic-vnf-pserver-B");
QueryBuilder<Edge> tQ = getNewEdgeTraversalWithTestEdgeRules(gvnf);
- tQ.getEdgesBetweenWithLabels(EdgeType.COUSIN, "generic-vnf", "pserver", Collections.singletonList("generic-vnf-pserver-B"));
+ tQ.getEdgesBetweenWithLabels(EdgeType.COUSIN, "generic-vnf", "pserver",
+ Collections.singletonList("generic-vnf-pserver-B"));
List<Edge> list = tQ.toList();
@@ -649,14 +624,15 @@ public abstract class QueryBuilderTestAbstraction {
@Test
public void getEdgesBetweenWithLabelsMultipleItemTest() throws AAIException {
- Vertex gvnf = g.addV("aai-node-type","generic-vnf","vnf-id","gvnf").next();
- Vertex pserver = g.addV("aai-node-type","pserver","hostname","a-name").next();
+ Vertex gvnf = g.addV("aai-node-type", "generic-vnf", "vnf-id", "gvnf").next();
+ Vertex pserver = g.addV("aai-node-type", "pserver", "hostname", "a-name").next();
Edge e1 = testEdgeSer.addEdge(g, gvnf, pserver);
Edge e2 = testEdgeSer.addEdge(g, gvnf, pserver, "generic-vnf-pserver-B");
QueryBuilder<Edge> tQ = getNewEdgeTraversalWithTestEdgeRules(gvnf);
- tQ.getEdgesBetweenWithLabels(EdgeType.COUSIN, "generic-vnf", "pserver", Arrays.asList("generic-vnf-pserver-B", "generic-vnf-pserver-A"));
+ tQ.getEdgesBetweenWithLabels(EdgeType.COUSIN, "generic-vnf", "pserver",
+ Arrays.asList("generic-vnf-pserver-B", "generic-vnf-pserver-A"));
List<Edge> list = tQ.toList();
@@ -667,7 +643,7 @@ public abstract class QueryBuilderTestAbstraction {
}
@Ignore("This test is failing for TraversalQueryTest and Optimized but it passes for GremlinQueryTest")
- @Test (expected = NoEdgeRuleFoundException.class)
+ @Test(expected = NoEdgeRuleFoundException.class)
public void createEdgeTraversalWithLabelsEmptyListTest() throws AAIException {
Vertex gvnf = getVertex();
@@ -677,12 +653,11 @@ public abstract class QueryBuilderTestAbstraction {
tQ.toList();
-
}
private Vertex getVertex() throws AAIException {
- Vertex gvnf = g.addV("aai-node-type","generic-vnf","vnf-id","gvnf").next();
- Vertex pserver = g.addV("aai-node-type","pserver","hostname","a-name").next();
+ Vertex gvnf = g.addV("aai-node-type", "generic-vnf", "vnf-id", "gvnf").next();
+ Vertex pserver = g.addV("aai-node-type", "pserver", "hostname", "a-name").next();
testEdgeSer.addEdge(g, gvnf, pserver);
testEdgeSer.addEdge(g, gvnf, pserver, "generic-vnf-pserver-B");
@@ -692,14 +667,15 @@ public abstract class QueryBuilderTestAbstraction {
@Test
public void createEdgeTraversalWithLabelsSingleItemTest() throws AAIException {
- Vertex gvnf = g.addV("aai-node-type","generic-vnf","vnf-id","gvnf").next();
- Vertex pserver = g.addV("aai-node-type","pserver","hostname","a-name").next();
+ Vertex gvnf = g.addV("aai-node-type", "generic-vnf", "vnf-id", "gvnf").next();
+ Vertex pserver = g.addV("aai-node-type", "pserver", "hostname", "a-name").next();
Edge e1 = testEdgeSer.addEdge(g, gvnf, pserver);
Edge e2 = testEdgeSer.addEdge(g, gvnf, pserver, "generic-vnf-pserver-B");
QueryBuilder<Edge> tQ = getNewEdgeTraversalWithTestEdgeRules(gvnf);
- tQ.getEdgesBetweenWithLabels(EdgeType.COUSIN, "generic-vnf", "pserver", Collections.singletonList("generic-vnf-pserver-B"));
+ tQ.getEdgesBetweenWithLabels(EdgeType.COUSIN, "generic-vnf", "pserver",
+ Collections.singletonList("generic-vnf-pserver-B"));
List<Edge> list = tQ.toList();
@@ -712,14 +688,15 @@ public abstract class QueryBuilderTestAbstraction {
@Test
public void createEdgeTraversalWithLabelsMultipleItemTest() throws AAIException {
- Vertex gvnf = g.addV("aai-node-type","generic-vnf","vnf-id","gvnf").next();
- Vertex pserver = g.addV("aai-node-type","pserver","hostname","a-name").next();
+ Vertex gvnf = g.addV("aai-node-type", "generic-vnf", "vnf-id", "gvnf").next();
+ Vertex pserver = g.addV("aai-node-type", "pserver", "hostname", "a-name").next();
Edge e1 = testEdgeSer.addEdge(g, gvnf, pserver);
Edge e2 = testEdgeSer.addEdge(g, gvnf, pserver, "generic-vnf-pserver-B");
QueryBuilder<Edge> tQ = getNewEdgeTraversalWithTestEdgeRules(gvnf);
- tQ.getEdgesBetweenWithLabels(EdgeType.COUSIN, "generic-vnf", "pserver", Arrays.asList("generic-vnf-pserver-B", "generic-vnf-pserver-A"));
+ tQ.getEdgesBetweenWithLabels(EdgeType.COUSIN, "generic-vnf", "pserver",
+ Arrays.asList("generic-vnf-pserver-B", "generic-vnf-pserver-A"));
List<Edge> list = tQ.toList();
diff --git a/aai-core/src/test/java/org/onap/aai/query/builder/QueryTestsConfigTranslator.java b/aai-core/src/test/java/org/onap/aai/query/builder/QueryTestsConfigTranslator.java
index 84c4bdd1..3661f3de 100644
--- a/aai-core/src/test/java/org/onap/aai/query/builder/QueryTestsConfigTranslator.java
+++ b/aai-core/src/test/java/org/onap/aai/query/builder/QueryTestsConfigTranslator.java
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.query.builder;
import java.util.*;
@@ -37,9 +38,10 @@ public class QueryTestsConfigTranslator extends AbstractConfigTranslator {
public QueryTestsConfigTranslator(SchemaLocationsBean bean, SchemaConfigVersions schemaVersions) {
super(bean, schemaVersions);
}
-
-
- /* (non-Javadoc)
+
+ /*
+ * (non-Javadoc)
+ *
* @see org.onap.aai.setup.ConfigTranslator#getEdgeFiles()
*/
@Override
diff --git a/aai-core/src/test/java/org/onap/aai/query/builder/SimplePathTest.java b/aai-core/src/test/java/org/onap/aai/query/builder/SimplePathTest.java
index 0a987c95..1929f4ea 100644
--- a/aai-core/src/test/java/org/onap/aai/query/builder/SimplePathTest.java
+++ b/aai-core/src/test/java/org/onap/aai/query/builder/SimplePathTest.java
@@ -17,8 +17,13 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.query.builder;
+import static org.junit.Assert.assertTrue;
+
+import java.util.List;
+
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.T;
@@ -31,23 +36,18 @@ import org.onap.aai.edges.enums.EdgeType;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.introspection.Loader;
import org.onap.aai.introspection.ModelType;
-
import org.onap.aai.serialization.db.EdgeSerializer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.DirtiesContext;
-import java.util.List;
-
-import static org.junit.Assert.assertTrue;
-
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
public class SimplePathTest extends AAISetup {
public Loader loader;
-
+
@Autowired
EdgeSerializer edgeSer;
-
+
@Before
public void setup() throws Exception {
loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getDefaultVersion());
@@ -56,52 +56,52 @@ public class SimplePathTest extends AAISetup {
private QueryBuilder<Vertex> buildTestQuery(QueryBuilder<Vertex> qb) throws AAIException {
return qb.createEdgeTraversal(EdgeType.TREE, "generic-vnf", "l-interface")
.until(qb.newInstance().getVerticesByProperty("aai-node-type", "generic-vnf"))
- .repeat(qb.newInstance().union(
- qb.newInstance().createEdgeTraversal(EdgeType.TREE, "generic-vnf", "l-interface"),
- qb.newInstance().createEdgeTraversal(EdgeType.TREE, "l-interface", "generic-vnf"),
- qb.newInstance().createEdgeTraversal(EdgeType.COUSIN, "l-interface", "logical-link"),
- qb.newInstance().createEdgeTraversal(EdgeType.COUSIN, "logical-link", "l-interface")
- ).simplePath())
+ .repeat(qb.newInstance()
+ .union(qb.newInstance().createEdgeTraversal(EdgeType.TREE, "generic-vnf", "l-interface"),
+ qb.newInstance().createEdgeTraversal(EdgeType.TREE, "l-interface", "generic-vnf"),
+ qb.newInstance().createEdgeTraversal(EdgeType.COUSIN, "l-interface", "logical-link"),
+ qb.newInstance().createEdgeTraversal(EdgeType.COUSIN, "logical-link", "l-interface"))
+ .simplePath())
.store("x").cap("x").unfold().dedup();
}
-
- private GraphTraversalSource setupGraph() throws AAIException{
+
+ private GraphTraversalSource setupGraph() throws AAIException {
Graph graph = TinkerGraph.open();
GraphTraversalSource g = graph.traversal();
-
- 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 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");
-
+ "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");
-
+ "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");
-
+ "interface-name", "lint2", "is-port-mirrored", "true", "in-maint", "true", "is-ip-unnumbered", "false");
+
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 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");
-
+
+ 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");
+
edgeSer.addTreeEdge(g, gvnf1, lint1);
edgeSer.addEdge(g, lint1, loglink1);
edgeSer.addEdge(g, loglink1, lint2);
edgeSer.addEdge(g, loglink1, lint3);
edgeSer.addTreeEdge(g, gvnf2, lint3);
-
+
return g;
}
-
+
@Test
public void gremlinQueryTest() throws AAIException {
GraphTraversalSource g = setupGraph();
List<Vertex> expected = g.V("01").toList();
Vertex start = g.V("00").toList().get(0);
-
+
GremlinTraversal<Vertex> qb = new GremlinTraversal<>(loader, g, start);
QueryBuilder<Vertex> q = buildTestQuery(qb);
List<Vertex> results = q.toList();
@@ -113,7 +113,7 @@ public class SimplePathTest extends AAISetup {
GraphTraversalSource g = setupGraph();
List<Vertex> expected = g.V("01").toList();
Vertex start = g.V("00").toList().get(0);
-
+
TraversalQuery<Vertex> qb = new TraversalQuery<>(loader, g, start);
QueryBuilder<Vertex> q = buildTestQuery(qb);
List<Vertex> results = q.toList();
diff --git a/aai-core/src/test/java/org/onap/aai/query/builder/TraversalQueryTest.java b/aai-core/src/test/java/org/onap/aai/query/builder/TraversalQueryTest.java
index f82166bf..eb1e57c3 100644
--- a/aai-core/src/test/java/org/onap/aai/query/builder/TraversalQueryTest.java
+++ b/aai-core/src/test/java/org/onap/aai/query/builder/TraversalQueryTest.java
@@ -17,8 +17,17 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.query.builder;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.List;
+
import org.apache.tinkerpop.gremlin.process.traversal.Path;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__;
@@ -28,44 +37,35 @@ import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.junit.Ignore;
import org.junit.Test;
import org.onap.aai.db.props.AAIProperties;
-import org.onap.aai.exceptions.AAIException;
import org.onap.aai.edges.enums.EdgeType;
+import org.onap.aai.exceptions.AAIException;
-import java.io.UnsupportedEncodingException;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.util.List;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
public class TraversalQueryTest extends QueryBuilderTestAbstraction {
-
@Override
protected QueryBuilder<Edge> getNewEdgeTraversalWithTestEdgeRules(Vertex v) {
return new TraversalQuery<>(loader, g, v);
}
-
+
@Override
protected QueryBuilder<Edge> getNewEdgeTraversalWithTestEdgeRules() {
return new TraversalQuery<>(loader, g);
}
-
+
@Override
protected QueryBuilder<Vertex> getNewVertexTraversalWithTestEdgeRules(Vertex v) {
return new TraversalQuery<>(loader, g, v);
}
-
+
@Override
protected QueryBuilder<Vertex> getNewVertexTraversalWithTestEdgeRules() {
return new TraversalQuery<>(loader, g);
}
-
protected QueryBuilder<Vertex> getNewVertexTraversal() {
return new TraversalQuery<>(loader, g);
}
-
+
@Override
protected QueryBuilder<Tree> getNewTreeTraversalWithTestEdgeRules(Vertex v) {
return new TraversalQuery<>(loader, g, v);
@@ -85,34 +85,33 @@ public class TraversalQueryTest extends QueryBuilderTestAbstraction {
protected QueryBuilder<Path> getNewPathTraversalWithTestEdgeRules() {
return new TraversalQuery<>(loader, g);
}
-
+
@Test
public void unionQuery() {
QueryBuilder<Vertex> tQ = getNewVertexTraversal();
QueryBuilder<Vertex> tQ2 = getNewVertexTraversal();
QueryBuilder<Vertex> tQ3 = getNewVertexTraversal();
- tQ.union(
- tQ2.getVerticesByProperty("test1", "value1"),
- tQ3.getVerticesByIndexedProperty("test2", "value2"));
+ tQ.union(tQ2.getVerticesByProperty("test1", "value1"), tQ3.getVerticesByIndexedProperty("test2", "value2"));
- GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start()
- .union(__.has("test1", "value1"),__.has("test2", "value2"));
+ GraphTraversal<Vertex, Vertex> expected =
+ __.<Vertex>start().union(__.has("test1", "value1"), __.has("test2", "value2"));
assertEquals("they are equal", expected, tQ.getQuery());
-
}
@Test
public void traversalClones() throws UnsupportedEncodingException, AAIException, URISyntaxException {
QueryBuilder<Vertex> tQ = getNewVertexTraversal();
- QueryBuilder<Vertex> builder = tQ.createQueryFromURI(new URI("network/generic-vnfs/generic-vnf/key1")).getQueryBuilder();
- GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start().has("vnf-id", "key1").has("aai-node-type", "generic-vnf");
+ QueryBuilder<Vertex> builder =
+ tQ.createQueryFromURI(new URI("network/generic-vnfs/generic-vnf/key1")).getQueryBuilder();
+ GraphTraversal<Vertex, Vertex> expected =
+ __.<Vertex>start().has("vnf-id", "key1").has("aai-node-type", "generic-vnf");
GraphTraversal<Vertex, Vertex> containerExpected = __.<Vertex>start().has("aai-node-type", "generic-vnf");
assertEquals("query object", expected.toString(), builder.getQuery().toString());
- assertEquals("container query object", containerExpected.toString(), builder.getContainerQuery().getQuery().toString());
-
+ assertEquals("container query object", containerExpected.toString(),
+ builder.getContainerQuery().getQuery().toString());
}
@@ -123,149 +122,139 @@ public class TraversalQueryTest extends QueryBuilderTestAbstraction {
public void nestedTraversalClones() throws UnsupportedEncodingException, AAIException, URISyntaxException {
QueryBuilder<Vertex> tQ = getNewVertexTraversal();
- QueryBuilder<Vertex> builder = tQ.createQueryFromURI(new URI("network/generic-vnfs/generic-vnf/key1/l-interfaces/l-interface/key2")).getQueryBuilder();
- GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start()
- .has("vnf-id", "key1")
- .has("aai-node-type", "generic-vnf")
- .in("org.onap.relationships.inventory.BelongsTo").has(AAIProperties.NODE_TYPE, "l-interface")
- .has("interface-name", "key2");
- GraphTraversal<Vertex, Vertex> containerExpected = __.<Vertex>start()
- .has("vnf-id", "key1")
- .has("aai-node-type", "generic-vnf")
- .in("org.onap.relationships.inventory.BelongsTo")
- .has(AAIProperties.NODE_TYPE, "l-interface");
-
+ QueryBuilder<Vertex> builder =
+ tQ.createQueryFromURI(new URI("network/generic-vnfs/generic-vnf/key1/l-interfaces/l-interface/key2"))
+ .getQueryBuilder();
+ GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start().has("vnf-id", "key1")
+ .has("aai-node-type", "generic-vnf").in("org.onap.relationships.inventory.BelongsTo")
+ .has(AAIProperties.NODE_TYPE, "l-interface").has("interface-name", "key2");
+ GraphTraversal<Vertex, Vertex> containerExpected =
+ __.<Vertex>start().has("vnf-id", "key1").has("aai-node-type", "generic-vnf")
+ .in("org.onap.relationships.inventory.BelongsTo").has(AAIProperties.NODE_TYPE, "l-interface");
+
assertEquals("query object", expected.toString(), builder.getQuery().toString());
- assertEquals("container query object", containerExpected.toString(), builder.getContainerQuery().getQuery().toString());
-
+ assertEquals("container query object", containerExpected.toString(),
+ builder.getContainerQuery().getQuery().toString());
}
-
+
@Test
public void abstractEdgeToVertexTraversalTest() throws AAIException {
-
- Vertex gvnf = g.addV("aai-node-type","generic-vnf","vnf-id","gvnf").next();
- Vertex vnfc1 = g.addV("aai-node-type","vnfc","vnfc-name","a-name").next();
-
+
+ Vertex gvnf = g.addV("aai-node-type", "generic-vnf", "vnf-id", "gvnf").next();
+ Vertex vnfc1 = g.addV("aai-node-type", "vnfc", "vnfc-name", "a-name").next();
+
testEdgeSer.addEdge(g, gvnf, vnfc1);
-
+
QueryBuilder<Vertex> tQ = getNewVertexTraversalWithTestEdgeRules(gvnf);
tQ.createEdgeTraversal(EdgeType.COUSIN, "vnf", "vnfc");
-
+
List<Vertex> list = tQ.toList();
assertEquals("Has 1 vertexes ", 1, list.size());
assertTrue("Has vertex on the default edge ", list.contains(vnfc1));
-
}
-
+
@Test
public void abstractEdgeToVertexTraversalSingleOutRuleTest() throws AAIException {
-
- Vertex vce = g.addV("aai-node-type","vce","vnf-id","vce").next();
- Vertex vnfc1 = g.addV("aai-node-type","vnfc","vnfc-name","a-name").next();
-
+
+ Vertex vce = g.addV("aai-node-type", "vce", "vnf-id", "vce").next();
+ Vertex vnfc1 = g.addV("aai-node-type", "vnfc", "vnfc-name", "a-name").next();
+
testEdgeSer.addEdge(g, vce, vnfc1);
-
+
QueryBuilder<Vertex> tQ1 = getNewVertexTraversalWithTestEdgeRules(vce);
tQ1.createEdgeTraversal(EdgeType.COUSIN, "vnf", "vnfc");
-
+
QueryBuilder<Vertex> tQ2 = getNewVertexTraversalWithTestEdgeRules(vnfc1);
tQ2.createEdgeTraversal(EdgeType.COUSIN, "vnfc", "vnf");
-
+
List<Vertex> list1 = tQ1.toList();
List<Vertex> list2 = tQ2.toList();
-
+
assertEquals("1 - Has 1 vertexes ", 1, list1.size());
assertTrue("1 - traversal results in vnfc ", list1.contains(vnfc1));
assertEquals("2 - Has 1 vertexes ", 1, list2.size());
assertTrue("2 - traversal results in vce ", list2.contains(vce));
-
}
-
+
@Test
public void abstractEdgeToVertexTraversalSingleInRuleTest() throws AAIException {
-
- Vertex vce = g.addV("aai-node-type","vce","vnf-id","vce").next();
- Vertex pserver = g.addV("aai-node-type","pserver","hostname","a-name").next();
-
+
+ Vertex vce = g.addV("aai-node-type", "vce", "vnf-id", "vce").next();
+ Vertex pserver = g.addV("aai-node-type", "pserver", "hostname", "a-name").next();
+
testEdgeSer.addEdge(g, vce, pserver);
-
+
QueryBuilder<Vertex> tQ1 = getNewVertexTraversalWithTestEdgeRules(vce);
tQ1.createEdgeTraversal(EdgeType.COUSIN, "vnf", "pserver");
-
+
List<Vertex> list = tQ1.toList();
assertEquals("1 - Has 1 vertexes ", 1, list.size());
assertTrue("1 - traversal results in vnfc ", list.contains(pserver));
-
}
-
+
@Test
public void abstractEdgeToVertexMultiRuleTraversalTest() throws AAIException {
-
- Vertex gvnf = g.addV("aai-node-type","generic-vnf","vnf-id","gvnf").next();
- Vertex vnfc1 = g.addV("aai-node-type","vnfc","vnfc-name","a-name").next();
- Vertex vnfc2 = g.addV("aai-node-type","vnfc","vnfc-name","b-name").next();
-
+
+ Vertex gvnf = g.addV("aai-node-type", "generic-vnf", "vnf-id", "gvnf").next();
+ Vertex vnfc1 = g.addV("aai-node-type", "vnfc", "vnfc-name", "a-name").next();
+ Vertex vnfc2 = g.addV("aai-node-type", "vnfc", "vnfc-name", "b-name").next();
+
testEdgeSer.addEdge(g, gvnf, vnfc1);
testEdgeSer.addEdge(g, gvnf, vnfc2, "re-uses");
-
+
QueryBuilder<Vertex> tQ = getNewVertexTraversalWithTestEdgeRules(gvnf);
tQ.createEdgeTraversal(EdgeType.COUSIN, "vnf", "vnfc");
-
+
List<Vertex> list = tQ.toList();
assertEquals("Has 2 vertexes ", 2, list.size());
assertTrue("Has vertex on the default edge ", list.contains(vnfc1));
assertTrue("Has vertex on the re-uses edge ", list.contains(vnfc2));
-
}
-
+
@Test
public void abstractEdgeToVertexMultiRuleOutTraversalTest() throws AAIException {
-
- Vertex gvnf = g.addV("aai-node-type","generic-vnf","vnf-id","gvnf").next();
- Vertex pserver = g.addV("aai-node-type","pserver","hostname","a-name").next();
-
+
+ Vertex gvnf = g.addV("aai-node-type", "generic-vnf", "vnf-id", "gvnf").next();
+ Vertex pserver = g.addV("aai-node-type", "pserver", "hostname", "a-name").next();
+
testEdgeSer.addEdge(g, gvnf, pserver);
testEdgeSer.addEdge(g, gvnf, pserver, "generic-vnf-pserver-B");
-
+
QueryBuilder<Vertex> tQ = getNewVertexTraversalWithTestEdgeRules(gvnf);
tQ.createEdgeTraversal(EdgeType.COUSIN, "vnf", "pserver");
-
+
List<Vertex> list = tQ.toList();
-
+
assertEquals("Has 2 vertexes ", 2, list.size());
assertTrue("result has pserver ", list.contains(pserver));
-
}
-
+
@Test
public void abstractEdgeToVertexMultiRuleInTraversalTest() throws AAIException {
-
- Vertex gvnf = g.addV("aai-node-type","generic-vnf","vnf-id","gvnf").next();
- Vertex complex = g.addV("aai-node-type","complex","physical-location-id","a-name").next();
-
+
+ Vertex gvnf = g.addV("aai-node-type", "generic-vnf", "vnf-id", "gvnf").next();
+ Vertex complex = g.addV("aai-node-type", "complex", "physical-location-id", "a-name").next();
+
testEdgeSer.addEdge(g, gvnf, complex);
testEdgeSer.addEdge(g, gvnf, complex, "complex-generic-vnf-B");
-
+
QueryBuilder<Vertex> tQ = getNewVertexTraversalWithTestEdgeRules(gvnf);
tQ.createEdgeTraversal(EdgeType.COUSIN, "vnf", "complex");
-
+
List<Vertex> list = tQ.toList();
-
+
assertEquals("Has 2 vertexes ", 2, list.size());
assertTrue("result has pserver ", list.contains(complex));
-
}
-
-
}
diff --git a/aai-core/src/test/java/org/onap/aai/query/builder/TraversalURIOptimizedQueryTest.java b/aai-core/src/test/java/org/onap/aai/query/builder/TraversalURIOptimizedQueryTest.java
index 8ec01aaa..7ed90711 100644
--- a/aai-core/src/test/java/org/onap/aai/query/builder/TraversalURIOptimizedQueryTest.java
+++ b/aai-core/src/test/java/org/onap/aai/query/builder/TraversalURIOptimizedQueryTest.java
@@ -17,12 +17,14 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.query.builder;
import org.apache.tinkerpop.gremlin.process.traversal.Path;
import org.apache.tinkerpop.gremlin.process.traversal.step.util.Tree;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Vertex;
+
public class TraversalURIOptimizedQueryTest extends TraversalQueryTest {
@Override
@@ -45,7 +47,6 @@ public class TraversalURIOptimizedQueryTest extends TraversalQueryTest {
return new TraversalURIOptimizedQuery<>(loader, g);
}
-
@Override
protected QueryBuilder<Vertex> getNewVertexTraversal() {
return new TraversalURIOptimizedQuery<>(loader, g);
diff --git a/aai-core/src/test/java/org/onap/aai/query/builder/UntilTest.java b/aai-core/src/test/java/org/onap/aai/query/builder/UntilTest.java
index c5290375..dcf11ba2 100644
--- a/aai-core/src/test/java/org/onap/aai/query/builder/UntilTest.java
+++ b/aai-core/src/test/java/org/onap/aai/query/builder/UntilTest.java
@@ -17,8 +17,14 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.query.builder;
+import static org.junit.Assert.assertTrue;
+
+import java.util.ArrayList;
+import java.util.List;
+
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.T;
@@ -28,47 +34,41 @@ import org.junit.Before;
import org.junit.Test;
import org.onap.aai.AAISetup;
import org.onap.aai.db.props.AAIProperties;
+import org.onap.aai.edges.enums.EdgeType;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.introspection.Loader;
import org.onap.aai.introspection.ModelType;
-
import org.onap.aai.serialization.db.EdgeSerializer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.DirtiesContext;
-import org.onap.aai.edges.enums.EdgeType;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import static org.junit.Assert.assertTrue;
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
public class UntilTest extends AAISetup {
private Loader loader;
-
+
@Autowired
EdgeSerializer edgeSer;
-
+
@Before
public void setup() throws Exception {
loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getDefaultVersion());
}
-
- private QueryBuilder<Vertex> buildTestQuery(QueryBuilder<Vertex> qb) throws AAIException{
- return qb.until(qb.newInstance().getVerticesByProperty("aai-node-type", "l-interface")).repeat(
- qb.newInstance().union(
+
+ private QueryBuilder<Vertex> buildTestQuery(QueryBuilder<Vertex> qb) throws AAIException {
+ return qb.until(qb.newInstance().getVerticesByProperty("aai-node-type", "l-interface"))
+ .repeat(qb.newInstance().union(
qb.newInstance().createEdgeTraversal(EdgeType.TREE, "cloud-region", "tenant"),
qb.newInstance().createEdgeTraversal(EdgeType.TREE, "tenant", "vserver"),
- qb.newInstance().createEdgeTraversal(EdgeType.TREE, "vserver", "l-interface")
- )).store("x").cap("x").unfold().dedup();
+ qb.newInstance().createEdgeTraversal(EdgeType.TREE, "vserver", "l-interface")))
+ .store("x").cap("x").unfold().dedup();
}
-
+
@Test
public void gremlinQueryUntilTest() throws AAIException {
Graph graph = TinkerGraph.open();
GraphTraversalSource g = graph.traversal();
-
+
Vertex v1 = graph.addVertex(T.id, 1, "aai-node-type", "cloud-region");
Vertex v2 = graph.addVertex(T.id, 2, "aai-node-type", "tenant");
Vertex v3 = graph.addVertex(T.id, 3, "aai-node-type", "vserver");
@@ -78,10 +78,10 @@ public class UntilTest extends AAISetup {
edgeSer.addTreeEdge(g, v3, v4);
List<Vertex> expected = new ArrayList<>();
expected.add(v4);
-
- GremlinTraversal<Vertex> qb = new GremlinTraversal<>(loader, g, v1);
+
+ GremlinTraversal<Vertex> qb = new GremlinTraversal<>(loader, g, v1);
QueryBuilder q = buildTestQuery(qb);
-
+
List<Vertex> results = q.toList();
assertTrue("results match", expected.containsAll(results) && results.containsAll(expected));
@@ -91,7 +91,7 @@ public class UntilTest extends AAISetup {
public void traversalQueryUntilTest() throws AAIException {
Graph graph = TinkerGraph.open();
GraphTraversalSource g = graph.traversal();
-
+
Vertex v1 = graph.addVertex(T.id, 1, "aai-node-type", "cloud-region");
Vertex v2 = graph.addVertex(T.id, 2, "aai-node-type", "tenant");
Vertex v3 = graph.addVertex(T.id, 3, "aai-node-type", "vserver");
@@ -101,15 +101,13 @@ public class UntilTest extends AAISetup {
edgeSer.addTreeEdge(g, v3, v4);
List<Vertex> expected = new ArrayList<>();
expected.add(v4);
-
- TraversalQuery<Vertex> qb = new TraversalQuery<>(loader, g, v1);
+
+ TraversalQuery<Vertex> qb = new TraversalQuery<>(loader, g, v1);
QueryBuilder<Vertex> q = buildTestQuery(qb);
-
+
List<Vertex> results = q.toList();
assertTrue("results match", expected.containsAll(results) && results.containsAll(expected));
}
-
-
}
diff --git a/aai-core/src/test/java/org/onap/aai/query/builder/optimization/AbstractGraphTraversalBuilderOptmizationTest.java b/aai-core/src/test/java/org/onap/aai/query/builder/optimization/AbstractGraphTraversalBuilderOptmizationTest.java
index c8134b2d..911cb20c 100644
--- a/aai-core/src/test/java/org/onap/aai/query/builder/optimization/AbstractGraphTraversalBuilderOptmizationTest.java
+++ b/aai-core/src/test/java/org/onap/aai/query/builder/optimization/AbstractGraphTraversalBuilderOptmizationTest.java
@@ -17,9 +17,19 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.query.builder.optimization;
+import static org.junit.Assert.assertEquals;
+
import com.google.common.base.CaseFormat;
+
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Random;
+
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.Vertex;
@@ -32,7 +42,6 @@ import org.onap.aai.dbmap.DBConnectionType;
import org.onap.aai.introspection.Introspector;
import org.onap.aai.introspection.Loader;
import org.onap.aai.introspection.ModelType;
-
import org.onap.aai.query.builder.QueryBuilder;
import org.onap.aai.serialization.db.DBSerializer;
import org.onap.aai.serialization.db.EdgeSerializer;
@@ -41,17 +50,9 @@ import org.onap.aai.serialization.engines.QueryStyle;
import org.onap.aai.serialization.engines.TransactionalGraphEngine;
import org.springframework.beans.factory.annotation.Autowired;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Random;
+public abstract class AbstractGraphTraversalBuilderOptmizationTest extends AAISetup {
-import static org.junit.Assert.assertEquals;
-
-public abstract class AbstractGraphTraversalBuilderOptmizationTest extends AAISetup{
-
- protected static final List<String> RANDOM_VALUES = Arrays.asList("A","B","C","D","E");
+ protected static final List<String> RANDOM_VALUES = Arrays.asList("A", "B", "C", "D", "E");
protected static final String crUriPattern = "/cloud-infrastructure/cloud-regions/cloud-region/%s/%s";
protected static final String tenantUriPatternSuffix = "/tenants/tenant/%s";
@@ -84,14 +85,14 @@ public abstract class AbstractGraphTraversalBuilderOptmizationTest extends AAISe
protected static Random rand;
-
- protected void setupData(int tenantNum, int vserverPerTenantNum, String prefix) throws Exception{
+ protected void setupData(int tenantNum, int vserverPerTenantNum, String prefix) throws Exception {
loader = loaderFactory.createLoaderForVersion(introspectorFactoryType, schemaVersions.getDefaultVersion());
graph = AAIGraph.getInstance().getGraph();
dbEngine = new JanusGraphDBEngine(queryStyle, type, loader);
g = dbEngine.startTransaction().traversal();
- dbser = new DBSerializer(schemaVersions.getDefaultVersion(), dbEngine, introspectorFactoryType, "AAI-TEST-" + prefix);
+ dbser = new DBSerializer(schemaVersions.getDefaultVersion(), dbEngine, introspectorFactoryType,
+ "AAI-TEST-" + prefix);
rand = new Random();
@@ -105,12 +106,9 @@ public abstract class AbstractGraphTraversalBuilderOptmizationTest extends AAISe
long startTime = System.currentTimeMillis();
for (int crCtr = 0; crCtr < 3; crCtr++) {
crUri = String.format(crUriPattern, prefix + "cloud-owner-" + crCtr, prefix + "cloud-region-id-" + crCtr);
- //System.out.println(crUri);
- cr = g.addV(AAIProperties.NODE_TYPE, CLOUD_REGION,
- CLOUD_REGION_ID, prefix + "cloud-region-id-" + crCtr,
- CLOUD_OWNER, prefix + "cloud-owner-" + crCtr,
- AAIProperties.AAI_URI, crUri
- ).next();
+ // System.out.println(crUri);
+ cr = g.addV(AAIProperties.NODE_TYPE, CLOUD_REGION, CLOUD_REGION_ID, prefix + "cloud-region-id-" + crCtr,
+ CLOUD_OWNER, prefix + "cloud-owner-" + crCtr, AAIProperties.AAI_URI, crUri).next();
for (int i = 0; i < tenantNum; i++) {
Introspector intro = loader.introspectorFromName(TENANT);
tenant = dbser.createNewVertex(intro);
@@ -118,7 +116,7 @@ public abstract class AbstractGraphTraversalBuilderOptmizationTest extends AAISe
intro.setValue(TENANT_ID, prefix + "tenant-id-" + i);
intro.setValue(TENANT_NAME, prefix + "tenant-name-" + i);
dbser.serializeSingleVertex(tenant, intro, "AAI-TEST-" + prefix);
- //System.out.println("Tenant " + crCtr + " " + i);
+ // System.out.println("Tenant " + crCtr + " " + i);
for (int j = 0; j < vserverPerTenantNum; j++) {
intro = loader.introspectorFromName(VSERVER);
vserver = dbser.createNewVertex(intro);
@@ -128,13 +126,15 @@ public abstract class AbstractGraphTraversalBuilderOptmizationTest extends AAISe
intro.setValue(PROV_STATUS, RANDOM_VALUES.get(rand.nextInt(RANDOM_VALUES.size())));
intro.setValue(VSERVER_SELFLINK, RANDOM_VALUES.get(rand.nextInt(RANDOM_VALUES.size())));
dbser.serializeSingleVertex(vserver, intro, "AAI-TEST-" + prefix);
- //System.out.println("Vserver " + crCtr + " " + i + " " + j);
+ // System.out.println("Vserver " + crCtr + " " + i + " " + j);
}
}
}
- //g.V().forEachRemaining(v -> v.properties().forEachRemaining(p -> System.out.println(p.key() + " : " + p.value())));
- //g.E().forEachRemaining(e -> System.out.println(e.outVertex().property(AAIProperties.NODE_TYPE).value() + " : " + e.inVertex().property(AAIProperties.NODE_TYPE).value()));
- long time = System.currentTimeMillis()-startTime;
+ // g.V().forEachRemaining(v -> v.properties().forEachRemaining(p -> System.out.println(p.key() + " : " +
+ // p.value())));
+ // g.E().forEachRemaining(e -> System.out.println(e.outVertex().property(AAIProperties.NODE_TYPE).value() + " :
+ // " + e.inVertex().property(AAIProperties.NODE_TYPE).value()));
+ long time = System.currentTimeMillis() - startTime;
System.out.println("Data load ended\n" + time);
}
@@ -149,48 +149,52 @@ public abstract class AbstractGraphTraversalBuilderOptmizationTest extends AAISe
System.out.println("Done");
}
- protected void execute(Method getQueryMethod, int numResultsExpected) throws Exception{
+ protected void execute(Method getQueryMethod, int numResultsExpected) throws Exception {
int iterations = numOfTimesToRun();
long noneTimer = 0;
long uriTimer = 0;
- for (int i = 0; i < iterations+1 ; i++) {
- if (i == 0 ) { // dont use incase initial cold starts
+ for (int i = 0; i < iterations + 1; i++) {
+ if (i == 0) { // dont use incase initial cold starts
timeQuery(getQuery(getQueryMethod, OptimizeEnum.NONE), numResultsExpected, OptimizeEnum.NONE);
timeQuery(getQuery(getQueryMethod, OptimizeEnum.URI), numResultsExpected, OptimizeEnum.URI);
} else {
- noneTimer += timeQuery(getQuery(getQueryMethod, OptimizeEnum.NONE), numResultsExpected, OptimizeEnum.NONE);
+ noneTimer +=
+ timeQuery(getQuery(getQueryMethod, OptimizeEnum.NONE), numResultsExpected, OptimizeEnum.NONE);
uriTimer += timeQuery(getQuery(getQueryMethod, OptimizeEnum.URI), numResultsExpected, OptimizeEnum.URI);
}
}
noneTimer /= iterations;
uriTimer /= iterations;
- System.out.println(CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, getQueryMethod.getName()).replace("-query", "") + "\t" + (noneTimer)/100000.0 + "\t" + (uriTimer)/100000.0);
- //System.out.println((noneTimer)/100000.0 + " ms, (Not optimized)");
- //System.out.println((uriTimer)/100000.0 + " ms, (URI optimized)");
+ System.out.println(
+ CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, getQueryMethod.getName()).replace("-query", "")
+ + "\t" + (noneTimer) / 100000.0 + "\t" + (uriTimer) / 100000.0);
+ // System.out.println((noneTimer)/100000.0 + " ms, (Not optimized)");
+ // System.out.println((uriTimer)/100000.0 + " ms, (URI optimized)");
}
- private QueryBuilder<Vertex> getQuery(Method getQueryMethod, OptimizeEnum optimization) throws InvocationTargetException, IllegalAccessException {
+ private QueryBuilder<Vertex> getQuery(Method getQueryMethod, OptimizeEnum optimization)
+ throws InvocationTargetException, IllegalAccessException {
return (QueryBuilder<Vertex>) getQueryMethod.invoke(this, optimization);
}
-
private long timeQuery(QueryBuilder<Vertex> query, int numResultsExpected, OptimizeEnum optimized) {
- //System.out.println(optimized.toString());
+ // System.out.println(optimized.toString());
long startTime = System.nanoTime();
List<Vertex> result = query.toList();
long endTime = System.nanoTime();
-// if (!optimized) {
-// result.get(0).properties().forEachRemaining(p -> System.out.println(p.key() + " : " + p.value()));
-// }
- //System.out.println("Result size: " + result.size());
+ // if (!optimized) {
+ // result.get(0).properties().forEachRemaining(p -> System.out.println(p.key() + " : " + p.value()));
+ // }
+ // System.out.println("Result size: " + result.size());
if (numResultsExpected != Integer.MIN_VALUE) {
- assertEquals( optimized.toString() + " optimized" + " query results in " + numResultsExpected + " vserver ", numResultsExpected, result.size());
+ assertEquals(optimized.toString() + " optimized" + " query results in " + numResultsExpected + " vserver ",
+ numResultsExpected, result.size());
}
return endTime - startTime;
@@ -206,4 +210,3 @@ public abstract class AbstractGraphTraversalBuilderOptmizationTest extends AAISe
}
}
-
diff --git a/aai-core/src/test/java/org/onap/aai/query/builder/optimization/AbstractGraphTraversalBuilderTestQueryiesToRun.java b/aai-core/src/test/java/org/onap/aai/query/builder/optimization/AbstractGraphTraversalBuilderTestQueryiesToRun.java
index 8a80fb94..28e7a7f8 100644
--- a/aai-core/src/test/java/org/onap/aai/query/builder/optimization/AbstractGraphTraversalBuilderTestQueryiesToRun.java
+++ b/aai-core/src/test/java/org/onap/aai/query/builder/optimization/AbstractGraphTraversalBuilderTestQueryiesToRun.java
@@ -17,8 +17,15 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.query.builder.optimization;
+import java.lang.reflect.Method;
+import java.net.URI;
+
+import javax.ws.rs.core.MultivaluedHashMap;
+import javax.ws.rs.core.MultivaluedMap;
+
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.junit.Before;
import org.junit.Test;
@@ -26,12 +33,8 @@ import org.onap.aai.query.builder.QueryBuilder;
import org.onap.aai.query.builder.TraversalQuery;
import org.onap.aai.query.builder.TraversalURIOptimizedQuery;
-import javax.ws.rs.core.MultivaluedHashMap;
-import javax.ws.rs.core.MultivaluedMap;
-import java.lang.reflect.Method;
-import java.net.URI;
-
-public abstract class AbstractGraphTraversalBuilderTestQueryiesToRun extends AbstractGraphTraversalBuilderOptmizationTest {
+public abstract class AbstractGraphTraversalBuilderTestQueryiesToRun
+ extends AbstractGraphTraversalBuilderOptmizationTest {
protected static final String CLOUD_OWNER_1 = "cloud-owner-1";
protected static final String CLOUD_REGION_ID_1 = "cloud-region-id-1";
@@ -52,7 +55,6 @@ public abstract class AbstractGraphTraversalBuilderTestQueryiesToRun extends Abs
protected abstract String getPrefix();
-
private QueryBuilder<Vertex> getQueryBuilder(OptimizeEnum optimized) {
if (OptimizeEnum.URI.equals(optimized)) {
return new TraversalURIOptimizedQuery<>(loader, g);
@@ -63,7 +65,8 @@ public abstract class AbstractGraphTraversalBuilderTestQueryiesToRun extends Abs
private void callTest(String methodName, int numResultsExpected) throws Exception {
String queryMethodName = methodName.replace("Test", "Query");
- Method method = AbstractGraphTraversalBuilderTestQueryiesToRun.class.getMethod(queryMethodName, OptimizeEnum.class);
+ Method method =
+ AbstractGraphTraversalBuilderTestQueryiesToRun.class.getMethod(queryMethodName, OptimizeEnum.class);
this.execute(method, numResultsExpected);
}
@@ -74,7 +77,8 @@ public abstract class AbstractGraphTraversalBuilderTestQueryiesToRun extends Abs
}
public QueryBuilder<Vertex> vserverQuery(OptimizeEnum optimized) throws Exception {
- URI uri = new URI(String.format(vserverUriPattern, getPrefix() + CLOUD_OWNER_1, getPrefix() + CLOUD_REGION_ID_1, tenantId, vserverId));
+ URI uri = new URI(String.format(vserverUriPattern, getPrefix() + CLOUD_OWNER_1, getPrefix() + CLOUD_REGION_ID_1,
+ tenantId, vserverId));
return getQueryBuilder(optimized).createQueryFromURI(uri).getQueryBuilder();
}
@@ -85,7 +89,9 @@ public abstract class AbstractGraphTraversalBuilderTestQueryiesToRun extends Abs
}
public QueryBuilder<Vertex> vserversUnderATenantQuery(OptimizeEnum optimized) throws Exception {
- URI uri = new URI(String.format(tenantUriPattern, getPrefix() + CLOUD_OWNER_1, getPrefix() + CLOUD_REGION_ID_1, tenantId) + "/vservers");
+ URI uri = new URI(
+ String.format(tenantUriPattern, getPrefix() + CLOUD_OWNER_1, getPrefix() + CLOUD_REGION_ID_1, tenantId)
+ + "/vservers");
return getQueryBuilder(optimized).createQueryFromURI(uri).getQueryBuilder();
}
@@ -96,7 +102,9 @@ public abstract class AbstractGraphTraversalBuilderTestQueryiesToRun extends Abs
}
public QueryBuilder<Vertex> vserversUnderATenantWithNonIndexPropertyQuery(OptimizeEnum optimized) throws Exception {
- URI uri = new URI(String.format(tenantUriPattern, getPrefix() + CLOUD_OWNER_1, getPrefix() + CLOUD_REGION_ID_1, tenantId) + "/vservers");
+ URI uri = new URI(
+ String.format(tenantUriPattern, getPrefix() + CLOUD_OWNER_1, getPrefix() + CLOUD_REGION_ID_1, tenantId)
+ + "/vservers");
MultivaluedMap<String, String> map = new MultivaluedHashMap<>();
map.putSingle(VSERVER_SELFLINK, randomFromList);
return getQueryBuilder(optimized).createQueryFromURI(uri, map).getQueryBuilder();
@@ -108,8 +116,11 @@ public abstract class AbstractGraphTraversalBuilderTestQueryiesToRun extends Abs
callTest(methodName, Integer.MIN_VALUE);
}
- public QueryBuilder<Vertex> vserversUnderATenantWithIndexPropertyWhereValueIsInMultipleQuery(OptimizeEnum optimized) throws Exception {
- URI uri = new URI(String.format(tenantUriPattern, getPrefix() + CLOUD_OWNER_1, getPrefix() + CLOUD_REGION_ID_1, tenantId) + "/vservers");
+ public QueryBuilder<Vertex> vserversUnderATenantWithIndexPropertyWhereValueIsInMultipleQuery(OptimizeEnum optimized)
+ throws Exception {
+ URI uri = new URI(
+ String.format(tenantUriPattern, getPrefix() + CLOUD_OWNER_1, getPrefix() + CLOUD_REGION_ID_1, tenantId)
+ + "/vservers");
MultivaluedMap<String, String> map = new MultivaluedHashMap<>();
map.putSingle(PROV_STATUS, randomFromList);
return getQueryBuilder(optimized).createQueryFromURI(uri, map).getQueryBuilder();
@@ -121,8 +132,11 @@ public abstract class AbstractGraphTraversalBuilderTestQueryiesToRun extends Abs
callTest(methodName, Integer.MIN_VALUE);
}
- public QueryBuilder<Vertex> vserversUnderATenantWithIndexPropertyWhereValueIsSemiUniqueQuery(OptimizeEnum optimized) throws Exception {
- URI uri = new URI(String.format(tenantUriPattern, getPrefix() + CLOUD_OWNER_1, getPrefix() + CLOUD_REGION_ID_1, tenantId) + "/vservers");
+ public QueryBuilder<Vertex> vserversUnderATenantWithIndexPropertyWhereValueIsSemiUniqueQuery(OptimizeEnum optimized)
+ throws Exception {
+ URI uri = new URI(
+ String.format(tenantUriPattern, getPrefix() + CLOUD_OWNER_1, getPrefix() + CLOUD_REGION_ID_1, tenantId)
+ + "/vservers");
MultivaluedMap<String, String> map = new MultivaluedHashMap<>();
map.putSingle(VSERVER_NAME, vserverName);
return getQueryBuilder(optimized).createQueryFromURI(uri, map).getQueryBuilder();
@@ -136,7 +150,8 @@ public abstract class AbstractGraphTraversalBuilderTestQueryiesToRun extends Abs
}
public QueryBuilder<Vertex> nonExistentVserverQuery(OptimizeEnum optimized) throws Exception {
- URI uri = new URI(String.format(vserverUriPattern, getPrefix() + CLOUD_OWNER_1, getPrefix() + CLOUD_REGION_ID_1, tenantId, "does-not-exist"));
+ URI uri = new URI(String.format(vserverUriPattern, getPrefix() + CLOUD_OWNER_1, getPrefix() + CLOUD_REGION_ID_1,
+ tenantId, "does-not-exist"));
return getQueryBuilder(optimized).createQueryFromURI(uri).getQueryBuilder();
}
@@ -147,7 +162,8 @@ public abstract class AbstractGraphTraversalBuilderTestQueryiesToRun extends Abs
}
public QueryBuilder<Vertex> vserverWithNonExistentTenantQuery(OptimizeEnum optimized) throws Exception {
- URI uri = new URI(String.format(vserverUriPattern, getPrefix() + CLOUD_OWNER_1, getPrefix() + CLOUD_REGION_ID_1, "does-not-exist", vserverId));
+ URI uri = new URI(String.format(vserverUriPattern, getPrefix() + CLOUD_OWNER_1, getPrefix() + CLOUD_REGION_ID_1,
+ "does-not-exist", vserverId));
return getQueryBuilder(optimized).createQueryFromURI(uri).getQueryBuilder();
}
@@ -158,7 +174,8 @@ public abstract class AbstractGraphTraversalBuilderTestQueryiesToRun extends Abs
}
public QueryBuilder<Vertex> vserverWithValidQueryParameterQuery(OptimizeEnum optimized) throws Exception {
- URI uri = new URI(String.format(vserverUriPattern, getPrefix() + CLOUD_OWNER_1, getPrefix() + CLOUD_REGION_ID_1, tenantId, vserverId));
+ URI uri = new URI(String.format(vserverUriPattern, getPrefix() + CLOUD_OWNER_1, getPrefix() + CLOUD_REGION_ID_1,
+ tenantId, vserverId));
MultivaluedMap<String, String> map = new MultivaluedHashMap<>();
map.putSingle("vserver-name2", "someName");
return getQueryBuilder(optimized).createQueryFromURI(uri, map).getQueryBuilder();
@@ -177,5 +194,4 @@ public abstract class AbstractGraphTraversalBuilderTestQueryiesToRun extends Abs
return getQueryBuilder(optimized).createQueryFromURI(uri, map).getQueryBuilder();
}
-
}
diff --git a/aai-core/src/test/java/org/onap/aai/query/builder/optimization/OptimizeEnum.java b/aai-core/src/test/java/org/onap/aai/query/builder/optimization/OptimizeEnum.java
index 907f4ff5..e8e4399b 100644
--- a/aai-core/src/test/java/org/onap/aai/query/builder/optimization/OptimizeEnum.java
+++ b/aai-core/src/test/java/org/onap/aai/query/builder/optimization/OptimizeEnum.java
@@ -17,8 +17,9 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.query.builder.optimization;
public enum OptimizeEnum {
- URI,NONE
+ URI, NONE
}
diff --git a/aai-core/src/test/java/org/onap/aai/query/builder/optimization/tests/AOneTenantOneVserversPerTenantTest.java b/aai-core/src/test/java/org/onap/aai/query/builder/optimization/tests/AOneTenantOneVserversPerTenantTest.java
index c65dbb4e..4c6226ac 100644
--- a/aai-core/src/test/java/org/onap/aai/query/builder/optimization/tests/AOneTenantOneVserversPerTenantTest.java
+++ b/aai-core/src/test/java/org/onap/aai/query/builder/optimization/tests/AOneTenantOneVserversPerTenantTest.java
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.query.builder.optimization.tests;
import org.junit.BeforeClass;
@@ -32,7 +33,7 @@ public class AOneTenantOneVserversPerTenantTest extends AbstractGraphTraversalBu
@BeforeClass
public void setup() throws Exception {
- setupData(tenantNum,vserverPerTenantNum, prefix);
+ setupData(tenantNum, vserverPerTenantNum, prefix);
}
@Override
diff --git a/aai-core/src/test/java/org/onap/aai/query/builder/optimization/tests/BTenTenantTenVserversPerTenantTest.java b/aai-core/src/test/java/org/onap/aai/query/builder/optimization/tests/BTenTenantTenVserversPerTenantTest.java
index 83c965e4..aea2899b 100644
--- a/aai-core/src/test/java/org/onap/aai/query/builder/optimization/tests/BTenTenantTenVserversPerTenantTest.java
+++ b/aai-core/src/test/java/org/onap/aai/query/builder/optimization/tests/BTenTenantTenVserversPerTenantTest.java
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.query.builder.optimization.tests;
import org.junit.BeforeClass;
@@ -32,7 +33,7 @@ public class BTenTenantTenVserversPerTenantTest extends AbstractGraphTraversalBu
@BeforeClass
public void setup() throws Exception {
- setupData(tenantNum,vserverPerTenantNum, prefix);
+ setupData(tenantNum, vserverPerTenantNum, prefix);
}
@Override
diff --git a/aai-core/src/test/java/org/onap/aai/rest/CloudRegionTest.java b/aai-core/src/test/java/org/onap/aai/rest/CloudRegionTest.java
index baed76b3..e410f529 100644
--- a/aai-core/src/test/java/org/onap/aai/rest/CloudRegionTest.java
+++ b/aai-core/src/test/java/org/onap/aai/rest/CloudRegionTest.java
@@ -17,9 +17,19 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.rest;
+import static org.junit.Assert.assertEquals;
+
import com.jayway.jsonpath.JsonPath;
+
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collection;
+
+import javax.ws.rs.core.Response;
+
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
@@ -32,13 +42,6 @@ import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.engines.QueryStyle;
import org.skyscreamer.jsonassert.JSONAssert;
-import javax.ws.rs.core.Response;
-import java.io.IOException;
-import java.util.Arrays;
-import java.util.Collection;
-
-import static org.junit.Assert.assertEquals;
-
/**
* <b>CloudRegionTest</b> is testing if you put a cloud region with all
* children nodes associated to it then you should be able to
@@ -54,14 +57,11 @@ public class CloudRegionTest extends AAISetup {
@Parameterized.Parameters(name = "QueryStyle.{0}")
public static Collection<Object[]> data() {
- return Arrays.asList(new Object[][]{
- {QueryStyle.TRAVERSAL},
- {QueryStyle.TRAVERSAL_URI}
- });
+ return Arrays.asList(new Object[][] {{QueryStyle.TRAVERSAL}, {QueryStyle.TRAVERSAL_URI}});
}
@Before
- public void setUp(){
+ public void setUp() {
httpTestUtil = new HttpTestUtil(queryStyle);
}
@@ -70,9 +70,10 @@ public class CloudRegionTest extends AAISetup {
public void testPutWithAllCloudRegionChildrenNodesAndCheckIfDeleteIsSuccessful() throws IOException, AAIException {
String cloudRegionPayload = PayloadUtil.getResourcePayload("cloud-region-with-all-children.json");
- String cloudRegionUri = "/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/junit-cloud-owner/junit-cloud-region";
+ String cloudRegionUri =
+ "/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/junit-cloud-owner/junit-cloud-region";
- Response response = httpTestUtil.doPut(cloudRegionUri, cloudRegionPayload);
+ Response response = httpTestUtil.doPut(cloudRegionUri, cloudRegionPayload);
assertEquals("Expected the cloud region to be created", 201, response.getStatus());
response = httpTestUtil.doGet(cloudRegionUri);
diff --git a/aai-core/src/test/java/org/onap/aai/rest/EdgeNotValidAnymoreTest.java b/aai-core/src/test/java/org/onap/aai/rest/EdgeNotValidAnymoreTest.java
index 1a69fc58..68fae9ce 100644
--- a/aai-core/src/test/java/org/onap/aai/rest/EdgeNotValidAnymoreTest.java
+++ b/aai-core/src/test/java/org/onap/aai/rest/EdgeNotValidAnymoreTest.java
@@ -17,8 +17,19 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
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.assertThat;
+
+import java.io.IOException;
+import java.util.UUID;
+
+import javax.ws.rs.core.Response;
+
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Vertex;
@@ -37,15 +48,6 @@ import org.onap.aai.edges.enums.EdgeProperty;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.engines.QueryStyle;
-import javax.ws.rs.core.Response;
-import java.io.IOException;
-import java.util.UUID;
-
-import static org.hamcrest.CoreMatchers.containsString;
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.Matchers.not;
-import static org.junit.Assert.assertThat;
-
public class EdgeNotValidAnymoreTest extends AAISetup {
private HttpTestUtil testUtil;
@@ -53,7 +55,8 @@ public class EdgeNotValidAnymoreTest extends AAISetup {
@Before
public void setupData() throws IOException, AAIException {
- String cloudRegionEndpoint = "/aai/v13/cloud-infrastructure/cloud-regions/cloud-region/junit-cloud-owner-with-vlan/junit-cloud-region-with-vlan";
+ String cloudRegionEndpoint =
+ "/aai/v13/cloud-infrastructure/cloud-regions/cloud-region/junit-cloud-owner-with-vlan/junit-cloud-region-with-vlan";
String cloudRegionBody = PayloadUtil.getResourcePayload("cloud-region-with-vlan.json");
testUtil = new HttpTestUtil(QueryStyle.TRAVERSAL_URI);
@@ -62,18 +65,13 @@ public class EdgeNotValidAnymoreTest extends AAISetup {
JanusGraphTransaction transaction = AAIGraph.getInstance().getGraph().newTransaction();
GraphTraversalSource g = transaction.traversal();
- Vertex configurationVertex = g.addV()
- .property( AAIProperties.NODE_TYPE, "configuration")
- .property( "configuration-id", "ci1")
- .property( "configuration-type", "ci1")
- .property( AAIProperties.AAI_URI, "/network/configurations/configuration/ci1")
- .property(AAIProperties.SOURCE_OF_TRUTH, "JUNIT")
- .next();
+ Vertex configurationVertex = g.addV().property(AAIProperties.NODE_TYPE, "configuration")
+ .property("configuration-id", "ci1").property("configuration-type", "ci1")
+ .property(AAIProperties.AAI_URI, "/network/configurations/configuration/ci1")
+ .property(AAIProperties.SOURCE_OF_TRUTH, "JUNIT").next();
- Vertex vlanVertex = g.V()
- .has("vlan-interface", "test-vlan-interface-1")
- .has(AAIProperties.NODE_TYPE, "vlan")
- .next();
+ Vertex vlanVertex =
+ g.V().has("vlan-interface", "test-vlan-interface-1").has(AAIProperties.NODE_TYPE, "vlan").next();
Edge edge = configurationVertex.addEdge("org.onap.relationships.inventory.PartOf", vlanVertex);
addEdge(edge);
@@ -104,16 +102,13 @@ public class EdgeNotValidAnymoreTest extends AAISetup {
}
@After
- public void teardown(){
+ public void teardown() {
JanusGraph janusGraph = AAIGraph.getInstance().getGraph();
JanusGraphTransaction transaction = janusGraph.newTransaction();
GraphTraversalSource g = transaction.traversal();
- g.V()
- .has(AAIProperties.SOURCE_OF_TRUTH, "JUNIT")
- .toList()
- .forEach((edge) -> edge.remove());
+ g.V().has(AAIProperties.SOURCE_OF_TRUTH, "JUNIT").toList().forEach((edge) -> edge.remove());
transaction.commit();
}
diff --git a/aai-core/src/test/java/org/onap/aai/rest/EntitlementTest.java b/aai-core/src/test/java/org/onap/aai/rest/EntitlementTest.java
index 3559b9d6..c992a946 100644
--- a/aai-core/src/test/java/org/onap/aai/rest/EntitlementTest.java
+++ b/aai-core/src/test/java/org/onap/aai/rest/EntitlementTest.java
@@ -17,9 +17,20 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.rest;
+import static org.junit.Assert.assertEquals;
+
import com.jayway.jsonpath.JsonPath;
+
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.util.Arrays;
+import java.util.Collection;
+
+import javax.ws.rs.core.Response;
+
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -33,14 +44,6 @@ import org.onap.aai.serialization.engines.QueryStyle;
import org.skyscreamer.jsonassert.JSONAssert;
import org.springframework.test.annotation.DirtiesContext;
-import javax.ws.rs.core.Response;
-import java.io.IOException;
-import java.io.UnsupportedEncodingException;
-import java.util.Arrays;
-import java.util.Collection;
-
-import static org.junit.Assert.assertEquals;
-
@RunWith(value = Parameterized.class)
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
public class EntitlementTest extends AAISetup {
@@ -56,9 +59,7 @@ public class EntitlementTest extends AAISetup {
@Parameterized.Parameters(name = "QueryStyle.{0}")
public static Collection<Object[]> data() {
- return Arrays.asList(new Object[][]{
- {QueryStyle.TRAVERSAL_URI}
- });
+ return Arrays.asList(new Object[][] {{QueryStyle.TRAVERSAL_URI}});
}
@Before
@@ -72,7 +73,7 @@ public class EntitlementTest extends AAISetup {
public void testPutGenericVnfAndThenInsertEntitlement() throws IOException, AAIException {
String entitlementPayload = PayloadUtil.getResourcePayload("entitlement.json");
String entitlementUri = "/aai/v14/network/generic-vnfs/generic-vnf/vnf1/entitlements/entitlement/g1/r1";
- Response response = httpTestUtil.doPut(vnfUri, vnfPayload);
+ Response response = httpTestUtil.doPut(vnfUri, vnfPayload);
assertEquals("Expected the Generic Vnf to be created", 201, response.getStatus());
response = httpTestUtil.doGet(vnfUri);
@@ -80,7 +81,7 @@ public class EntitlementTest extends AAISetup {
String jsonResponse = response.getEntity().toString();
JSONAssert.assertEquals(vnfPayload, jsonResponse, false);
- response = httpTestUtil.doPut(entitlementUri, entitlementPayload);
+ response = httpTestUtil.doPut(entitlementUri, entitlementPayload);
assertEquals("Expected the Entitlement to be created", 201, response.getStatus());
}
diff --git a/aai-core/src/test/java/org/onap/aai/rest/GenericVnfLInterfaceTest.java b/aai-core/src/test/java/org/onap/aai/rest/GenericVnfLInterfaceTest.java
index 60519b1a..d6202f24 100644
--- a/aai-core/src/test/java/org/onap/aai/rest/GenericVnfLInterfaceTest.java
+++ b/aai-core/src/test/java/org/onap/aai/rest/GenericVnfLInterfaceTest.java
@@ -17,8 +17,19 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.rest;
+import static org.junit.Assert.assertEquals;
+
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.ws.rs.core.Response;
+
import org.json.JSONObject;
import org.junit.After;
import org.junit.Before;
@@ -32,35 +43,23 @@ import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.engines.QueryStyle;
import org.skyscreamer.jsonassert.JSONAssert;
import org.springframework.test.annotation.DirtiesContext;
-import javax.ws.rs.core.Response;
-import java.io.IOException;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Map;
-
-import static org.junit.Assert.assertEquals;
@RunWith(value = Parameterized.class)
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
public class GenericVnfLInterfaceTest extends AAISetup {
private HttpTestUtil httpTestUtil;
-
@Parameterized.Parameter(value = 0)
public QueryStyle queryStyle;
@Parameterized.Parameters(name = "QueryStyle.{0}")
public static Collection<Object[]> data() {
- return Arrays.asList(new Object[][]{
- {QueryStyle.TRAVERSAL},
- {QueryStyle.TRAVERSAL_URI}
- });
+ return Arrays.asList(new Object[][] {{QueryStyle.TRAVERSAL}, {QueryStyle.TRAVERSAL_URI}});
}
@Before
- public void setUp(){
+ public void setUp() {
httpTestUtil = new HttpTestUtil(queryStyle);
}
diff --git a/aai-core/src/test/java/org/onap/aai/rest/HPACapabilityTest.java b/aai-core/src/test/java/org/onap/aai/rest/HPACapabilityTest.java
index 85eb0b00..a742313a 100644
--- a/aai-core/src/test/java/org/onap/aai/rest/HPACapabilityTest.java
+++ b/aai-core/src/test/java/org/onap/aai/rest/HPACapabilityTest.java
@@ -17,11 +17,19 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.rest;
+import static org.junit.Assert.assertEquals;
+
import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
import com.jayway.jsonpath.JsonPath;
+
+import java.util.*;
+
+import javax.ws.rs.core.Response;
+
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
@@ -33,11 +41,6 @@ import org.onap.aai.PayloadUtil;
import org.onap.aai.serialization.engines.QueryStyle;
import org.skyscreamer.jsonassert.JSONAssert;
-import javax.ws.rs.core.Response;
-import java.util.*;
-
-import static org.junit.Assert.assertEquals;
-
@Ignore
@RunWith(AAIJunitRunner.class)
public class HPACapabilityTest {
@@ -51,9 +54,7 @@ public class HPACapabilityTest {
@Parameterized.Parameters(name = "QueryStyle.{0}")
public static Collection<Object[]> data() {
- return Arrays.asList(new Object[][]{
- {QueryStyle.TRAVERSAL}
- });
+ return Arrays.asList(new Object[][] {{QueryStyle.TRAVERSAL}});
}
@Before
@@ -82,9 +83,7 @@ public class HPACapabilityTest {
String cloudRegionPayload = PayloadUtil.getTemplatePayload("hpa.json", templateValuesMap);
String cloudRegionUri = String.format("/aai/v14/cloud-infrastructure/cloud-regions/cloud-region/%s/%s",
- templateValuesMap.get("cloud-owner"),
- templateValuesMap.get("cloud-region-id")
- );
+ templateValuesMap.get("cloud-owner"), templateValuesMap.get("cloud-region-id"));
Response response = httpTestUtil.doPut(cloudRegionUri, cloudRegionPayload);
assertEquals("Expected the cloud region to be created", 201, response.getStatus());
@@ -141,9 +140,9 @@ public class HPACapabilityTest {
System.out.println("#########################Flavor Response#########################");
String responseStr = response.getEntity().toString();
- List<String> capabilityIds = JsonPath.read(responseStr,
- "$.hpa-capabilities.hpa-capability[*].hpa-capability-id");
- for(String capabilityId : capabilityIds) {
+ List<String> capabilityIds =
+ JsonPath.read(responseStr, "$.hpa-capabilities.hpa-capability[*].hpa-capability-id");
+ for (String capabilityId : capabilityIds) {
deleteHPACapability(flavorUri, capabilityId);
}
diff --git a/aai-core/src/test/java/org/onap/aai/rest/ModelElementTest.java b/aai-core/src/test/java/org/onap/aai/rest/ModelElementTest.java
index d808c993..a5bcb2e5 100644
--- a/aai-core/src/test/java/org/onap/aai/rest/ModelElementTest.java
+++ b/aai-core/src/test/java/org/onap/aai/rest/ModelElementTest.java
@@ -17,9 +17,20 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.rest;
+import static org.junit.Assert.assertEquals;
+
import com.jayway.jsonpath.JsonPath;
+
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.util.Arrays;
+import java.util.Collection;
+
+import javax.ws.rs.core.Response;
+
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -33,14 +44,6 @@ import org.onap.aai.serialization.engines.QueryStyle;
import org.skyscreamer.jsonassert.JSONAssert;
import org.springframework.test.annotation.DirtiesContext;
-import javax.ws.rs.core.Response;
-import java.io.IOException;
-import java.io.UnsupportedEncodingException;
-import java.util.Arrays;
-import java.util.Collection;
-
-import static org.junit.Assert.assertEquals;
-
@RunWith(value = Parameterized.class)
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
public class ModelElementTest extends AAISetup {
@@ -58,9 +61,7 @@ public class ModelElementTest extends AAISetup {
@Parameterized.Parameters(name = "QueryStyle.{0}")
public static Collection<Object[]> data() {
- return Arrays.asList(new Object[][]{
- {QueryStyle.TRAVERSAL_URI}
- });
+ return Arrays.asList(new Object[][] {{QueryStyle.TRAVERSAL_URI}});
}
@Before
@@ -69,12 +70,13 @@ public class ModelElementTest extends AAISetup {
modelPayload = PayloadUtil.getResourcePayload("model.json");
modelElementPayload = PayloadUtil.getResourcePayload("model-element.json");
modelUri = "/aai/v14/service-design-and-creation/models/model/24c04fc5-f3f8-43ec-8792-c6f940638676-test1";
- modelElementUri = "/aai/v14/service-design-and-creation/models/model/24c04fc5-f3f8-43ec-8792-c6f940638676-test1/model-vers/model-ver/0c4c59f0-9864-43ca-b0c2-ca38746b72a5-test1/model-elements/model-element/0dc2b8b6-af8d-4213-970b-7861a603fc86-test1/model-constraints/model-constraint/782ba24a-28ab-4fd0-8e69-da10cc5373f3-test1/constrained-element-sets/constrained-element-set/a33e65c3-1198-4d4c-9799-2b521e4c4212-test1/element-choice-sets/element-choice-set/7df27a94-06c8-46ef-9fc2-5900d8cffbb0-test1/model-elements/model-element/acf8b6cf-e051-4c1b-bcad-b24792f826cf-test1";
+ modelElementUri =
+ "/aai/v14/service-design-and-creation/models/model/24c04fc5-f3f8-43ec-8792-c6f940638676-test1/model-vers/model-ver/0c4c59f0-9864-43ca-b0c2-ca38746b72a5-test1/model-elements/model-element/0dc2b8b6-af8d-4213-970b-7861a603fc86-test1/model-constraints/model-constraint/782ba24a-28ab-4fd0-8e69-da10cc5373f3-test1/constrained-element-sets/constrained-element-set/a33e65c3-1198-4d4c-9799-2b521e4c4212-test1/element-choice-sets/element-choice-set/7df27a94-06c8-46ef-9fc2-5900d8cffbb0-test1/model-elements/model-element/acf8b6cf-e051-4c1b-bcad-b24792f826cf-test1";
}
@Test
public void testPutModelAndThenModelElementAndItShouldSucceed() throws IOException, AAIException {
- Response response = httpTestUtil.doPut(modelUri, modelPayload);
+ Response response = httpTestUtil.doPut(modelUri, modelPayload);
assertEquals("Expected the cloud region to be created", 201, response.getStatus());
response = httpTestUtil.doGet(modelUri);
@@ -82,7 +84,7 @@ public class ModelElementTest extends AAISetup {
String jsonResponse = response.getEntity().toString();
JSONAssert.assertEquals(modelPayload, jsonResponse, false);
- response = httpTestUtil.doPut(modelElementUri, modelElementPayload);
+ response = httpTestUtil.doPut(modelElementUri, modelElementPayload);
assertEquals("Expected the cloud region to be created", 201, response.getStatus());
}
diff --git a/aai-core/src/test/java/org/onap/aai/rest/PrivateEdgeIntegrationOldClientTest.java b/aai-core/src/test/java/org/onap/aai/rest/PrivateEdgeIntegrationOldClientTest.java
index a3520f56..0232c5aa 100644
--- a/aai-core/src/test/java/org/onap/aai/rest/PrivateEdgeIntegrationOldClientTest.java
+++ b/aai-core/src/test/java/org/onap/aai/rest/PrivateEdgeIntegrationOldClientTest.java
@@ -17,10 +17,21 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.rest;
+import static org.hamcrest.CoreMatchers.containsString;
+import static org.hamcrest.CoreMatchers.not;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.core.Is.is;
+import static org.junit.Assert.assertNotNull;
import com.jayway.jsonpath.JsonPath;
+
+import java.util.*;
+
+import javax.ws.rs.core.Response;
+
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.junit.Before;
import org.junit.Test;
@@ -34,15 +45,6 @@ import org.onap.aai.serialization.engines.QueryStyle;
import org.onap.aai.setup.SchemaVersion;
import org.springframework.test.annotation.DirtiesContext;
-import javax.ws.rs.core.Response;
-import java.util.*;
-
-import static org.hamcrest.CoreMatchers.containsString;
-import static org.hamcrest.CoreMatchers.not;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.core.Is.is;
-import static org.junit.Assert.assertNotNull;
-
@RunWith(value = Parameterized.class)
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
public class PrivateEdgeIntegrationOldClientTest extends AAISetup {
@@ -53,7 +55,6 @@ public class PrivateEdgeIntegrationOldClientTest extends AAISetup {
private String modelId;
private String modelVerId;
-
@Parameterized.Parameter(value = 0)
public QueryStyle queryStyle;
@@ -62,10 +63,8 @@ public class PrivateEdgeIntegrationOldClientTest extends AAISetup {
@Parameterized.Parameters(name = "QueryStyle.{0} {1}")
public static Collection<Object[]> data() {
- return Arrays.asList(new Object[][]{
- {QueryStyle.TRAVERSAL, new SchemaVersion("v14")},
- {QueryStyle.TRAVERSAL_URI, new SchemaVersion("v14")},
- });
+ return Arrays.asList(new Object[][] {{QueryStyle.TRAVERSAL, new SchemaVersion("v14")},
+ {QueryStyle.TRAVERSAL_URI, new SchemaVersion("v14")},});
}
@Before
@@ -79,9 +78,10 @@ public class PrivateEdgeIntegrationOldClientTest extends AAISetup {
Map<String, String> modelTemplateValues = new HashMap<>();
modelTemplateValues.put("model-invariant-id", modelId);
- String modelPayload = PayloadUtil.getTemplatePayload("model.json", modelTemplateValues);
+ String modelPayload = PayloadUtil.getTemplatePayload("model.json", modelTemplateValues);
- Response response = httpTestUtil.doPut("/aai/"+version.toString()+"/service-design-and-creation/models/model/" + modelId, modelPayload);
+ Response response = httpTestUtil.doPut(
+ "/aai/" + version.toString() + "/service-design-and-creation/models/model/" + modelId, modelPayload);
assertNotNull(response);
assertThat("Model was not successfully created", response.getStatus(), is(201));
@@ -91,15 +91,17 @@ public class PrivateEdgeIntegrationOldClientTest extends AAISetup {
modelVersionTemplateValues.put("model-name", "some-model");
modelVersionTemplateValues.put("model-version", "testValue");
- String modelVersionPayload = PayloadUtil.getTemplatePayload("model-ver.json", modelVersionTemplateValues);
+ String modelVersionPayload = PayloadUtil.getTemplatePayload("model-ver.json", modelVersionTemplateValues);
- response = httpTestUtil.doPut("/aai/"+version.toString()+"/service-design-and-creation/models/model/" + modelId + "/model-vers/model-ver/" + modelVerId, modelVersionPayload);
+ response = httpTestUtil.doPut("/aai/" + version.toString() + "/service-design-and-creation/models/model/"
+ + modelId + "/model-vers/model-ver/" + modelVerId, modelVersionPayload);
assertNotNull(response);
assertThat("Model was not successfully created", response.getStatus(), is(201));
}
@Test
- public void testPutGenericVnfWithModelInfoToMatchExistingModelAndCheckIfPrivateEdgeCreatedAndDoGetOnOldModelAndMakeSureNoRelationship() throws Exception {
+ public void testPutGenericVnfWithModelInfoToMatchExistingModelAndCheckIfPrivateEdgeCreatedAndDoGetOnOldModelAndMakeSureNoRelationship()
+ throws Exception {
Map<String, String> genericVnfHashMap = new HashMap<>();
String genericVnf = "test-generic-" + UUID.randomUUID().toString();
@@ -109,16 +111,18 @@ public class PrivateEdgeIntegrationOldClientTest extends AAISetup {
genericVnfHashMap.put("model-version-id", modelVerId);
String genericVnfPayload = PayloadUtil.getTemplatePayload("generic-vnf.json", genericVnfHashMap);
- Response response = httpTestUtil.doPut("/aai/"+version.toString()+"/network/generic-vnfs/generic-vnf/" + genericVnf, genericVnfPayload);
+ Response response = httpTestUtil.doPut(
+ "/aai/" + version.toString() + "/network/generic-vnfs/generic-vnf/" + genericVnf, genericVnfPayload);
assertNotNull("Response returned null", response);
assertThat("Check the generic vnf is created", response.getStatus(), is(201));
- response = httpTestUtil.doGet("/aai/"+version.toString()+"/network/generic-vnfs/generic-vnf/" + genericVnf);
+ response = httpTestUtil.doGet("/aai/" + version.toString() + "/network/generic-vnfs/generic-vnf/" + genericVnf);
assertNotNull("Response returned null", response);
assertThat("Check the generic vnf is created", response.getStatus(), is(200));
assertThat(response.getEntity().toString(), not(containsString("relationship-list")));
- List<Edge> edges = AAIGraph.getInstance().getGraph().newTransaction().traversal().E().has("private", true).toList();
+ List<Edge> edges =
+ AAIGraph.getInstance().getGraph().newTransaction().traversal().E().has("private", true).toList();
assertNotNull("List of edges should not be null", edges);
assertThat(edges.size(), is(1));
Edge oldEdge = edges.get(0);
@@ -130,7 +134,8 @@ public class PrivateEdgeIntegrationOldClientTest extends AAISetup {
assertThat(response.getEntity().toString(), not(containsString("relationship-list")));
String resourceVersion = JsonPath.read(response.getEntity().toString(), "$.resource-version");
- response = httpTestUtil.doDelete("/aai/"+version.toString()+"/network/generic-vnfs/generic-vnf/" + genericVnf, resourceVersion);
+ response = httpTestUtil.doDelete(
+ "/aai/" + version.toString() + "/network/generic-vnfs/generic-vnf/" + genericVnf, resourceVersion);
assertNotNull("Response returned null", response);
assertThat("Check the generic vnf is deleted", response.getStatus(), is(204));
diff --git a/aai-core/src/test/java/org/onap/aai/rest/PrivateEdgeIntegrationTest.java b/aai-core/src/test/java/org/onap/aai/rest/PrivateEdgeIntegrationTest.java
index b8709bdb..d3452153 100644
--- a/aai-core/src/test/java/org/onap/aai/rest/PrivateEdgeIntegrationTest.java
+++ b/aai-core/src/test/java/org/onap/aai/rest/PrivateEdgeIntegrationTest.java
@@ -17,11 +17,26 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.rest;
+import static junit.framework.TestCase.fail;
+import static org.hamcrest.CoreMatchers.containsString;
+import static org.hamcrest.CoreMatchers.not;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.core.Is.is;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertNotNull;
+
import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
import com.jayway.jsonpath.JsonPath;
+
+import java.util.*;
+
+import javax.ws.rs.core.Response;
+
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.janusgraph.core.JanusGraphTransaction;
@@ -37,18 +52,6 @@ import org.onap.aai.dbmap.AAIGraph;
import org.onap.aai.serialization.engines.QueryStyle;
import org.onap.aai.setup.SchemaVersion;
-import javax.ws.rs.core.Response;
-import java.util.*;
-
-import static junit.framework.TestCase.fail;
-import static org.hamcrest.CoreMatchers.containsString;
-import static org.hamcrest.CoreMatchers.not;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.core.Is.is;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertNotNull;
-
@RunWith(value = Parameterized.class)
public class PrivateEdgeIntegrationTest extends AAISetup {
@@ -67,18 +70,12 @@ public class PrivateEdgeIntegrationTest extends AAISetup {
@Parameterized.Parameters(name = "QueryStyle.{0} Version.{1}")
public static Collection<Object[]> data() {
- return Arrays.asList(new Object[][]{
- {QueryStyle.TRAVERSAL, new SchemaVersion("v10")},
- {QueryStyle.TRAVERSAL_URI, new SchemaVersion("v10")},
- {QueryStyle.TRAVERSAL, new SchemaVersion("v11")},
- {QueryStyle.TRAVERSAL_URI, new SchemaVersion("v11")},
- {QueryStyle.TRAVERSAL, new SchemaVersion("v12")},
- {QueryStyle.TRAVERSAL_URI, new SchemaVersion("v12")},
- {QueryStyle.TRAVERSAL, new SchemaVersion("v13")},
- {QueryStyle.TRAVERSAL_URI, new SchemaVersion("v13")},
- {QueryStyle.TRAVERSAL, new SchemaVersion("v14")},
- {QueryStyle.TRAVERSAL_URI, new SchemaVersion("v14")}
- });
+ return Arrays.asList(new Object[][] {{QueryStyle.TRAVERSAL, new SchemaVersion("v10")},
+ {QueryStyle.TRAVERSAL_URI, new SchemaVersion("v10")}, {QueryStyle.TRAVERSAL, new SchemaVersion("v11")},
+ {QueryStyle.TRAVERSAL_URI, new SchemaVersion("v11")}, {QueryStyle.TRAVERSAL, new SchemaVersion("v12")},
+ {QueryStyle.TRAVERSAL_URI, new SchemaVersion("v12")}, {QueryStyle.TRAVERSAL, new SchemaVersion("v13")},
+ {QueryStyle.TRAVERSAL_URI, new SchemaVersion("v13")}, {QueryStyle.TRAVERSAL, new SchemaVersion("v14")},
+ {QueryStyle.TRAVERSAL_URI, new SchemaVersion("v14")}});
}
@Before
@@ -96,9 +93,10 @@ public class PrivateEdgeIntegrationTest extends AAISetup {
Map<String, String> modelTemplateValues = new HashMap<>();
modelTemplateValues.put("model-invariant-id", modelId);
- String modelPayload = PayloadUtil.getTemplatePayload("model.json", modelTemplateValues);
+ String modelPayload = PayloadUtil.getTemplatePayload("model.json", modelTemplateValues);
- Response response = httpTestUtil.doPut("/aai/"+version.toString()+"/service-design-and-creation/models/model/" + modelId, modelPayload);
+ Response response = httpTestUtil.doPut(
+ "/aai/" + version.toString() + "/service-design-and-creation/models/model/" + modelId, modelPayload);
assertNotNull(response);
assertThat("Model was not successfully created", response.getStatus(), is(201));
@@ -108,9 +106,10 @@ public class PrivateEdgeIntegrationTest extends AAISetup {
modelVersionTemplateValues.put("model-name", "some-model");
modelVersionTemplateValues.put("model-version", "testValue");
- String modelVersionPayload = PayloadUtil.getTemplatePayload("model-ver.json", modelVersionTemplateValues);
+ String modelVersionPayload = PayloadUtil.getTemplatePayload("model-ver.json", modelVersionTemplateValues);
- response = httpTestUtil.doPut("/aai/"+version.toString()+"/service-design-and-creation/models/model/" + modelId + "/model-vers/model-ver/" + modelVerId, modelVersionPayload);
+ response = httpTestUtil.doPut("/aai/" + version.toString() + "/service-design-and-creation/models/model/"
+ + modelId + "/model-vers/model-ver/" + modelVerId, modelVersionPayload);
assertNotNull(response);
assertThat("Model was not successfully created", response.getStatus(), is(201));
}
@@ -126,23 +125,26 @@ public class PrivateEdgeIntegrationTest extends AAISetup {
genericVnfHashMap.put("model-version-id", modelVerId);
String genericVnfPayload = PayloadUtil.getTemplatePayload("generic-vnf.json", genericVnfHashMap);
- Response response = httpTestUtil.doPut("/aai/"+version.toString()+"/network/generic-vnfs/generic-vnf/" + genericVnf, genericVnfPayload);
+ Response response = httpTestUtil.doPut(
+ "/aai/" + version.toString() + "/network/generic-vnfs/generic-vnf/" + genericVnf, genericVnfPayload);
assertNotNull("Response returned null", response);
assertThat("Check the generic vnf is created", response.getStatus(), is(201));
- List<Edge> edges = AAIGraph.getInstance().getGraph().newTransaction().traversal().E().has("private", true).toList();
+ List<Edge> edges =
+ AAIGraph.getInstance().getGraph().newTransaction().traversal().E().has("private", true).toList();
assertNotNull("List of edges should not be null", edges);
assertThat(edges.size(), is(1));
Edge oldEdge = edges.get(0);
assertNotNull(oldEdge);
- response = httpTestUtil.doGet("/aai/"+version.toString()+"/network/generic-vnfs/generic-vnf/" + genericVnf);
+ response = httpTestUtil.doGet("/aai/" + version.toString() + "/network/generic-vnfs/generic-vnf/" + genericVnf);
assertNotNull("Response returned null", response);
assertThat("Check the generic vnf is created", response.getStatus(), is(200));
assertThat(response.getEntity().toString(), not(containsString("relationship-list")));
String resourceVersion = JsonPath.read(response.getEntity().toString(), "$.resource-version");
- response = httpTestUtil.doDelete("/aai/"+version.toString()+"/network/generic-vnfs/generic-vnf/" + genericVnf, resourceVersion);
+ response = httpTestUtil.doDelete(
+ "/aai/" + version.toString() + "/network/generic-vnfs/generic-vnf/" + genericVnf, resourceVersion);
assertNotNull("Response returned null", response);
assertThat("Check the generic vnf is deleted", response.getStatus(), is(204));
@@ -152,7 +154,8 @@ public class PrivateEdgeIntegrationTest extends AAISetup {
}
@Test
- public void testPutGenericVnfWithModelInfoToMatchExistingModelAndDoAnotherPutAndDontIncludeModelInfoAndPrivateEdgeShouldBeDeleted() throws Exception {
+ public void testPutGenericVnfWithModelInfoToMatchExistingModelAndDoAnotherPutAndDontIncludeModelInfoAndPrivateEdgeShouldBeDeleted()
+ throws Exception {
Map<String, String> genericVnfHashMap = new HashMap<>();
String genericVnf = "test-generic-" + UUID.randomUUID().toString();
@@ -162,34 +165,34 @@ public class PrivateEdgeIntegrationTest extends AAISetup {
genericVnfHashMap.put("model-version-id", modelVerId);
String genericVnfPayload = PayloadUtil.getTemplatePayload("generic-vnf.json", genericVnfHashMap);
- Response response = httpTestUtil.doPut("/aai/"+version.toString()+"/network/generic-vnfs/generic-vnf/" + genericVnf, genericVnfPayload);
+ Response response = httpTestUtil.doPut(
+ "/aai/" + version.toString() + "/network/generic-vnfs/generic-vnf/" + genericVnf, genericVnfPayload);
assertNotNull("Response returned null", response);
assertThat("Check the generic vnf is created", response.getStatus(), is(201));
- response = httpTestUtil.doGet("/aai/"+version.toString()+"/network/generic-vnfs/generic-vnf/" + genericVnf);
+ response = httpTestUtil.doGet("/aai/" + version.toString() + "/network/generic-vnfs/generic-vnf/" + genericVnf);
assertNotNull("Response returned null", response);
assertThat("Check the generic vnf is created", response.getStatus(), is(200));
assertThat(response.getEntity().toString(), not(containsString("relationship-list")));
- List<Edge> edges = AAIGraph.getInstance().getGraph().newTransaction().traversal().E().has("private", true).toList();
+ List<Edge> edges =
+ AAIGraph.getInstance().getGraph().newTransaction().traversal().E().has("private", true).toList();
assertNotNull("List of edges should not be null", edges);
assertThat(edges.size(), is(1));
Edge oldEdge = edges.get(0);
assertNotNull(oldEdge);
String resourceVersion = JsonPath.read(response.getEntity().toString(), "$.resource-version");
- String newGenericVnfPayload = "{\n" +
- " \"vnf-id\": \"" + genericVnf+ "\",\n" +
- " \"vnf-type\": \"someval\",\n" +
- " \"vnf-name\": \"someval\"\n," +
- " \"resource-version\": \"" + resourceVersion + "\"" +
- "}";
-
- response = httpTestUtil.doPut("/aai/"+version.toString()+"/network/generic-vnfs/generic-vnf/" + genericVnf, newGenericVnfPayload);
+ String newGenericVnfPayload = "{\n" + " \"vnf-id\": \"" + genericVnf + "\",\n"
+ + " \"vnf-type\": \"someval\",\n" + " \"vnf-name\": \"someval\"\n," + " \"resource-version\": \""
+ + resourceVersion + "\"" + "}";
+
+ response = httpTestUtil.doPut("/aai/" + version.toString() + "/network/generic-vnfs/generic-vnf/" + genericVnf,
+ newGenericVnfPayload);
assertNotNull("Response returned from second put is null", response);
assertThat("Check the generic vnf is updated", response.getStatus(), is(200));
- response = httpTestUtil.doGet("/aai/"+version.toString()+"/network/generic-vnfs/generic-vnf/" + genericVnf);
+ response = httpTestUtil.doGet("/aai/" + version.toString() + "/network/generic-vnfs/generic-vnf/" + genericVnf);
assertNotNull("Response returned from second put is null", response);
assertThat("Check the generic vnf is updated", response.getStatus(), is(200));
@@ -198,7 +201,8 @@ public class PrivateEdgeIntegrationTest extends AAISetup {
assertThat("Expected the edges to be zero since updated with no model info", edges.size(), is(0));
resourceVersion = JsonPath.read(response.getEntity().toString(), "$.resource-version");
- response = httpTestUtil.doDelete("/aai/"+version.toString()+"/network/generic-vnfs/generic-vnf/" + genericVnf, resourceVersion);
+ response = httpTestUtil.doDelete(
+ "/aai/" + version.toString() + "/network/generic-vnfs/generic-vnf/" + genericVnf, resourceVersion);
assertNotNull("Response returned null", response);
assertThat("Check the generic vnf is deleted", response.getStatus(), is(204));
@@ -208,7 +212,8 @@ public class PrivateEdgeIntegrationTest extends AAISetup {
}
@Test
- public void testPutGenericVnfWithModelInfoToMatchExistingModelAndCheckIfPrivateEdgeCreatedAndAlsoDoAnotherPutSameDataAndMakeSureEdgeIsStillThere() throws Exception {
+ public void testPutGenericVnfWithModelInfoToMatchExistingModelAndCheckIfPrivateEdgeCreatedAndAlsoDoAnotherPutSameDataAndMakeSureEdgeIsStillThere()
+ throws Exception {
Map<String, String> genericVnfHashMap = new HashMap<>();
String genericVnf = "test-generic-" + UUID.randomUUID().toString();
@@ -217,16 +222,18 @@ public class PrivateEdgeIntegrationTest extends AAISetup {
genericVnfHashMap.put("model-version-id", modelVerId);
String genericVnfPayload = PayloadUtil.getTemplatePayload("generic-vnf.json", genericVnfHashMap);
- Response response = httpTestUtil.doPut("/aai/"+version.toString()+"/network/generic-vnfs/generic-vnf/" + genericVnf, genericVnfPayload);
+ Response response = httpTestUtil.doPut(
+ "/aai/" + version.toString() + "/network/generic-vnfs/generic-vnf/" + genericVnf, genericVnfPayload);
assertNotNull("Response returned null", response);
assertThat("Check the generic vnf is created", response.getStatus(), is(201));
- response = httpTestUtil.doGet("/aai/"+version.toString()+"/network/generic-vnfs/generic-vnf/" + genericVnf);
+ response = httpTestUtil.doGet("/aai/" + version.toString() + "/network/generic-vnfs/generic-vnf/" + genericVnf);
assertNotNull("Response returned null", response);
assertThat("Check the generic vnf is created", response.getStatus(), is(200));
assertThat(response.getEntity().toString(), not(containsString("relationship-list")));
- List<Edge> edges = AAIGraph.getInstance().getGraph().newTransaction().traversal().E().has("private", true).toList();
+ List<Edge> edges =
+ AAIGraph.getInstance().getGraph().newTransaction().traversal().E().has("private", true).toList();
assertNotNull("List of edges should not be null", edges);
assertThat(edges.size(), is(1));
Edge oldEdge = edges.get(0);
@@ -234,13 +241,15 @@ public class PrivateEdgeIntegrationTest extends AAISetup {
String resourceVersion = JsonPath.read(response.getEntity().toString(), "$.resource-version");
genericVnfHashMap.put("resource-version", resourceVersion);
- String genericVnfPayloadWithResource = PayloadUtil.getTemplatePayload("generic-vnf-resource.json", genericVnfHashMap);
+ String genericVnfPayloadWithResource =
+ PayloadUtil.getTemplatePayload("generic-vnf-resource.json", genericVnfHashMap);
- response = httpTestUtil.doPut("/aai/"+version.toString()+"/network/generic-vnfs/generic-vnf/" + genericVnf, genericVnfPayloadWithResource);
+ response = httpTestUtil.doPut("/aai/" + version.toString() + "/network/generic-vnfs/generic-vnf/" + genericVnf,
+ genericVnfPayloadWithResource);
assertNotNull("Response returned null", response);
assertThat("Check the generic vnf is updated", response.getStatus(), is(200));
- response = httpTestUtil.doGet("/aai/"+version.toString()+"/network/generic-vnfs/generic-vnf/" + genericVnf);
+ response = httpTestUtil.doGet("/aai/" + version.toString() + "/network/generic-vnfs/generic-vnf/" + genericVnf);
assertNotNull("Response returned null", response);
assertThat("Check the generic vnf is created", response.getStatus(), is(200));
assertThat(response.getEntity().toString(), not(containsString("relationship-list")));
@@ -253,7 +262,8 @@ public class PrivateEdgeIntegrationTest extends AAISetup {
assertNotNull(newEdge);
assertEquals(oldEdge, newEdge);
- response = httpTestUtil.doDelete("/aai/"+version.toString()+"/network/generic-vnfs/generic-vnf/" + genericVnf, resourceVersion);
+ response = httpTestUtil.doDelete(
+ "/aai/" + version.toString() + "/network/generic-vnfs/generic-vnf/" + genericVnf, resourceVersion);
assertNotNull("Response returned null", response);
assertThat("Check the generic vnf is deleted", response.getStatus(), is(204));
@@ -272,7 +282,8 @@ public class PrivateEdgeIntegrationTest extends AAISetup {
genericVnfHashMap.put("model-version-id", "random-wrong-model-ver");
String genericVnfPayload = PayloadUtil.getTemplatePayload("generic-vnf.json", genericVnfHashMap);
- Response response = httpTestUtil.doPut("/aai/"+version.toString()+"/network/generic-vnfs/generic-vnf/" + genericVnf, genericVnfPayload);
+ Response response = httpTestUtil.doPut(
+ "/aai/" + version.toString() + "/network/generic-vnfs/generic-vnf/" + genericVnf, genericVnfPayload);
assertNotNull("Response returned null", response);
String body = response.getEntity().toString();
@@ -286,14 +297,11 @@ public class PrivateEdgeIntegrationTest extends AAISetup {
public void testPutGenericVnfWithModelMissingPartOfKeyReturnsBadRequest() throws Exception {
String genericVnf = "test-generic-" + UUID.randomUUID().toString();
- String genericVnfPayload = "{\n" +
- " \"vnf-id\": \"" + genericVnf + "\",\n" +
- " \"vnf-type\": \"someval\",\n" +
- " \"vnf-name\": \"someval\",\n" +
- " \"model-invariant-id\": \"some-model\"\n" +
- "}";
-
- Response response = httpTestUtil.doPut("/aai/"+version.toString()+"/network/generic-vnfs/generic-vnf/" + genericVnf, genericVnfPayload);
+ String genericVnfPayload = "{\n" + " \"vnf-id\": \"" + genericVnf + "\",\n" + " \"vnf-type\": \"someval\",\n"
+ + " \"vnf-name\": \"someval\",\n" + " \"model-invariant-id\": \"some-model\"\n" + "}";
+
+ Response response = httpTestUtil.doPut(
+ "/aai/" + version.toString() + "/network/generic-vnfs/generic-vnf/" + genericVnf, genericVnfPayload);
assertNotNull("Response returned null", response);
String body = response.getEntity().toString();
@@ -303,7 +311,8 @@ public class PrivateEdgeIntegrationTest extends AAISetup {
}
@Test
- public void testPutGenericVnfWithModelInfoToMatchExistingModelAndDeleteModelVerAndCheckIfPreventDeleteFailsWithBadRequest() throws Exception {
+ public void testPutGenericVnfWithModelInfoToMatchExistingModelAndDeleteModelVerAndCheckIfPreventDeleteFailsWithBadRequest()
+ throws Exception {
Map<String, String> genericVnfHashMap = new HashMap<>();
String genericVnf = "test-generic-" + UUID.randomUUID().toString();
@@ -313,28 +322,34 @@ public class PrivateEdgeIntegrationTest extends AAISetup {
genericVnfHashMap.put("model-version-id", modelVerId);
String genericVnfPayload = PayloadUtil.getTemplatePayload("generic-vnf.json", genericVnfHashMap);
- Response response = httpTestUtil.doPut("/aai/"+version.toString()+"/network/generic-vnfs/generic-vnf/" + genericVnf, genericVnfPayload);
+ Response response = httpTestUtil.doPut(
+ "/aai/" + version.toString() + "/network/generic-vnfs/generic-vnf/" + genericVnf, genericVnfPayload);
assertNotNull("Response returned null", response);
assertThat("Check the generic vnf is created", response.getStatus(), is(201));
- List<Edge> edges = AAIGraph.getInstance().getGraph().newTransaction().traversal().E().has("private", true).toList();
+ List<Edge> edges =
+ AAIGraph.getInstance().getGraph().newTransaction().traversal().E().has("private", true).toList();
assertNotNull("List of edges should not be null", edges);
assertThat(edges.size(), is(1));
Edge oldEdge = edges.get(0);
assertNotNull(oldEdge);
- response = httpTestUtil.doGet("/aai/"+version.toString()+"/service-design-and-creation/models/model/" + modelId + "/model-vers/model-ver/" + modelVerId);
+ response = httpTestUtil.doGet("/aai/" + version.toString() + "/service-design-and-creation/models/model/"
+ + modelId + "/model-vers/model-ver/" + modelVerId);
assertNotNull(response);
assertThat(response.getStatus(), is(200));
String resourceVersion = JsonPath.read(response.getEntity().toString(), "$.resource-version");
- response = httpTestUtil.doDelete("/aai/"+version.toString()+"/service-design-and-creation/models/model/" + modelId + "/model-vers/model-ver/" + modelVerId, resourceVersion);
+ response = httpTestUtil.doDelete("/aai/" + version.toString() + "/service-design-and-creation/models/model/"
+ + modelId + "/model-vers/model-ver/" + modelVerId, resourceVersion);
assertNotNull("Response returned null", response);
assertThat("Check the generic vnf is deleted", response.getStatus(), is(400));
- assertThat(response.getEntity().toString(), containsString(" Please clean up references from the following types [generic-vnf]"));
+ assertThat(response.getEntity().toString(),
+ containsString(" Please clean up references from the following types [generic-vnf]"));
}
@Test
- public void testPutWithGenericVnfToExistingModelAndUpdateWithNewModelInfoAndEdgeToOldModelShouldBeDeletedAndNewEdgeToNewModelShouldBeCreated() throws Exception {
+ public void testPutWithGenericVnfToExistingModelAndUpdateWithNewModelInfoAndEdgeToOldModelShouldBeDeletedAndNewEdgeToNewModelShouldBeCreated()
+ throws Exception {
Map<String, String> genericVnfHashMap = new HashMap<>();
String genericVnf = "test-generic-" + UUID.randomUUID().toString();
@@ -344,17 +359,19 @@ public class PrivateEdgeIntegrationTest extends AAISetup {
genericVnfHashMap.put("model-version-id", modelVerId);
String genericVnfPayload = PayloadUtil.getTemplatePayload("generic-vnf.json", genericVnfHashMap);
- Response response = httpTestUtil.doPut("/aai/"+version.toString()+"/network/generic-vnfs/generic-vnf/" + genericVnf, genericVnfPayload);
+ Response response = httpTestUtil.doPut(
+ "/aai/" + version.toString() + "/network/generic-vnfs/generic-vnf/" + genericVnf, genericVnfPayload);
assertNotNull("Response returned null", response);
assertThat("Check the generic vnf is created", response.getStatus(), is(201));
- List<Edge> edges = AAIGraph.getInstance().getGraph().newTransaction().traversal().E().has("private", true).toList();
+ List<Edge> edges =
+ AAIGraph.getInstance().getGraph().newTransaction().traversal().E().has("private", true).toList();
assertNotNull("List of edges should not be null", edges);
assertThat(edges.size(), is(1));
Edge oldEdge = edges.get(0);
assertNotNull(oldEdge);
- response = httpTestUtil.doGet("/aai/"+version.toString()+"/network/generic-vnfs/generic-vnf/" + genericVnf);
+ response = httpTestUtil.doGet("/aai/" + version.toString() + "/network/generic-vnfs/generic-vnf/" + genericVnf);
assertNotNull("Response returned null", response);
assertThat("Check the generic vnf is created", response.getStatus(), is(200));
assertThat(response.getEntity().toString(), not(containsString("relationship-list")));
@@ -370,9 +387,11 @@ public class PrivateEdgeIntegrationTest extends AAISetup {
genericVnfHashMap.put("model-invariant-id", newModelId);
genericVnfHashMap.put("model-version-id", newModelVerId);
- String genericVnfPayloadWithResource = PayloadUtil.getTemplatePayload("generic-vnf-resource.json", genericVnfHashMap);
+ String genericVnfPayloadWithResource =
+ PayloadUtil.getTemplatePayload("generic-vnf-resource.json", genericVnfHashMap);
- response = httpTestUtil.doPut("/aai/"+version.toString()+"/network/generic-vnfs/generic-vnf/" + genericVnf, genericVnfPayloadWithResource);
+ response = httpTestUtil.doPut("/aai/" + version.toString() + "/network/generic-vnfs/generic-vnf/" + genericVnf,
+ genericVnfPayloadWithResource);
assertNotNull("Response returned null", response);
assertThat("Check the generic vnf is successfully updated based on new model", response.getStatus(), is(200));
@@ -383,13 +402,14 @@ public class PrivateEdgeIntegrationTest extends AAISetup {
assertNotNull(newEdge);
assertNotEquals(oldEdge, newEdge);
- response = httpTestUtil.doGet("/aai/"+version.toString()+"/network/generic-vnfs/generic-vnf/" + genericVnf);
+ response = httpTestUtil.doGet("/aai/" + version.toString() + "/network/generic-vnfs/generic-vnf/" + genericVnf);
assertNotNull("Response returned null", response);
assertThat("Check the generic vnf is created", response.getStatus(), is(200));
assertThat(response.getEntity().toString(), not(containsString("relationship-list")));
resourceVersion = JsonPath.read(response.getEntity().toString(), "$.resource-version");
- response = httpTestUtil.doDelete("/aai/"+version.toString()+"/network/generic-vnfs/generic-vnf/" + genericVnf, resourceVersion);
+ response = httpTestUtil.doDelete(
+ "/aai/" + version.toString() + "/network/generic-vnfs/generic-vnf/" + genericVnf, resourceVersion);
assertNotNull("Response returned null", response);
assertThat("Check the generic vnf is deleted", response.getStatus(), is(204));
@@ -399,7 +419,8 @@ public class PrivateEdgeIntegrationTest extends AAISetup {
}
@Test
- public void testPutWithGenericVnfToExistingModelAndUpdateWithNewModelInfoThatDoesntExistAndCheckIfReturnsNotFoundAndOldEdgeShouldNotBeDeleted() throws Exception {
+ public void testPutWithGenericVnfToExistingModelAndUpdateWithNewModelInfoThatDoesntExistAndCheckIfReturnsNotFoundAndOldEdgeShouldNotBeDeleted()
+ throws Exception {
Map<String, String> genericVnfHashMap = new HashMap<>();
String genericVnf = "test-generic-" + UUID.randomUUID().toString();
@@ -409,17 +430,19 @@ public class PrivateEdgeIntegrationTest extends AAISetup {
genericVnfHashMap.put("model-version-id", modelVerId);
String genericVnfPayload = PayloadUtil.getTemplatePayload("generic-vnf.json", genericVnfHashMap);
- Response response = httpTestUtil.doPut("/aai/"+version.toString()+"/network/generic-vnfs/generic-vnf/" + genericVnf, genericVnfPayload);
+ Response response = httpTestUtil.doPut(
+ "/aai/" + version.toString() + "/network/generic-vnfs/generic-vnf/" + genericVnf, genericVnfPayload);
assertNotNull("Response returned null", response);
assertThat("Check the generic vnf is created", response.getStatus(), is(201));
- List<Edge> edges = AAIGraph.getInstance().getGraph().newTransaction().traversal().E().has("private", true).toList();
+ List<Edge> edges =
+ AAIGraph.getInstance().getGraph().newTransaction().traversal().E().has("private", true).toList();
assertNotNull("List of edges should not be null", edges);
assertThat(edges.size(), is(1));
Edge oldEdge = edges.get(0);
assertNotNull(oldEdge);
- response = httpTestUtil.doGet("/aai/"+version.toString()+"/network/generic-vnfs/generic-vnf/" + genericVnf);
+ response = httpTestUtil.doGet("/aai/" + version.toString() + "/network/generic-vnfs/generic-vnf/" + genericVnf);
assertNotNull("Response returned null", response);
assertThat("Check the generic vnf is created", response.getStatus(), is(200));
assertThat(response.getEntity().toString(), not(containsString("relationship-list")));
@@ -433,9 +456,11 @@ public class PrivateEdgeIntegrationTest extends AAISetup {
genericVnfHashMap.put("model-invariant-id", newModelId);
genericVnfHashMap.put("model-version-id", newModelVerId);
- String genericVnfPayloadWithResource = PayloadUtil.getTemplatePayload("generic-vnf-resource.json", genericVnfHashMap);
+ String genericVnfPayloadWithResource =
+ PayloadUtil.getTemplatePayload("generic-vnf-resource.json", genericVnfHashMap);
- response = httpTestUtil.doPut("/aai/"+version.toString()+"/network/generic-vnfs/generic-vnf/" + genericVnf, genericVnfPayloadWithResource);
+ response = httpTestUtil.doPut("/aai/" + version.toString() + "/network/generic-vnfs/generic-vnf/" + genericVnf,
+ genericVnfPayloadWithResource);
assertNotNull("Response returned null", response);
assertThat("Check the generic vnf is failed due to missing model ver", response.getStatus(), is(404));
@@ -448,7 +473,8 @@ public class PrivateEdgeIntegrationTest extends AAISetup {
}
@Test
- public void testPutWithGenericVnfToExistingModelAndUpdateVnfWithModelMissingPartOfKeyAndUpdateShouldFailAndOldEdgeShouldStillExist() throws Exception {
+ public void testPutWithGenericVnfToExistingModelAndUpdateVnfWithModelMissingPartOfKeyAndUpdateShouldFailAndOldEdgeShouldStillExist()
+ throws Exception {
Map<String, String> genericVnfHashMap = new HashMap<>();
String genericVnf = "test-generic-" + UUID.randomUUID().toString();
@@ -458,17 +484,19 @@ public class PrivateEdgeIntegrationTest extends AAISetup {
genericVnfHashMap.put("model-version-id", modelVerId);
String genericVnfPayload = PayloadUtil.getTemplatePayload("generic-vnf.json", genericVnfHashMap);
- Response response = httpTestUtil.doPut("/aai/"+version.toString()+"/network/generic-vnfs/generic-vnf/" + genericVnf, genericVnfPayload);
+ Response response = httpTestUtil.doPut(
+ "/aai/" + version.toString() + "/network/generic-vnfs/generic-vnf/" + genericVnf, genericVnfPayload);
assertNotNull("Response returned null", response);
assertThat("Check the generic vnf is created", response.getStatus(), is(201));
- List<Edge> edges = AAIGraph.getInstance().getGraph().newTransaction().traversal().E().has("private", true).toList();
+ List<Edge> edges =
+ AAIGraph.getInstance().getGraph().newTransaction().traversal().E().has("private", true).toList();
assertNotNull("List of edges should not be null", edges);
assertThat(edges.size(), is(1));
Edge oldEdge = edges.get(0);
assertNotNull(oldEdge);
- response = httpTestUtil.doGet("/aai/"+version.toString()+"/network/generic-vnfs/generic-vnf/" + genericVnf);
+ response = httpTestUtil.doGet("/aai/" + version.toString() + "/network/generic-vnfs/generic-vnf/" + genericVnf);
assertNotNull("Response returned null", response);
assertThat("Check the generic vnf is created", response.getStatus(), is(200));
assertThat(response.getEntity().toString(), not(containsString("relationship-list")));
@@ -484,15 +512,12 @@ public class PrivateEdgeIntegrationTest extends AAISetup {
genericVnfHashMap.put("model-invariant-id", newModelId);
genericVnfHashMap.put("model-version-id", newModelVerId);
- String genericVnfPayloadWithResource = "{\n" +
- " \"vnf-id\": \"" + genericVnf + "\",\n" +
- " \"vnf-type\": \"someval\",\n" +
- " \"vnf-name\": \"someval\",\n" +
- " \"model-invariant-id\": \"" + newModelId + "\",\n" +
- " \"resource-version\": \"${resource-version}\"\n" +
- "}";
+ String genericVnfPayloadWithResource = "{\n" + " \"vnf-id\": \"" + genericVnf + "\",\n"
+ + " \"vnf-type\": \"someval\",\n" + " \"vnf-name\": \"someval\",\n" + " \"model-invariant-id\": \""
+ + newModelId + "\",\n" + " \"resource-version\": \"${resource-version}\"\n" + "}";
- response = httpTestUtil.doPut("/aai/"+version.toString()+"/network/generic-vnfs/generic-vnf/" + genericVnf, genericVnfPayloadWithResource);
+ response = httpTestUtil.doPut("/aai/" + version.toString() + "/network/generic-vnfs/generic-vnf/" + genericVnf,
+ genericVnfPayloadWithResource);
assertNotNull("Response returned null", response);
assertThat("Check the generic vnf is failed due to missing model ver", response.getStatus(), is(400));
assertThat(response.getEntity().toString(), containsString("model-invariant-id requires model-version-id"));
@@ -506,7 +531,8 @@ public class PrivateEdgeIntegrationTest extends AAISetup {
}
@Test
- public void testPutCustomerWithServiceInstanceThatHasModelVerThatExistsInDbAndDoGetOnCustomerAndCheckIfRelationshipIsNotThere() throws Exception {
+ public void testPutCustomerWithServiceInstanceThatHasModelVerThatExistsInDbAndDoGetOnCustomerAndCheckIfRelationshipIsNotThere()
+ throws Exception {
Map<String, String> customerHashMap = new HashMap<>();
@@ -517,40 +543,36 @@ public class PrivateEdgeIntegrationTest extends AAISetup {
customerHashMap.put("model-version-id", modelVerId);
String customer = PayloadUtil.getTemplatePayload("customer.json", customerHashMap);
- Response response = httpTestUtil.doPut("/aai/"+version.toString()+"/business/customers/customer/" + customerHashMap.get("global-customer-id"), customer);
+ Response response = httpTestUtil.doPut("/aai/" + version.toString() + "/business/customers/customer/"
+ + customerHashMap.get("global-customer-id"), customer);
assertNotNull("Response returned null", response);
assertThat("Check the cloud region is created with link to generic vnf", response.getStatus(), is(201));
- List<Edge> edges = AAIGraph.getInstance().getGraph().newTransaction().traversal().E().has("private", true).toList();
+ List<Edge> edges =
+ AAIGraph.getInstance().getGraph().newTransaction().traversal().E().has("private", true).toList();
assertNotNull("List of edges should not be null", edges);
assertThat(edges.size(), is(1));
Edge oldEdge = edges.get(0);
assertNotNull(oldEdge);
- response = httpTestUtil.doGet("/aai/"+version.toString()+"/business/customers/customer/" + customerHashMap.get("global-customer-id"));
+ response = httpTestUtil.doGet("/aai/" + version.toString() + "/business/customers/customer/"
+ + customerHashMap.get("global-customer-id"));
assertNotNull("Response returned null", response);
assertThat("Check the customer is returned", response.getStatus(), is(200));
assertThat(response.getEntity().toString(), not(containsString("\"related-to\":\"model-ver\"")));
- String url = "/aai/" + version + "/business/customers/customer/" + customerHashMap.get("global-customer-id") + "/service-subscriptions/service-subscription/" + customerHashMap.get("subscription-type") + "/service-instances/service-instance/"+ customerHashMap.get("service-instance-id");
+ String url = "/aai/" + version + "/business/customers/customer/" + customerHashMap.get("global-customer-id")
+ + "/service-subscriptions/service-subscription/" + customerHashMap.get("subscription-type")
+ + "/service-instances/service-instance/" + customerHashMap.get("service-instance-id");
String genericVnf = "vnf-" + UUID.randomUUID().toString();
- String genericVnfPayload = "{\n" +
- " \"vnf-id\": \"" + genericVnf + "\",\n" +
- " \"vnf-type\": \"someval\",\n" +
- " \"vnf-name\": \"someval\",\n" +
- " \"relationship-list\": {\n" +
- " \"relationship\": [\n" +
- " {\n" +
- " \"related-to\": \"service-instance\",\n" +
- " \"related-link\": \"" + url + "\"\n" +
- " }\n" +
- " ]\n" +
- " }\n" +
- "}\n";
-
-
- response = httpTestUtil.doPut("/aai/" + version.toString() + "/network/generic-vnfs/generic-vnf/" + genericVnf, genericVnfPayload);
+ String genericVnfPayload = "{\n" + " \"vnf-id\": \"" + genericVnf + "\",\n" + " \"vnf-type\": \"someval\",\n"
+ + " \"vnf-name\": \"someval\",\n" + " \"relationship-list\": {\n" + " \"relationship\": [\n"
+ + " {\n" + " \"related-to\": \"service-instance\",\n" + " \"related-link\": \"" + url
+ + "\"\n" + " }\n" + " ]\n" + " }\n" + "}\n";
+
+ response = httpTestUtil.doPut("/aai/" + version.toString() + "/network/generic-vnfs/generic-vnf/" + genericVnf,
+ genericVnfPayload);
assertNotNull("Response returned null", response);
assertThat("Check the customer is returned", response.getStatus(), is(201));
@@ -559,7 +581,8 @@ public class PrivateEdgeIntegrationTest extends AAISetup {
assertThat("Check the customer is returned", response.getStatus(), is(200));
assertThat(response.getEntity().toString(), containsString("\"related-to\":\"service-instance\""));
- response = httpTestUtil.doGet("/aai/"+version.toString()+"/business/customers/customer/" + customerHashMap.get("global-customer-id"));
+ response = httpTestUtil.doGet("/aai/" + version.toString() + "/business/customers/customer/"
+ + customerHashMap.get("global-customer-id"));
assertNotNull("Response returned null", response);
assertThat("Check the customer is returned", response.getStatus(), is(200));
assertThat(response.getEntity().toString(), not(containsString("\"related-to\":\"model-ver\"")));
@@ -568,7 +591,7 @@ public class PrivateEdgeIntegrationTest extends AAISetup {
}
@After
- public void tearDown(){
+ public void tearDown() {
JanusGraphTransaction transaction = AAIGraph.getInstance().getGraph().newTransaction();
boolean success = true;
@@ -577,15 +600,13 @@ public class PrivateEdgeIntegrationTest extends AAISetup {
GraphTraversalSource g = transaction.traversal();
- g.V().has("source-of-truth", "JUNIT")
- .toList()
- .forEach(v -> v.remove());
+ g.V().has("source-of-truth", "JUNIT").toList().forEach(v -> v.remove());
- } catch(Exception ex){
+ } catch (Exception ex) {
success = false;
logger.error("Unable to remove the vertexes", ex);
} finally {
- if(success){
+ if (success) {
transaction.commit();
} else {
transaction.rollback();
diff --git a/aai-core/src/test/java/org/onap/aai/rest/PserverDuplicateTest.java b/aai-core/src/test/java/org/onap/aai/rest/PserverDuplicateTest.java
index f0618b02..5fe3bd00 100644
--- a/aai-core/src/test/java/org/onap/aai/rest/PserverDuplicateTest.java
+++ b/aai-core/src/test/java/org/onap/aai/rest/PserverDuplicateTest.java
@@ -17,10 +17,27 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.rest;
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.fail;
+
import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
+
+import java.util.List;
+import java.util.UUID;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+
+import javax.ws.rs.core.Response;
+
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.janusgraph.core.JanusGraph;
@@ -33,20 +50,6 @@ import org.onap.aai.db.props.AAIProperties;
import org.onap.aai.dbmap.AAIGraph;
import org.onap.aai.serialization.engines.QueryStyle;
-import javax.ws.rs.core.Response;
-import java.util.List;
-import java.util.UUID;
-import java.util.concurrent.Callable;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.TimeUnit;
-import java.util.stream.Collectors;
-import java.util.stream.IntStream;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.fail;
-
public class PserverDuplicateTest extends AAISetup {
private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(PserverDuplicateTest.class);
@@ -59,7 +62,7 @@ public class PserverDuplicateTest extends AAISetup {
hostname = getHostname();
final String aaiUri = "/cloud-infrastructure/pservers/pserver/" + hostname;
- final int threads = getNumberOfThreads();
+ final int threads = getNumberOfThreads();
ExecutorService service = Executors.newFixedThreadPool(threads);
@@ -67,27 +70,21 @@ public class PserverDuplicateTest extends AAISetup {
// Due to the lazy instantiation of the graph, it needs to create a new transaction to create schema
janusGraph.newTransaction().rollback();
- service.invokeAll(
- IntStream.range(0, threads)
- .mapToObj((i) -> (Callable<Void>) () -> {
- JanusGraphTransaction transaction = janusGraph.newTransaction();
- GraphTraversalSource g = transaction.traversal();
- try {
- g.addV()
- .property(AAIProperties.AAI_URI, aaiUri)
- .property(AAIProperties.NODE_TYPE, "pserver")
- .property("hostname", hostname)
- .next();
- transaction.commit();
- } catch (Exception e) {
- throw new Exception("Duplicate was found, error");
- }
- return null;
- }).collect(Collectors.toList())
- , 7, TimeUnit.SECONDS
- );
+ service.invokeAll(IntStream.range(0, threads).mapToObj((i) -> (Callable<Void>) () -> {
+ JanusGraphTransaction transaction = janusGraph.newTransaction();
+ GraphTraversalSource g = transaction.traversal();
+ try {
+ g.addV().property(AAIProperties.AAI_URI, aaiUri).property(AAIProperties.NODE_TYPE, "pserver")
+ .property("hostname", hostname).next();
+ transaction.commit();
+ } catch (Exception e) {
+ throw new Exception("Duplicate was found, error");
+ }
+ return null;
+ }).collect(Collectors.toList()), 7, TimeUnit.SECONDS);
- JanusGraphTransaction readOnlyTransaction = AAIGraph.getInstance().getGraph().buildTransaction().readOnly().start();
+ JanusGraphTransaction readOnlyTransaction =
+ AAIGraph.getInstance().getGraph().buildTransaction().readOnly().start();
GraphTraversalSource g = readOnlyTransaction.traversal();
List<Vertex> pserverList = g.V().has(AAIProperties.AAI_URI, aaiUri).toList();
@@ -95,22 +92,21 @@ public class PserverDuplicateTest extends AAISetup {
testUtil = new HttpTestUtil(QueryStyle.TRAVERSAL_URI);
- if(pserverList.size() == 1){
+ if (pserverList.size() == 1) {
return false;
}
return true;
}
-
@Ignore
public void testWhenDuplicatesExistInGraphThatGetAllSuceeds() throws InterruptedException {
int totalRetries = getNumOfRetries();
- for(int retry = 0; retry < totalRetries; retry++){
- if(!this.createDuplicate()){
- if(retry == (totalRetries-1)){
- fail("Unable to produce duplicates in the graph, " +
- "please increase retry or ignore test if it becomes impossible to create duplicate this test");
+ for (int retry = 0; retry < totalRetries; retry++) {
+ if (!this.createDuplicate()) {
+ if (retry == (totalRetries - 1)) {
+ fail("Unable to produce duplicates in the graph, "
+ + "please increase retry or ignore test if it becomes impossible to create duplicate this test");
}
} else {
// Successfully created a duplicate in the janus graph
@@ -121,20 +117,20 @@ public class PserverDuplicateTest extends AAISetup {
String endpoint = "/aai/v14/cloud-infrastructure/pservers";
Response response = testUtil.doGet(endpoint, null);
- LOGGER.info("GET ALL Pservers with duplicates status code {} and body {}", response.getStatus(), response.getEntity());
+ LOGGER.info("GET ALL Pservers with duplicates status code {} and body {}", response.getStatus(),
+ response.getEntity());
assertThat(response.getStatus(), is(200));
}
- public String getHostname(){
+ public String getHostname() {
return UUID.randomUUID().toString();
}
- public int getNumOfRetries(){
+ public int getNumOfRetries() {
return 10;
}
- public int getNumberOfThreads(){
- return 10;
+ public int getNumberOfThreads() {
+ return 10;
}
}
-
diff --git a/aai-core/src/test/java/org/onap/aai/rest/PserverTest.java b/aai-core/src/test/java/org/onap/aai/rest/PserverTest.java
index f7bea7c3..8ede3c32 100644
--- a/aai-core/src/test/java/org/onap/aai/rest/PserverTest.java
+++ b/aai-core/src/test/java/org/onap/aai/rest/PserverTest.java
@@ -17,11 +17,23 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.rest;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
import com.jayway.jsonpath.JsonPath;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.ws.rs.core.Response;
+
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -30,23 +42,13 @@ import org.onap.aai.AAISetup;
import org.onap.aai.HttpTestUtil;
import org.onap.aai.PayloadUtil;
import org.onap.aai.introspection.*;
-
import org.onap.aai.serialization.engines.QueryStyle;
import org.skyscreamer.jsonassert.JSONAssert;
import org.springframework.test.annotation.DirtiesContext;
-import javax.ws.rs.core.Response;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Map;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-
@RunWith(value = Parameterized.class)
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
-public class PserverTest extends AAISetup{
+public class PserverTest extends AAISetup {
private static EELFLogger logger = EELFManager.getInstance().getLogger(PserverTest.class);
private HttpTestUtil httpTestUtil;
@@ -57,15 +59,11 @@ public class PserverTest extends AAISetup{
@Parameterized.Parameters(name = "QueryStyle.{0}")
public static Collection<Object[]> data() {
- return Arrays.asList(new Object[][]{
- {QueryStyle.TRAVERSAL},
- {QueryStyle.TRAVERSAL_URI}
- });
+ return Arrays.asList(new Object[][] {{QueryStyle.TRAVERSAL}, {QueryStyle.TRAVERSAL_URI}});
}
-
@Before
- public void setUp(){
+ public void setUp() {
httpTestUtil = new HttpTestUtil(queryStyle);
relationshipMap = new HashMap<>();
}
@@ -103,7 +101,8 @@ public class PserverTest extends AAISetup{
response = httpTestUtil.doPut(cloudRegionUri, "{}");
assertNotNull("Expected the response to be not null", response);
assertEquals("Expect the cloud region to be created", 201, response.getStatus());
- logger.info("Successfully able to create the cloud region with payload that has no keys to be retrieved from uri");
+ logger.info(
+ "Successfully able to create the cloud region with payload that has no keys to be retrieved from uri");
response = httpTestUtil.doGet(cloudRegionUri);
assertNotNull("Expected the response to be not null", response);
@@ -120,7 +119,7 @@ public class PserverTest extends AAISetup{
assertEquals("Expect the cloud region relationship to pserver to be created", 200, response.getStatus());
logger.info("Successfully created the relationship between cloud region and pserver");
- response = httpTestUtil.doGet(cloudRegionUri);
+ response = httpTestUtil.doGet(cloudRegionUri);
assertNotNull("Expected the response to be not null", response);
assertEquals("Expect the cloud region to be created", 200, response.getStatus());
logger.info("Successfully retrieved the cloud region from db");
diff --git a/aai-core/src/test/java/org/onap/aai/rest/RestHandlerTest.java b/aai-core/src/test/java/org/onap/aai/rest/RestHandlerTest.java
index c25e2929..cba81d73 100644
--- a/aai-core/src/test/java/org/onap/aai/rest/RestHandlerTest.java
+++ b/aai-core/src/test/java/org/onap/aai/rest/RestHandlerTest.java
@@ -19,6 +19,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.rest;
import static org.junit.Assert.*;
@@ -30,11 +31,11 @@ public class RestHandlerTest {
@Test
public void testGetInstance() {
- RestHandlerService firstInstance = RestHandlerService.getInstance();
- RestHandlerService secondInstance = RestHandlerService.getInstance();
- assertNotNull(firstInstance);
- assertNotNull(secondInstance);
- assertTrue(firstInstance == secondInstance);
+ RestHandlerService firstInstance = RestHandlerService.getInstance();
+ RestHandlerService secondInstance = RestHandlerService.getInstance();
+ assertNotNull(firstInstance);
+ assertNotNull(secondInstance);
+ assertTrue(firstInstance == secondInstance);
}
}
diff --git a/aai-core/src/test/java/org/onap/aai/rest/TenantTest.java b/aai-core/src/test/java/org/onap/aai/rest/TenantTest.java
index e031a326..f8172b02 100644
--- a/aai-core/src/test/java/org/onap/aai/rest/TenantTest.java
+++ b/aai-core/src/test/java/org/onap/aai/rest/TenantTest.java
@@ -17,9 +17,17 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.rest;
+import static org.junit.Assert.assertEquals;
+
import com.jayway.jsonpath.JsonPath;
+
+import java.util.*;
+
+import javax.ws.rs.core.Response;
+
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Ignore;
@@ -35,11 +43,6 @@ import org.skyscreamer.jsonassert.JSONAssert;
import org.springframework.test.context.junit4.rules.SpringClassRule;
import org.springframework.test.context.junit4.rules.SpringMethodRule;
-import javax.ws.rs.core.Response;
-import java.util.*;
-
-import static org.junit.Assert.assertEquals;
-
@RunWith(value = Parameterized.class)
public class TenantTest extends AAISetup {
@@ -50,20 +53,17 @@ public class TenantTest extends AAISetup {
@Rule
public final SpringMethodRule springMethodRule = new SpringMethodRule();
-
+
@Parameterized.Parameter(value = 0)
public QueryStyle queryStyle;
@Parameterized.Parameters(name = "QueryStyle.{0}")
public static Collection<Object[]> data() {
- return Arrays.asList(new Object[][]{
- {QueryStyle.TRAVERSAL},
- {QueryStyle.TRAVERSAL_URI}
- });
+ return Arrays.asList(new Object[][] {{QueryStyle.TRAVERSAL}, {QueryStyle.TRAVERSAL_URI}});
}
@Before
- public void setUp(){
+ public void setUp() {
httpTestUtil = new HttpTestUtil(queryStyle);
templateValuesMap = new HashMap<>();
}
@@ -79,32 +79,30 @@ public class TenantTest extends AAISetup {
String cloudRegionPayload = PayloadUtil.getTemplatePayload("cloud-region.json", templateValuesMap);
String cloudRegionUri = String.format("/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/%s/%s",
- templateValuesMap.get("cloud-owner"),
- templateValuesMap.get("cloud-region-id")
- );
+ templateValuesMap.get("cloud-owner"), templateValuesMap.get("cloud-region-id"));
String tenantUri = cloudRegionUri + "/tenants/tenant/" + templateValuesMap.get("tenant-id");
String tenantPayload = PayloadUtil.getTemplatePayload("tenant.json", templateValuesMap);
- Response response = httpTestUtil.doPut(cloudRegionUri, cloudRegionPayload);
+ Response response = httpTestUtil.doPut(cloudRegionUri, cloudRegionPayload);
assertEquals("Expected the cloud region to be created", 201, response.getStatus());
- response = httpTestUtil.doGet(tenantUri);
+ response = httpTestUtil.doGet(tenantUri);
assertEquals("Expected the cloud region to be created", 200, response.getStatus());
String responseStr = response.getEntity().toString();
JSONAssert.assertEquals(tenantPayload, responseStr, false);
String resourceVersion = JsonPath.read(responseStr, "$.resource-version");
- response = httpTestUtil.doDelete(tenantUri, resourceVersion);
+ response = httpTestUtil.doDelete(tenantUri, resourceVersion);
assertEquals("Expected the cloud region to be created", 204, response.getStatus());
- response = httpTestUtil.doGet(cloudRegionUri);
+ response = httpTestUtil.doGet(cloudRegionUri);
assertEquals("Expected the cloud region to be created", 200, response.getStatus());
responseStr = response.getEntity().toString();
resourceVersion = JsonPath.read(responseStr, "$.resource-version");
- response = httpTestUtil.doDelete(cloudRegionUri, resourceVersion);
+ response = httpTestUtil.doDelete(cloudRegionUri, resourceVersion);
assertEquals("Expected the cloud region to be created", 204, response.getStatus());
}
}
diff --git a/aai-core/src/test/java/org/onap/aai/rest/VipAddressListTest.java b/aai-core/src/test/java/org/onap/aai/rest/VipAddressListTest.java
index 0351c2c3..354b030b 100644
--- a/aai-core/src/test/java/org/onap/aai/rest/VipAddressListTest.java
+++ b/aai-core/src/test/java/org/onap/aai/rest/VipAddressListTest.java
@@ -17,9 +17,19 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.rest;
+import static org.junit.Assert.assertEquals;
+
import com.jayway.jsonpath.JsonPath;
+
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collection;
+
+import javax.ws.rs.core.Response;
+
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
@@ -32,13 +42,6 @@ import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.engines.QueryStyle;
import org.skyscreamer.jsonassert.JSONAssert;
-import javax.ws.rs.core.Response;
-import java.io.IOException;
-import java.util.Arrays;
-import java.util.Collection;
-
-import static org.junit.Assert.assertEquals;
-
@RunWith(value = Parameterized.class)
public class VipAddressListTest extends AAISetup {
@@ -49,13 +52,11 @@ public class VipAddressListTest extends AAISetup {
@Parameterized.Parameters(name = "QueryStyle.{0}")
public static Collection<Object[]> data() {
- return Arrays.asList(new Object[][]{
- {QueryStyle.TRAVERSAL_URI}
- });
+ return Arrays.asList(new Object[][] {{QueryStyle.TRAVERSAL_URI}});
}
@Before
- public void setUp(){
+ public void setUp() {
httpTestUtil = new HttpTestUtil(queryStyle);
}
@@ -63,9 +64,10 @@ public class VipAddressListTest extends AAISetup {
public void testPutWithAllCloudRegionChildrenNodesAndCheckIfDeleteIsSuccessful() throws IOException, AAIException {
String cloudRegionPayload = PayloadUtil.getResourcePayload("cloud-region.json");
- String cloudRegionUri = "/aai/v14/cloud-infrastructure/cloud-regions/cloud-region/cloud-region-owner-with-vip-ipv4/cloud-region-id-with-vip-ipv4";
+ String cloudRegionUri =
+ "/aai/v14/cloud-infrastructure/cloud-regions/cloud-region/cloud-region-owner-with-vip-ipv4/cloud-region-id-with-vip-ipv4";
- Response response = httpTestUtil.doPut(cloudRegionUri, cloudRegionPayload);
+ Response response = httpTestUtil.doPut(cloudRegionUri, cloudRegionPayload);
assertEquals("Expected the cloud region to be created", 201, response.getStatus());
response = httpTestUtil.doGet(cloudRegionUri);
@@ -77,7 +79,7 @@ public class VipAddressListTest extends AAISetup {
String vipIpv4Uri = cloudRegionUri + "/vip-ipv4-address-list/vip-ipv4-address-list-1";
String vipIpv4Payload = PayloadUtil.getResourcePayload("vip-ipv4-address-list.json");
- response = httpTestUtil.doPut(vipIpv4Uri, vipIpv4Payload);
+ response = httpTestUtil.doPut(vipIpv4Uri, vipIpv4Payload);
assertEquals("Expected the ipv4 address list to be created", 201, response.getStatus());
response = httpTestUtil.doGet(vipIpv4Uri);
diff --git a/aai-core/src/test/java/org/onap/aai/rest/db/HttpEntryTest.java b/aai-core/src/test/java/org/onap/aai/rest/db/HttpEntryTest.java
index 6e72a0f1..c01d270e 100644
--- a/aai-core/src/test/java/org/onap/aai/rest/db/HttpEntryTest.java
+++ b/aai-core/src/test/java/org/onap/aai/rest/db/HttpEntryTest.java
@@ -17,10 +17,26 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.rest.db;
+import static org.hamcrest.Matchers.containsString;
+import static org.hamcrest.Matchers.not;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThat;
+import static org.mockito.Matchers.anyObject;
+import static org.mockito.Mockito.doNothing;
+import static org.mockito.Mockito.when;
+
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URI;
+import java.util.*;
+
+import javax.ws.rs.core.*;
+
import org.javatuples.Pair;
import org.junit.Before;
import org.junit.FixMethodOrder;
@@ -44,20 +60,6 @@ import org.onap.aai.serialization.engines.QueryStyle;
import org.onap.aai.serialization.engines.TransactionalGraphEngine;
import org.onap.aai.util.AAIConfig;
-import javax.ws.rs.core.*;
-import java.io.UnsupportedEncodingException;
-import java.net.URI;
-import java.util.*;
-
-import static org.hamcrest.Matchers.containsString;
-import static org.hamcrest.Matchers.not;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertThat;
-import static org.mockito.Matchers.anyObject;
-import static org.mockito.Mockito.doNothing;
-import static org.mockito.Mockito.when;
-
-
@RunWith(value = Parameterized.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class HttpEntryTest extends AAISetup {
@@ -71,7 +73,6 @@ public class HttpEntryTest extends AAISetup {
VALID_HTTP_STATUS_CODES.add(201);
VALID_HTTP_STATUS_CODES.add(204);
}
-
@Parameterized.Parameter(value = 0)
public QueryStyle queryStyle;
@@ -81,10 +82,7 @@ public class HttpEntryTest extends AAISetup {
*/
@Parameterized.Parameters(name = "QueryStyle.{0}")
public static Collection<Object[]> data() {
- return Arrays.asList(new Object[][]{
- {QueryStyle.TRAVERSAL},
- {QueryStyle.TRAVERSAL_URI}
- });
+ return Arrays.asList(new Object[][] {{QueryStyle.TRAVERSAL}, {QueryStyle.TRAVERSAL_URI}});
}
private HttpHeaders httpHeaders;
@@ -99,13 +97,13 @@ public class HttpEntryTest extends AAISetup {
private List<MediaType> outputMediaTypes;
@Before
- public void setup(){
+ public void setup() {
- 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());
@@ -124,7 +122,6 @@ public class HttpEntryTest extends AAISetup {
when(httpHeaders.getRequestHeader("aai-request-context")).thenReturn(aaiRequestContextList);
-
when(uriInfo.getQueryParameters()).thenReturn(queryParameters);
when(uriInfo.getQueryParameters(false)).thenReturn(queryParameters);
@@ -134,7 +131,8 @@ public class HttpEntryTest extends AAISetup {
when(httpHeaders.getMediaType()).thenReturn(APPLICATION_JSON);
}
- private Response doRequest(HttpEntry httpEntry, Loader loader, TransactionalGraphEngine dbEngine, HttpMethod method, String uri, String content) throws UnsupportedEncodingException, AAIException {
+ private Response doRequest(HttpEntry httpEntry, Loader loader, TransactionalGraphEngine dbEngine, HttpMethod method,
+ String uri, String content) throws UnsupportedEncodingException, AAIException {
URI uriObject = UriBuilder.fromPath(uri).build();
QueryParser uriQuery = dbEngine.getQueryBuilder().createQueryFromURI(uriObject);
String objType = uriQuery.getResultType();
@@ -155,11 +153,10 @@ public class HttpEntryTest extends AAISetup {
List<DBRequest> dbRequestList = new ArrayList<>();
dbRequestList.add(dbRequest);
- Pair<Boolean, List<Pair<URI, Response>>> responsesTuple = httpEntry.process(dbRequestList, "JUNIT");
+ Pair<Boolean, List<Pair<URI, Response>>> responsesTuple = httpEntry.process(dbRequestList, "JUNIT");
return responsesTuple.getValue1().get(0).getValue1();
}
-
@Test
public void test1PutOnPserver() throws UnsupportedEncodingException, AAIException {
@@ -171,7 +168,6 @@ public class HttpEntryTest extends AAISetup {
Loader loader = traversalHttpEntry.getLoader();
TransactionalGraphEngine dbEngine = traversalHttpEntry.getDbEngine();
-
String uri = "/cloud-infrastructure/pservers/pserver/junit-test1";
String content = "{\"hostname\":\"junit-test1\"}";
Response response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.PUT, uri, content);
@@ -195,33 +191,30 @@ public class HttpEntryTest extends AAISetup {
}
@Test
- public void test3PutOnPInterface() {
+ public void test3PutOnPInterface() {
try {
- DBConnectionType type = DBConnectionType.REALTIME;
- traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion(), type);
- Loader loader = traversalHttpEntry.getLoader();
- TransactionalGraphEngine dbEngine = traversalHttpEntry.getDbEngine();
-
- String uri = "/cloud-infrastructure/pservers/pserver/junit-test1/p-interfaces/p-interface/p1";
- String content = "{\"interface-name\":\"p1\"}";
- Response response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.PUT, uri, content);
- dbEngine.commit();
- assertEquals("Expected the p-interface to be created", 201, response.getStatus());
+ DBConnectionType type = DBConnectionType.REALTIME;
+ traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion(), type);
+ Loader loader = traversalHttpEntry.getLoader();
+ TransactionalGraphEngine dbEngine = traversalHttpEntry.getDbEngine();
+
+ String uri = "/cloud-infrastructure/pservers/pserver/junit-test1/p-interfaces/p-interface/p1";
+ String content = "{\"interface-name\":\"p1\"}";
+ Response response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.PUT, uri, content);
+ dbEngine.commit();
+ assertEquals("Expected the p-interface to be created", 201, response.getStatus());
} catch (UnsupportedEncodingException | AAIException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
-
-
@Test
public void test4GetOnPserver() throws UnsupportedEncodingException, AAIException {
DBConnectionType type = DBConnectionType.REALTIME;
traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion(), type);
-
-
+
Loader loader = traversalHttpEntry.getLoader();
TransactionalGraphEngine dbEngine = traversalHttpEntry.getDbEngine();
@@ -233,13 +226,13 @@ public class HttpEntryTest extends AAISetup {
dbEngine.commit();
assertEquals("Expected the pserver to be returned", 200, response.getStatus());
}
-
+
@Test
public void test5MergePatchOnPserver() throws UnsupportedEncodingException, AAIException {
DBConnectionType type = DBConnectionType.REALTIME;
traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion(), type);
-
+
Loader loader = traversalHttpEntry.getLoader();
TransactionalGraphEngine dbEngine = traversalHttpEntry.getDbEngine();
@@ -249,8 +242,9 @@ public class HttpEntryTest extends AAISetup {
dbEngine.commit();
assertEquals("Expected the pserver to be updated", 200, response.getStatus());
}
-
- private int doDelete(String resourceVersion, String uri, String nodeType) throws UnsupportedEncodingException, AAIException {
+
+ private int doDelete(String resourceVersion, String uri, String nodeType)
+ throws UnsupportedEncodingException, AAIException {
queryParameters.add("resource-version", resourceVersion);
DBConnectionType type = DBConnectionType.REALTIME;
traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion(), type);
@@ -265,23 +259,21 @@ public class HttpEntryTest extends AAISetup {
Introspector obj = loader.introspectorFromName(nodeType);
- DBRequest dbRequest =
- new DBRequest.Builder(HttpMethod.DELETE, uriObject, uriQuery, obj, httpHeaders, uriInfo, "JUNIT-TRANSACTION")
- .rawRequestContent(content).build();
+ DBRequest dbRequest = new DBRequest.Builder(HttpMethod.DELETE, uriObject, uriQuery, obj, httpHeaders, uriInfo,
+ "JUNIT-TRANSACTION").rawRequestContent(content).build();
List<DBRequest> dbRequestList = new ArrayList<>();
dbRequestList.add(dbRequest);
- Pair<Boolean, List<Pair<URI, Response>>> responsesTuple = traversalHttpEntry.process(dbRequestList, "JUNIT");
+ Pair<Boolean, List<Pair<URI, Response>>> responsesTuple = traversalHttpEntry.process(dbRequestList, "JUNIT");
Response response = responsesTuple.getValue1().get(0).getValue1();
dbEngine.commit();
return response.getStatus();
}
-
+
@Test
public void test6DeleteOnPserver() throws UnsupportedEncodingException, AAIException {
-
DBConnectionType type = DBConnectionType.REALTIME;
traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion(), type);
Loader loader = traversalHttpEntry.getLoader();
@@ -295,19 +287,19 @@ public class HttpEntryTest extends AAISetup {
String msg = response.getEntity().toString();
JsonObject jsonObj = new JsonParser().parse(msg).getAsJsonObject();
String resourceVersion = "";
- if ( jsonObj.isJsonObject()) {
+ if (jsonObj.isJsonObject()) {
resourceVersion = jsonObj.get("resource-version").getAsString();
}
- assertEquals("Expected the pserver to be deleted", 204, doDelete(resourceVersion, "/cloud-infrastructure/pservers/pserver/junit-test1", "pserver"));
+ assertEquals("Expected the pserver to be deleted", 204,
+ doDelete(resourceVersion, "/cloud-infrastructure/pservers/pserver/junit-test1", "pserver"));
}
@Test
public void test7DeleteOnPserverNoPinterface() throws UnsupportedEncodingException, AAIException {
-
DBConnectionType type = DBConnectionType.REALTIME;
traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion(), type);
- //HttpEntry httpEntry = new HttpEntry(Version.getLatest(), ModelType.MOXY, queryStyle, type);
+ // HttpEntry httpEntry = new HttpEntry(Version.getLatest(), ModelType.MOXY, queryStyle, type);
Loader loader = traversalHttpEntry.getLoader();
TransactionalGraphEngine dbEngine = traversalHttpEntry.getDbEngine();
@@ -318,19 +310,19 @@ public class HttpEntryTest extends AAISetup {
String msg = response.getEntity().toString();
JsonObject jsonObj = new JsonParser().parse(msg).getAsJsonObject();
String resourceVersion = "";
- if ( jsonObj.isJsonObject()) {
+ if (jsonObj.isJsonObject()) {
resourceVersion = jsonObj.get("resource-version").getAsString();
}
- assertEquals("Expected the pserver to be deleted", 204, doDelete(resourceVersion, "/cloud-infrastructure/pservers/pserver/junit-test2", "pserver"));
+ assertEquals("Expected the pserver to be deleted", 204,
+ doDelete(resourceVersion, "/cloud-infrastructure/pservers/pserver/junit-test2", "pserver"));
}
-
@Test
public void test8FailedGetOnPserver() throws UnsupportedEncodingException, AAIException {
DBConnectionType type = DBConnectionType.REALTIME;
traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion(), type);
- //HttpEntry httpEntry = new HttpEntry(Version.getLatest(), ModelType.MOXY, queryStyle, type);
+ // HttpEntry httpEntry = new HttpEntry(Version.getLatest(), ModelType.MOXY, queryStyle, type);
Loader loader = traversalHttpEntry.getLoader();
TransactionalGraphEngine dbEngine = traversalHttpEntry.getDbEngine();
@@ -347,51 +339,54 @@ public class HttpEntryTest extends AAISetup {
DBConnectionType type = DBConnectionType.REALTIME;
traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion(), type);
- //HttpEntry httpEntry = new HttpEntry(Version.getLatest(), ModelType.MOXY, queryStyle, type);
+ // HttpEntry httpEntry = new HttpEntry(Version.getLatest(), ModelType.MOXY, queryStyle, type);
Loader loader = traversalHttpEntry.getLoader();
TransactionalGraphEngine dbEngine = traversalHttpEntry.getDbEngine();
- //Put pserver
+ // Put pserver
String uri = "/cloud-infrastructure/pservers/pserver/junit-edge-test-pserver";
String content = "{\"hostname\":\"junit-edge-test-pserver\"}";
doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.PUT, uri, content);
- //Put complex
+ // Put complex
uri = "/cloud-infrastructure/complexes/complex/junit-edge-test-complex";
- content = "{\"physical-location-id\":\"junit-edge-test-complex\",\"physical-location-type\":\"AAIDefault\",\"street1\":\"AAIDefault\",\"city\":\"AAIDefault\",\"state\":\"NJ\",\"postal-code\":\"07748\",\"country\":\"USA\",\"region\":\"US\"}";
+ content =
+ "{\"physical-location-id\":\"junit-edge-test-complex\",\"physical-location-type\":\"AAIDefault\",\"street1\":\"AAIDefault\",\"city\":\"AAIDefault\",\"state\":\"NJ\",\"postal-code\":\"07748\",\"country\":\"USA\",\"region\":\"US\"}";
doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.PUT, uri, content);
- //PutEdge
+ // PutEdge
uri = "/cloud-infrastructure/complexes/complex/junit-edge-test-complex/relationship-list/relationship";
- content = "{\"related-to\":\"pserver\",\"related-link\":\"/aai/" + schemaVersions.getDefaultVersion().toString() + "/cloud-infrastructure/pservers/pserver/junit-edge-test-pserver\",\"relationship-label\":\"org.onap.relationships.inventory.LocatedIn\"}";
+ content = "{\"related-to\":\"pserver\",\"related-link\":\"/aai/" + schemaVersions.getDefaultVersion().toString()
+ + "/cloud-infrastructure/pservers/pserver/junit-edge-test-pserver\",\"relationship-label\":\"org.onap.relationships.inventory.LocatedIn\"}";
Response response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.PUT_EDGE, uri, content);
dbEngine.rollback();
- assertEquals("Expected the pserver relationship to be created", 200, response.getStatus());
+ assertEquals("Expected the pserver relationship to be created", 200, response.getStatus());
}
-
@Test
public void notificationOnRelatedToTest() throws UnsupportedEncodingException, AAIException {
Loader ld = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getDefaultVersion());
UEBNotification uebNotification = Mockito.spy(new UEBNotification(ld, loaderFactory, schemaVersions));
DBConnectionType type = DBConnectionType.REALTIME;
- traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion(), type , uebNotification);
-
+ traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion(), type, uebNotification);
+
Loader loader = traversalHttpEntry.getLoader();
TransactionalGraphEngine dbEngine = traversalHttpEntry.getDbEngine();
- //Put pserver
+ // Put pserver
String uri = "/cloud-infrastructure/pservers/pserver/junit-edge-test-pserver";
String content = "{\"hostname\":\"junit-edge-test-pserver\"}";
doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.PUT, uri, content);
- //Put complex
+ // Put complex
uri = "/cloud-infrastructure/complexes/complex/junit-edge-test-complex";
- content = "{\"physical-location-id\":\"junit-edge-test-complex\",\"physical-location-type\":\"AAIDefault\",\"street1\":\"AAIDefault\",\"city\":\"AAIDefault\",\"state\":\"NJ\",\"postal-code\":\"07748\",\"country\":\"USA\",\"region\":\"US\"}";
+ content =
+ "{\"physical-location-id\":\"junit-edge-test-complex\",\"physical-location-type\":\"AAIDefault\",\"street1\":\"AAIDefault\",\"city\":\"AAIDefault\",\"state\":\"NJ\",\"postal-code\":\"07748\",\"country\":\"USA\",\"region\":\"US\"}";
doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.PUT, uri, content);
- //PutEdge
+ // PutEdge
uri = "/cloud-infrastructure/complexes/complex/junit-edge-test-complex/relationship-list/relationship";
- content = "{\"related-to\":\"pserver\",\"related-link\":\"/aai/" + schemaVersions.getDefaultVersion().toString() + "/cloud-infrastructure/pservers/pserver/junit-edge-test-pserver\",\"relationship-label\":\"org.onap.relationships.inventory.LocatedIn\"}";
+ content = "{\"related-to\":\"pserver\",\"related-link\":\"/aai/" + schemaVersions.getDefaultVersion().toString()
+ + "/cloud-infrastructure/pservers/pserver/junit-edge-test-pserver\",\"relationship-label\":\"org.onap.relationships.inventory.LocatedIn\"}";
doNothing().when(uebNotification).triggerEvents();
Response response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.PUT_EDGE, uri, content);
@@ -413,8 +408,6 @@ public class HttpEntryTest extends AAISetup {
uebNotification.getEvents().get(1).getObj().marshal(false),
not(containsString("cloud-infrastructure/pservers/pserver/junit-edge-test-pserver")));
-
-
}
@Test
@@ -422,29 +415,32 @@ public class HttpEntryTest extends AAISetup {
DBConnectionType type = DBConnectionType.REALTIME;
traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion(), type);
- //HttpEntry httpEntry = new HttpEntry(Version.getLatest(), ModelType.MOXY, queryStyle, type);
+ // HttpEntry httpEntry = new HttpEntry(Version.getLatest(), ModelType.MOXY, queryStyle, type);
Loader loader = traversalHttpEntry.getLoader();
TransactionalGraphEngine dbEngine = traversalHttpEntry.getDbEngine();
- //Put pserver
+ // Put pserver
String uri = "/cloud-infrastructure/pservers/pserver/junit-edge-test-pserver";
String content = "{\"hostname\":\"junit-edge-test-pserver\"}";
doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.PUT, uri, content);
- //Put complex
+ // Put complex
uri = "/cloud-infrastructure/complexes/complex/junit-edge-test-complex";
- content = "{\"physical-location-id\":\"junit-edge-test-complex\",\"physical-location-type\":\"AAIDefault\",\"street1\":\"AAIDefault\",\"city\":\"AAIDefault\",\"state\":\"NJ\",\"postal-code\":\"07748\",\"country\":\"USA\",\"region\":\"US\"}";
+ content =
+ "{\"physical-location-id\":\"junit-edge-test-complex\",\"physical-location-type\":\"AAIDefault\",\"street1\":\"AAIDefault\",\"city\":\"AAIDefault\",\"state\":\"NJ\",\"postal-code\":\"07748\",\"country\":\"USA\",\"region\":\"US\"}";
doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.PUT, uri, content);
- //PutEdge
+ // PutEdge
uri = "/cloud-infrastructure/complexes/complex/junit-edge-test-complex/relationship-list/relationship";
- content = "{\"related-to\":\"pserver\",\"related-link\":\"/aai/" + schemaVersions.getDefaultVersion().toString() + "/cloud-infrastructure/pservers/pserver/junit-edge-test-pserver\",\"relationship-label\":\"junk\"}";
+ content = "{\"related-to\":\"pserver\",\"related-link\":\"/aai/" + schemaVersions.getDefaultVersion().toString()
+ + "/cloud-infrastructure/pservers/pserver/junit-edge-test-pserver\",\"relationship-label\":\"junk\"}";
Response response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.PUT_EDGE, uri, content);
dbEngine.rollback();
String msg = response.getEntity().toString();
assertEquals("Expected the pserver to be created", 400, response.getStatus());
assertThat(msg, containsString("ERR.5.4.6107"));
- assertThat(msg, containsString("Required Edge-property not found in input data:org.onap.aai.edges.exceptions.EdgeRuleNotFoundException: No rule found for EdgeRuleQuery with filter params node type: complex, node type: pserver, label: junk, type: COUSIN, isPrivate: false"));
+ assertThat(msg, containsString(
+ "Required Edge-property not found in input data:org.onap.aai.edges.exceptions.EdgeRuleNotFoundException: No rule found for EdgeRuleQuery with filter params node type: complex, node type: pserver, label: junk, type: COUSIN, isPrivate: false"));
}
@@ -455,29 +451,34 @@ public class HttpEntryTest extends AAISetup {
DBConnectionType type = DBConnectionType.REALTIME;
traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion(), type);
- //HttpEntry httpEntry = new HttpEntry(schemaVersions.getDefaultVersion(), ModelType.MOXY, QueryStyle.TRAVERSAL, type);
+ // HttpEntry httpEntry = new HttpEntry(schemaVersions.getDefaultVersion(), ModelType.MOXY, QueryStyle.TRAVERSAL,
+ // type);
Loader loader = traversalHttpEntry.getLoader();
TransactionalGraphEngine dbEngine = traversalHttpEntry.getDbEngine();
- //Put pserver
+ // Put pserver
String pserverKey = "pserver-" + testName;
String pserverUri = "/cloud-infrastructure/pservers/pserver/" + pserverKey;
String content = "{\"hostname\":\"" + pserverKey + "\"}";
doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.PUT, pserverUri, content);
- //Put complex
+ // Put complex
String complexKey = "complex-" + testName;
String complexUri = "/cloud-infrastructure/complexes/complex/" + complexKey;
- content = "{\"physical-location-id\":\"" + complexKey + "\",\"physical-location-type\":\"AAIDefault\",\"street1\":\"AAIDefault\",\"city\":\"AAIDefault\",\"state\":\"NJ\",\"postal-code\":\"07748\",\"country\":\"USA\",\"region\":\"US\"}";
+ content = "{\"physical-location-id\":\"" + complexKey
+ + "\",\"physical-location-type\":\"AAIDefault\",\"street1\":\"AAIDefault\",\"city\":\"AAIDefault\",\"state\":\"NJ\",\"postal-code\":\"07748\",\"country\":\"USA\",\"region\":\"US\"}";
doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.PUT, complexUri, content);
- //PutEdge
- String relationshipUri = "/cloud-infrastructure/complexes/complex/" + complexKey + "/relationship-list/relationship";
- content = "{\"related-to\":\"pserver\",\"related-link\":\"/aai/" + schemaVersions.getDefaultVersion().toString() + "/cloud-infrastructure/pservers/pserver/" + pserverKey + "\",\"relationship-label\":\"org.onap.relationships.inventory.LocatedIn\"}";
+ // PutEdge
+ String relationshipUri =
+ "/cloud-infrastructure/complexes/complex/" + complexKey + "/relationship-list/relationship";
+ content = "{\"related-to\":\"pserver\",\"related-link\":\"/aai/" + schemaVersions.getDefaultVersion().toString()
+ + "/cloud-infrastructure/pservers/pserver/" + pserverKey
+ + "\",\"relationship-label\":\"org.onap.relationships.inventory.LocatedIn\"}";
doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.PUT_EDGE, relationshipUri, content);
- //Get pserver with pathed
- queryParameters.add("format","pathed");
+ // Get pserver with pathed
+ queryParameters.add("format", "pathed");
content = "";
Response response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.GET, pserverUri, content);
queryParameters.remove("format");
@@ -497,26 +498,27 @@ public class HttpEntryTest extends AAISetup {
DBConnectionType type = DBConnectionType.REALTIME;
traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion(), type);
- //HttpEntry httpEntry = new HttpEntry(Version.getLatest(), ModelType.MOXY, QueryStyle.TRAVERSAL, type);
+ // HttpEntry httpEntry = new HttpEntry(Version.getLatest(), ModelType.MOXY, QueryStyle.TRAVERSAL, type);
Loader loader = traversalHttpEntry.getLoader();
TransactionalGraphEngine dbEngine = traversalHttpEntry.getDbEngine();
- //Put pserver
+ // Put pserver
String pserver1Key = "pserver-1-" + testName;
String pserver1Uri = "/cloud-infrastructure/pservers/pserver/" + pserver1Key;
String content = "{\"hostname\":\"" + pserver1Key + "\"}";
doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.PUT, pserver1Uri, content);
- //Put complex
+ // Put complex
String pserver2Key = "pserver-2-" + testName;
String pserver2Uri = "/cloud-infrastructure/pservers/pserver/" + pserver2Key;
content = "{\"hostname\":\"" + pserver2Key + "\"}";
doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.PUT, pserver2Uri, content);
- //Get pserver with pathed
- queryParameters.add("format","pathed");
+ // Get pserver with pathed
+ queryParameters.add("format", "pathed");
content = "";
- Response response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.GET, "/cloud-infrastructure/pservers", content);
+ Response response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.GET,
+ "/cloud-infrastructure/pservers", content);
queryParameters.remove("format");
String msg = response.getEntity().toString();
@@ -528,18 +530,20 @@ public class HttpEntryTest extends AAISetup {
}
- @Test
- public void testSetGetPaginationMethods(){
+ @Test
+ public void testSetGetPaginationMethods() {
DBConnectionType type = DBConnectionType.REALTIME;
traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion(), type);
- //HttpEntry httpEntry = new HttpEntry(schemaVersions.getDefaultVersion(), ModelType.MOXY, QueryStyle.TRAVERSAL, type);
+ // HttpEntry httpEntry = new HttpEntry(schemaVersions.getDefaultVersion(), ModelType.MOXY, QueryStyle.TRAVERSAL,
+ // type);
traversalHttpEntry.setPaginationBucket(10);
traversalHttpEntry.setPaginationIndex(1);
traversalHttpEntry.setTotalsForPaging(101, traversalHttpEntry.getPaginationBucket());
assertEquals("Expected the pagination bucket size to be 10", 10, traversalHttpEntry.getPaginationBucket());
- assertEquals("Expected the total number of pagination buckets to be 11", 11, traversalHttpEntry.getTotalPaginationBuckets());
- assertEquals("Expected the pagination index to be 1",1, traversalHttpEntry.getPaginationIndex());
- assertEquals("Expected the total amount of vertices to be 101",101, traversalHttpEntry.getTotalVertices());
+ assertEquals("Expected the total number of pagination buckets to be 11", 11,
+ traversalHttpEntry.getTotalPaginationBuckets());
+ assertEquals("Expected the pagination index to be 1", 1, traversalHttpEntry.getPaginationIndex());
+ assertEquals("Expected the total amount of vertices to be 101", 101, traversalHttpEntry.getTotalVertices());
}
@Test
@@ -547,25 +551,27 @@ public class HttpEntryTest extends AAISetup {
DBConnectionType type = DBConnectionType.REALTIME;
traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion(), type);
- //HttpEntry httpEntry = new HttpEntry(schemaVersions.getDefaultVersion(), ModelType.MOXY, queryStyle, type);
+ // HttpEntry httpEntry = new HttpEntry(schemaVersions.getDefaultVersion(), ModelType.MOXY, queryStyle, type);
Loader loader = traversalHttpEntry.getLoader();
TransactionalGraphEngine dbEngine = traversalHttpEntry.getDbEngine();
- //Put pserver
+ // Put pserver
String uri = "/cloud-infrastructure/pservers/pserver/junit-edge-test-pserver";
String content = "{\"hostname\":\"junit-edge-test-pserver\"}";
doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.PUT, uri, content);
- //Put complex
+ // Put complex
uri = "/cloud-infrastructure/complexes/complex/junit-edge-test-complex";
- content = "{\"physical-location-id\":\"junit-edge-test-complex\",\"physical-location-type\":\"AAIDefault\",\"street1\":\"AAIDefault\",\"city\":\"AAIDefault\",\"state\":\"NJ\",\"postal-code\":\"07748\",\"country\":\"USA\",\"region\":\"US\"}";
+ content =
+ "{\"physical-location-id\":\"junit-edge-test-complex\",\"physical-location-type\":\"AAIDefault\",\"street1\":\"AAIDefault\",\"city\":\"AAIDefault\",\"state\":\"NJ\",\"postal-code\":\"07748\",\"country\":\"USA\",\"region\":\"US\"}";
doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.PUT, uri, content);
- //PutEdge
+ // PutEdge
uri = "/cloud-infrastructure/complexes/complex/junit-edge-test-complex/relationship-list/relationship";
- content = "{\"related-to\":\"pserver\",\"related-link\":\"/aai/" + schemaVersions.getDefaultVersion().toString() + "/cloud-infrastructure/pservers/pserver/junit-edge-test-pserver\",\"relationship-label\":\"org.onap.relationships.inventory.LocatedIn\"}";
+ content = "{\"related-to\":\"pserver\",\"related-link\":\"/aai/" + schemaVersions.getDefaultVersion().toString()
+ + "/cloud-infrastructure/pservers/pserver/junit-edge-test-pserver\",\"relationship-label\":\"org.onap.relationships.inventory.LocatedIn\"}";
doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.PUT_EDGE, uri, content);
- //getRelatedTo
+ // getRelatedTo
uri = "/cloud-infrastructure/complexes/complex/junit-edge-test-complex/related-to/pservers";
content = "";
Response response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.GET, uri, content);
@@ -573,8 +579,9 @@ public class HttpEntryTest extends AAISetup {
dbEngine.rollback();
assertEquals("Expected the pserver to be created", 200, response.getStatus());
- assertThat("Related to pserver is returned.", respBody, containsString("\"hostname\":\"junit-edge-test-pserver\""));
-
+ assertThat("Related to pserver is returned.", respBody,
+ containsString("\"hostname\":\"junit-edge-test-pserver\""));
+
}
@Test
@@ -585,43 +592,44 @@ public class HttpEntryTest extends AAISetup {
String depthParam = AAIConfig.get("aai.rest.getall.depthparam");
DBConnectionType type = DBConnectionType.REALTIME;
traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion(), type);
- //HttpEntry httpEntry = new HttpEntry(Version.getLatest(), ModelType.MOXY, QueryStyle.TRAVERSAL, type);
+ // HttpEntry httpEntry = new HttpEntry(Version.getLatest(), ModelType.MOXY, QueryStyle.TRAVERSAL, type);
int depth = traversalHttpEntry.setDepth(null, depthParam);
assertEquals(AAIProperties.MAXIMUM_DEPTH.intValue(), depth);
}
-
@Test
public void getAbstractTest() throws UnsupportedEncodingException, AAIException {
DBConnectionType type = DBConnectionType.REALTIME;
traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion(), type);
- //HttpEntry httpEntry = new HttpEntry(Version.getLatest(), ModelType.MOXY, queryStyle, type);
+ // HttpEntry httpEntry = new HttpEntry(Version.getLatest(), ModelType.MOXY, queryStyle, type);
Loader loader = traversalHttpEntry.getLoader();
TransactionalGraphEngine dbEngine = traversalHttpEntry.getDbEngine();
- //Put generic-vnf
+ // Put generic-vnf
String uri = "/network/generic-vnfs/generic-vnf/junit-abstract-test-generic-vnf";
String content = "{\"vnf-id\":\"junit-abstract-test-generic-vnf\",\"vnf-name\":\"junit-generic-vnf-name\"}";
doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.PUT, uri, content);
- //Put pserver
+ // Put pserver
uri = "/cloud-infrastructure/pservers/pserver/junit-abstract-test-pserver";
content = "{\"hostname\":\"junit-abstract-test-pserver\"}";
doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.PUT, uri, content);
- //PutEdge
+ // PutEdge
uri = "/cloud-infrastructure/pservers/pserver/junit-abstract-test-pserver/relationship-list/relationship";
- content = "{\"related-to\":\"vnf\",\"relationship-data\":[{\"relationship-key\":\"vnf.vnf-id\",\"relationship-value\":\"junit-abstract-test-generic-vnf\"}]}";
+ content =
+ "{\"related-to\":\"vnf\",\"relationship-data\":[{\"relationship-key\":\"vnf.vnf-id\",\"relationship-value\":\"junit-abstract-test-generic-vnf\"}]}";
doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.PUT_EDGE, uri, content);
- //getRelatedTo
+ // getRelatedTo
uri = "/network/generic-vnfs/generic-vnf/junit-abstract-test-generic-vnf/related-to/pservers";
content = "";
Response response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.GET, uri, content);
String respBody = response.getEntity().toString();
dbEngine.rollback();
- assertThat("Related to pserver is returned.", respBody, containsString("\"hostname\":\"junit-abstract-test-pserver\""));
+ assertThat("Related to pserver is returned.", respBody,
+ containsString("\"hostname\":\"junit-abstract-test-pserver\""));
}
-} \ No newline at end of file
+}
diff --git a/aai-core/src/test/java/org/onap/aai/serialization/db/AAICoreFakeEdgesConfigTranslator.java b/aai-core/src/test/java/org/onap/aai/serialization/db/AAICoreFakeEdgesConfigTranslator.java
index 9c37ad99..a49394f1 100644
--- a/aai-core/src/test/java/org/onap/aai/serialization/db/AAICoreFakeEdgesConfigTranslator.java
+++ b/aai-core/src/test/java/org/onap/aai/serialization/db/AAICoreFakeEdgesConfigTranslator.java
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.serialization.db;
import java.util.*;
@@ -33,25 +34,25 @@ import org.onap.aai.setup.SchemaVersions;
*/
public class AAICoreFakeEdgesConfigTranslator extends AbstractConfigTranslator {
- public AAICoreFakeEdgesConfigTranslator(SchemaLocationsBean bean, SchemaConfigVersions schemaVersions) {
- super(bean, schemaVersions);
- }
-
- /* (non-Javadoc)
- * @see org.onap.aai.setup.ConfigTranslator#getEdgeFiles()
- */
- @Override
- public Map<SchemaVersion, List<String>> getEdgeFiles() {
- String file = "src/test/resources/dbedgerules/DbEdgeRules_test.json";
-
- Map<SchemaVersion, List<String>> files = new TreeMap<>();
- List<String> container = new ArrayList<>();
- container.add(file);
- files.put(schemaVersions.getDefaultVersion(), container);
-
- return files;
- }
-
-
+ public AAICoreFakeEdgesConfigTranslator(SchemaLocationsBean bean, SchemaConfigVersions schemaVersions) {
+ super(bean, schemaVersions);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.aai.setup.ConfigTranslator#getEdgeFiles()
+ */
+ @Override
+ public Map<SchemaVersion, List<String>> getEdgeFiles() {
+ String file = "src/test/resources/dbedgerules/DbEdgeRules_test.json";
+
+ Map<SchemaVersion, List<String>> files = new TreeMap<>();
+ List<String> container = new ArrayList<>();
+ container.add(file);
+ files.put(schemaVersions.getDefaultVersion(), container);
+
+ return files;
+ }
}
diff --git a/aai-core/src/test/java/org/onap/aai/serialization/db/AAICorePrivateEdgeTestConfigTranslator.java b/aai-core/src/test/java/org/onap/aai/serialization/db/AAICorePrivateEdgeTestConfigTranslator.java
index 149d2849..24762d57 100644
--- a/aai-core/src/test/java/org/onap/aai/serialization/db/AAICorePrivateEdgeTestConfigTranslator.java
+++ b/aai-core/src/test/java/org/onap/aai/serialization/db/AAICorePrivateEdgeTestConfigTranslator.java
@@ -17,41 +17,42 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.serialization.db;
+import java.util.*;
+
import org.onap.aai.AbstractConfigTranslator;
import org.onap.aai.setup.SchemaConfigVersions;
import org.onap.aai.setup.SchemaLocationsBean;
import org.onap.aai.setup.SchemaVersion;
import org.onap.aai.setup.SchemaVersions;
-import java.util.*;
-
/**
* Quick and dirty access to the real schema files for updating core tests
*
*/
public class AAICorePrivateEdgeTestConfigTranslator extends AbstractConfigTranslator {
- public AAICorePrivateEdgeTestConfigTranslator(SchemaLocationsBean bean, SchemaConfigVersions schemaVersions) {
- super(bean, schemaVersions);
- }
-
- /* (non-Javadoc)
- * @see org.onap.aai.setup.ConfigTranslator#getEdgeFiles()
- */
- @Override
- public Map<SchemaVersion, List<String>> getEdgeFiles() {
- String file = "src/test/resources/dbedgerules/DbEdgeRules_PrivateEdges.json";
-
- Map<SchemaVersion, List<String>> files = new TreeMap<>();
- List<String> container = new ArrayList<>();
- container.add(file);
- files.put(schemaVersions.getDefaultVersion(), container);
-
- return files;
- }
-
-
+ public AAICorePrivateEdgeTestConfigTranslator(SchemaLocationsBean bean, SchemaConfigVersions schemaVersions) {
+ super(bean, schemaVersions);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.aai.setup.ConfigTranslator#getEdgeFiles()
+ */
+ @Override
+ public Map<SchemaVersion, List<String>> getEdgeFiles() {
+ String file = "src/test/resources/dbedgerules/DbEdgeRules_PrivateEdges.json";
+
+ Map<SchemaVersion, List<String>> files = new TreeMap<>();
+ List<String> container = new ArrayList<>();
+ container.add(file);
+ files.put(schemaVersions.getDefaultVersion(), container);
+
+ return files;
+ }
}
diff --git a/aai-core/src/test/java/org/onap/aai/serialization/db/DbAliasTest.java b/aai-core/src/test/java/org/onap/aai/serialization/db/DbAliasTest.java
index d63220b7..944a4067 100644
--- a/aai-core/src/test/java/org/onap/aai/serialization/db/DbAliasTest.java
+++ b/aai-core/src/test/java/org/onap/aai/serialization/db/DbAliasTest.java
@@ -17,13 +17,28 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.serialization.db;
-import org.janusgraph.core.JanusGraphFactory;
-import org.janusgraph.core.JanusGraph;
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.when;
+
+import java.io.UnsupportedEncodingException;
+import java.lang.reflect.InvocationTargetException;
+import java.net.MalformedURLException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+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.Vertex;
+import org.janusgraph.core.JanusGraph;
+import org.janusgraph.core.JanusGraphFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -36,116 +51,100 @@ import org.onap.aai.exceptions.AAIException;
import org.onap.aai.introspection.*;
import org.onap.aai.parsers.query.QueryParser;
import org.onap.aai.schema.enums.PropertyMetadata;
-import org.onap.aai.serialization.engines.QueryStyle;
import org.onap.aai.serialization.engines.JanusGraphDBEngine;
+import org.onap.aai.serialization.engines.QueryStyle;
import org.onap.aai.serialization.engines.TransactionalGraphEngine;
import org.onap.aai.setup.SchemaVersion;
import org.springframework.test.annotation.DirtiesContext;
-import java.io.UnsupportedEncodingException;
-import java.lang.reflect.InvocationTargetException;
-import java.net.MalformedURLException;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Map;
-
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.when;
-
@RunWith(value = Parameterized.class)
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
public class DbAliasTest extends DataLinkSetup {
- private JanusGraph graph;
-
- private SchemaVersion version;
- private final ModelType introspectorFactoryType = ModelType.MOXY;
- private final DBConnectionType type = DBConnectionType.REALTIME;
- private Loader loader;
- private TransactionalGraphEngine dbEngine;
-
- @Parameterized.Parameter(value = 0)
- public QueryStyle queryStyle;
-
- @Parameterized.Parameters(name = "QueryStyle.{0}")
- public static Collection<Object[]> data() {
- return Arrays.asList(new Object[][]{
- {QueryStyle.TRAVERSAL},
- {QueryStyle.TRAVERSAL_URI}
- });
- }
-
- @Before
- public void setup() throws Exception {
- version = schemaVersions.getDepthVersion();
- graph = JanusGraphFactory.build().set("storage.backend","inmemory").open();
- loader = loaderFactory.createLoaderForVersion(introspectorFactoryType, version);
- dbEngine = new JanusGraphDBEngine(
- queryStyle,
- type,
- loader);
- }
-
- @After
- public void tearDown() {
- graph.tx().rollback();
- graph.close();
- }
-
- @Test
- public void checkOnWrite() throws AAIException, UnsupportedEncodingException, URISyntaxException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, NoSuchMethodException, InterruptedException {
- final String property = "persona-model-customization-id";
- String dbPropertyName = property;
- TransactionalGraphEngine spy = spy(this.dbEngine);
- TransactionalGraphEngine.Admin adminSpy = spy(dbEngine.asAdmin());
- Graph g = graph.newTransaction();
- GraphTraversalSource traversal = g.traversal();
- when(spy.asAdmin()).thenReturn(adminSpy);
- when(adminSpy.getTraversalSource()).thenReturn(traversal);
- DBSerializer serializer = new DBSerializer(version, spy, introspectorFactoryType, "AAI_TEST");
- QueryParser uriQuery = spy.getQueryBuilder().createQueryFromURI(new URI("network/generic-vnfs/generic-vnf/key1"));
- Introspector obj = loader.introspectorFromName("generic-vnf");
- Vertex v = g.addVertex();
- Object id = v.id();
- obj.setValue("vnf-id", "key1");
- obj.setValue(property, "hello");
- serializer.serializeToDb(obj, v, uriQuery, "", "");
- g.tx().commit();
- v = graph.traversal().V(id).next();
- Map<PropertyMetadata, String> map = obj.getPropertyMetadata(property);
- if (map.containsKey(PropertyMetadata.DB_ALIAS)) {
- dbPropertyName = map.get(PropertyMetadata.DB_ALIAS);
- }
-
- assertEquals("dbAlias is ", "model-customization-id", dbPropertyName);
- assertEquals("dbAlias property exists", "hello", v.property(dbPropertyName).orElse(""));
- assertEquals("model property does not", "missing", v.property(property).orElse("missing"));
-
- }
-
- @Test
- public void checkOnRead() throws AAIException, UnsupportedEncodingException, URISyntaxException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, NoSuchMethodException, InterruptedException, MalformedURLException {
- final String property = "persona-model-customization-id";
-
- TransactionalGraphEngine spy = spy(dbEngine);
- TransactionalGraphEngine.Admin adminSpy = spy(dbEngine.asAdmin());
- Vertex v = graph.traversal().addV("vnf-id", "key1", "model-customization-id", "hello").next();
- graph.tx().commit();
- Graph g = graph.newTransaction();
- GraphTraversalSource traversal = g.traversal();
- when(spy.asAdmin()).thenReturn(adminSpy);
- when(adminSpy.getTraversalSource()).thenReturn(traversal);
- DBSerializer serializer = new DBSerializer(version, spy, introspectorFactoryType, "AAI_TEST");
- Introspector obj = loader.introspectorFromName("generic-vnf");
- serializer.dbToObject(Collections.singletonList(v), obj, 0, true, "false");
-
- assertEquals("dbAlias property exists", "hello", obj.getValue(property));
-
- }
-
+ private JanusGraph graph;
+
+ private SchemaVersion version;
+ private final ModelType introspectorFactoryType = ModelType.MOXY;
+ private final DBConnectionType type = DBConnectionType.REALTIME;
+ private Loader loader;
+ private TransactionalGraphEngine dbEngine;
+
+ @Parameterized.Parameter(value = 0)
+ public QueryStyle queryStyle;
+
+ @Parameterized.Parameters(name = "QueryStyle.{0}")
+ public static Collection<Object[]> data() {
+ return Arrays.asList(new Object[][] {{QueryStyle.TRAVERSAL}, {QueryStyle.TRAVERSAL_URI}});
+ }
+
+ @Before
+ public void setup() throws Exception {
+ version = schemaVersions.getDepthVersion();
+ graph = JanusGraphFactory.build().set("storage.backend", "inmemory").open();
+ loader = loaderFactory.createLoaderForVersion(introspectorFactoryType, version);
+ dbEngine = new JanusGraphDBEngine(queryStyle, type, loader);
+ }
+
+ @After
+ public void tearDown() {
+ graph.tx().rollback();
+ graph.close();
+ }
+
+ @Test
+ public void checkOnWrite() throws AAIException, UnsupportedEncodingException, URISyntaxException, SecurityException,
+ IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException,
+ NoSuchMethodException, InterruptedException {
+ final String property = "persona-model-customization-id";
+ String dbPropertyName = property;
+ TransactionalGraphEngine spy = spy(this.dbEngine);
+ TransactionalGraphEngine.Admin adminSpy = spy(dbEngine.asAdmin());
+ Graph g = graph.newTransaction();
+ GraphTraversalSource traversal = g.traversal();
+ when(spy.asAdmin()).thenReturn(adminSpy);
+ when(adminSpy.getTraversalSource()).thenReturn(traversal);
+ DBSerializer serializer = new DBSerializer(version, spy, introspectorFactoryType, "AAI_TEST");
+ QueryParser uriQuery =
+ spy.getQueryBuilder().createQueryFromURI(new URI("network/generic-vnfs/generic-vnf/key1"));
+ Introspector obj = loader.introspectorFromName("generic-vnf");
+ Vertex v = g.addVertex();
+ Object id = v.id();
+ obj.setValue("vnf-id", "key1");
+ obj.setValue(property, "hello");
+ serializer.serializeToDb(obj, v, uriQuery, "", "");
+ g.tx().commit();
+ v = graph.traversal().V(id).next();
+ Map<PropertyMetadata, String> map = obj.getPropertyMetadata(property);
+ if (map.containsKey(PropertyMetadata.DB_ALIAS)) {
+ dbPropertyName = map.get(PropertyMetadata.DB_ALIAS);
+ }
+
+ assertEquals("dbAlias is ", "model-customization-id", dbPropertyName);
+ assertEquals("dbAlias property exists", "hello", v.property(dbPropertyName).orElse(""));
+ assertEquals("model property does not", "missing", v.property(property).orElse("missing"));
+
+ }
+
+ @Test
+ public void checkOnRead() throws AAIException, UnsupportedEncodingException, URISyntaxException, SecurityException,
+ IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException,
+ NoSuchMethodException, InterruptedException, MalformedURLException {
+ final String property = "persona-model-customization-id";
+
+ TransactionalGraphEngine spy = spy(dbEngine);
+ TransactionalGraphEngine.Admin adminSpy = spy(dbEngine.asAdmin());
+ Vertex v = graph.traversal().addV("vnf-id", "key1", "model-customization-id", "hello").next();
+ graph.tx().commit();
+ Graph g = graph.newTransaction();
+ GraphTraversalSource traversal = g.traversal();
+ when(spy.asAdmin()).thenReturn(adminSpy);
+ when(adminSpy.getTraversalSource()).thenReturn(traversal);
+ DBSerializer serializer = new DBSerializer(version, spy, introspectorFactoryType, "AAI_TEST");
+ Introspector obj = loader.introspectorFromName("generic-vnf");
+ serializer.dbToObject(Collections.singletonList(v), obj, 0, true, "false");
+
+ assertEquals("dbAlias property exists", "hello", obj.getValue(property));
+
+ }
}
diff --git a/aai-core/src/test/java/org/onap/aai/serialization/db/DbSerializerTest.java b/aai-core/src/test/java/org/onap/aai/serialization/db/DbSerializerTest.java
index cbc1bd9a..b50adf2a 100644
--- a/aai-core/src/test/java/org/onap/aai/serialization/db/DbSerializerTest.java
+++ b/aai-core/src/test/java/org/onap/aai/serialization/db/DbSerializerTest.java
@@ -17,18 +17,28 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.serialization.db;
-import org.janusgraph.core.JanusGraphFactory;
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.*;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.when;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.*;
+
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.structure.*;
import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph;
+import org.janusgraph.core.JanusGraphFactory;
import org.junit.*;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.onap.aai.AAISetup;
-import org.onap.aai.util.AAIConstants;
import org.onap.aai.db.props.AAIProperties;
import org.onap.aai.dbmap.DBConnectionType;
import org.onap.aai.edges.EdgeIngestor;
@@ -36,871 +46,871 @@ import org.onap.aai.edges.enums.EdgeType;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.introspection.*;
import org.onap.aai.parsers.query.QueryParser;
-import org.onap.aai.serialization.engines.QueryStyle;
import org.onap.aai.serialization.engines.JanusGraphDBEngine;
+import org.onap.aai.serialization.engines.QueryStyle;
import org.onap.aai.serialization.engines.TransactionalGraphEngine;
import org.onap.aai.setup.SchemaVersion;
+import org.onap.aai.util.AAIConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.DirtiesContext;
-import java.io.UnsupportedEncodingException;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.util.*;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.*;
-import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.when;
-
@RunWith(value = Parameterized.class)
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
public class DbSerializerTest extends AAISetup {
- //to use, set thrown.expect to whatever your test needs
- //this line establishes default of expecting no exception to be thrown
- @Rule
- public ExpectedException thrown = ExpectedException.none();
-
- protected static Graph graph;
-
- @Autowired
- protected EdgeSerializer edgeSer;
- @Autowired
- protected EdgeIngestor ei;
-
- private SchemaVersion version;
- private final ModelType introspectorFactoryType = ModelType.MOXY;
- private final DBConnectionType type = DBConnectionType.REALTIME;
- private Loader loader;
- private TransactionalGraphEngine dbEngine;
- private TransactionalGraphEngine engine; //for tests that aren't mocking the engine
- private DBSerializer dbser;
- TransactionalGraphEngine spy;
- TransactionalGraphEngine.Admin adminSpy;
-
- @Parameterized.Parameter(value = 0)
- public QueryStyle queryStyle;
-
- @Parameterized.Parameters(name = "QueryStyle.{0}")
- public static Collection<Object[]> data() {
- return Arrays.asList(new Object[][]{
- {QueryStyle.TRAVERSAL},
- {QueryStyle.TRAVERSAL_URI}
- });
- }
-
- @BeforeClass
- public static void init() throws Exception {
- graph = JanusGraphFactory.build().set("storage.backend", "inmemory").open();
-
- }
-
- @Before
- public void setup() throws Exception {
- //createGraph();
+ // to use, set thrown.expect to whatever your test needs
+ // this line establishes default of expecting no exception to be thrown
+ @Rule
+ public ExpectedException thrown = ExpectedException.none();
+
+ protected static Graph graph;
+
+ @Autowired
+ protected EdgeSerializer edgeSer;
+ @Autowired
+ protected EdgeIngestor ei;
+
+ private SchemaVersion version;
+ private final ModelType introspectorFactoryType = ModelType.MOXY;
+ private final DBConnectionType type = DBConnectionType.REALTIME;
+ private Loader loader;
+ private TransactionalGraphEngine dbEngine;
+ private TransactionalGraphEngine engine; // for tests that aren't mocking the engine
+ private DBSerializer dbser;
+ TransactionalGraphEngine spy;
+ TransactionalGraphEngine.Admin adminSpy;
+
+ @Parameterized.Parameter(value = 0)
+ public QueryStyle queryStyle;
+
+ @Parameterized.Parameters(name = "QueryStyle.{0}")
+ public static Collection<Object[]> data() {
+ return Arrays.asList(new Object[][] {{QueryStyle.TRAVERSAL}, {QueryStyle.TRAVERSAL_URI}});
+ }
+
+ @BeforeClass
+ public static void init() throws Exception {
+ graph = JanusGraphFactory.build().set("storage.backend", "inmemory").open();
+
+ }
+
+ @Before
+ public void setup() throws Exception {
+ // createGraph();
version = schemaVersions.getDefaultVersion();
- loader = loaderFactory.createLoaderForVersion(introspectorFactoryType, version);
- dbEngine = new JanusGraphDBEngine(queryStyle, type, loader);
- spy = spy(dbEngine);
- adminSpy = spy(dbEngine.asAdmin());
-
-
- engine = new JanusGraphDBEngine(queryStyle, type, loader);
- dbser = new DBSerializer(version, engine, introspectorFactoryType, "AAI-TEST");
- }
-
- @Test
- public void testFindDeletableDoesNotReturnDuplicates() throws AAIException {
-
- Vertex genericVnf1 = graph.addVertex("aai-node-type", "generic-vnf", "vnf-id", "vnf1", "vnf-name", "vnfName1");
-
- Vertex lInterface1 = graph.addVertex("aai-node-type", "l-interface", "interface-name", "lInterface1");
- Vertex lInterface2 = graph.addVertex("aai-node-type", "l-interface", "interface-name", "lInterface2");
-
- Vertex logicalLink1 = graph.addVertex("aai-node-type", "logical-link", "link-name", "logicalLink1");
- Vertex logicalLink2 = graph.addVertex("aai-node-type", "logical-link", "link-name", "logicalLink2");
-
- GraphTraversalSource g = graph.traversal();
-
- edgeSer.addTreeEdge(g, genericVnf1, lInterface1);
- edgeSer.addTreeEdge(g, genericVnf1, lInterface2);
- edgeSer.addEdge(g, lInterface1, logicalLink1);
- edgeSer.addEdge(g, lInterface1, logicalLink2);
- // This line will cause the logical link2 to be found twice under linterface 1
- // and also under the linterface 2 and since in the past deletable returned
- // duplicates this test checks that it shouldn't return duplicates
- edgeSer.addEdge(g, lInterface2, logicalLink2);
-
- when(spy.asAdmin()).thenReturn(adminSpy);
- when(adminSpy.getTraversalSource()).thenReturn(g);
- when(adminSpy.getReadOnlyTraversalSource()).thenReturn(g);
-
- List<Vertex> deletableVertexes = spy.getQueryEngine().findDeletable(genericVnf1);
- Set<Vertex> vertexSet = new HashSet<>();
-
- for (Vertex deletableVertex : deletableVertexes) {
- if(!vertexSet.contains(deletableVertex)){
- vertexSet.add(deletableVertex);
- } else {
- fail("Find deletable is returning a list of duplicate vertexes");
- }
- }
- }
-
- @After
- public void tearDown() throws Exception {
- engine.rollback();
- }
-
- @AfterClass
- public static void destroy() throws Exception {
- graph.close();
- }
-
-
- public void subnetSetup() throws AAIException {
- /*
- * This setus up the test graph, For future junits , add more vertices
- * and edges
- */
-
- Vertex l3interipv4addresslist_1 = graph.traversal().addV("aai-node-type", "l3-interface-ipv4-address-list",
- "l3-interface-ipv4-address", "l3-interface-ipv4-address-1").next();
- Vertex subnet_2 = graph.traversal().addV("aai-node-type", "subnet", "subnet-id", "subnet-id-2").next();
- Vertex l3interipv6addresslist_3 = graph.traversal().addV("aai-node-type", "l3-interface-ipv6-address-list",
- "l3-interface-ipv6-address", "l3-interface-ipv6-address-3").next();
- Vertex subnet_4 = graph.traversal().addV("aai-node-type", "subnet", "subnet-id", "subnet-id-4").next();
- Vertex subnet_5 = graph.traversal().addV("aai-node-type", "subnet", "subnet-id", "subnet-id-5").next();
- Vertex l3network_6 = graph.traversal()
- .addV("aai-node-type", "l3-network", "network-id", "network-id-6", "network-name", "network-name-6")
- .next();
-
- GraphTraversalSource g = graph.traversal();
- edgeSer.addEdge(g, l3interipv4addresslist_1, subnet_2);
- edgeSer.addEdge(g, l3interipv6addresslist_3, subnet_4);
- edgeSer.addTreeEdge(g, subnet_5, l3network_6);
- }
-
-
- public void l3NetworkSetup() throws AAIException {
- /*
- * This setus up the test graph, For future junits , add more vertices
- * and edges
- */
-
- Vertex l3network1 = graph.addVertex("aai-node-type", "l3-network", "network-id", "network-id-v1", "network-name", "network-name-v1");
- Vertex l3network2 = graph.addVertex("aai-node-type", "l3-network", "network-id", "network-id-v2", "network-name", "network-name-v2");
- Vertex subnet1 = graph.addVertex("aai-node-type", "subnet", "subnet-id", "subnet-id-v1");
- Vertex subnet2 = graph.addVertex("aai-node-type", "subnet", "subnet-id", "subnet-id-v2");
-
- Vertex l3interipv4addresslist_1 = graph.addVertex("aai-node-type", "l3-interface-ipv4-address-list",
- "l3-interface-ipv4-address", "l3-intr-v1");
- Vertex l3interipv6addresslist_1 = graph.addVertex("aai-node-type", "l3-interface-ipv6-address-list",
- "l3-interface-ipv6-address", "l3-interface-ipv6-v1");
-
-
-
-
-
- GraphTraversalSource g = graph.traversal();
- edgeSer.addTreeEdge(g, subnet1, l3network1);
- edgeSer.addEdge(g, l3interipv4addresslist_1, subnet1);
- edgeSer.addEdge(g, l3interipv6addresslist_1, subnet1);
+ loader = loaderFactory.createLoaderForVersion(introspectorFactoryType, version);
+ dbEngine = new JanusGraphDBEngine(queryStyle, type, loader);
+ spy = spy(dbEngine);
+ adminSpy = spy(dbEngine.asAdmin());
- edgeSer.addTreeEdge(g, subnet2, l3network2);
+ engine = new JanusGraphDBEngine(queryStyle, type, loader);
+ dbser = new DBSerializer(version, engine, introspectorFactoryType, "AAI-TEST");
+ }
+ @Test
+ public void testFindDeletableDoesNotReturnDuplicates() throws AAIException {
+
+ Vertex genericVnf1 = graph.addVertex("aai-node-type", "generic-vnf", "vnf-id", "vnf1", "vnf-name", "vnfName1");
+
+ Vertex lInterface1 = graph.addVertex("aai-node-type", "l-interface", "interface-name", "lInterface1");
+ Vertex lInterface2 = graph.addVertex("aai-node-type", "l-interface", "interface-name", "lInterface2");
+
+ Vertex logicalLink1 = graph.addVertex("aai-node-type", "logical-link", "link-name", "logicalLink1");
+ Vertex logicalLink2 = graph.addVertex("aai-node-type", "logical-link", "link-name", "logicalLink2");
+
+ GraphTraversalSource g = graph.traversal();
+
+ edgeSer.addTreeEdge(g, genericVnf1, lInterface1);
+ edgeSer.addTreeEdge(g, genericVnf1, lInterface2);
+ edgeSer.addEdge(g, lInterface1, logicalLink1);
+ edgeSer.addEdge(g, lInterface1, logicalLink2);
+ // This line will cause the logical link2 to be found twice under linterface 1
+ // and also under the linterface 2 and since in the past deletable returned
+ // duplicates this test checks that it shouldn't return duplicates
+ edgeSer.addEdge(g, lInterface2, logicalLink2);
+
+ when(spy.asAdmin()).thenReturn(adminSpy);
+ when(adminSpy.getTraversalSource()).thenReturn(g);
+ when(adminSpy.getReadOnlyTraversalSource()).thenReturn(g);
+
+ List<Vertex> deletableVertexes = spy.getQueryEngine().findDeletable(genericVnf1);
+ Set<Vertex> vertexSet = new HashSet<>();
+
+ for (Vertex deletableVertex : deletableVertexes) {
+ if (!vertexSet.contains(deletableVertex)) {
+ vertexSet.add(deletableVertex);
+ } else {
+ fail("Find deletable is returning a list of duplicate vertexes");
+ }
+ }
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ engine.rollback();
+ }
+
+ @AfterClass
+ public static void destroy() throws Exception {
+ graph.close();
+ }
+
+ public void subnetSetup() throws AAIException {
+ /*
+ * This setus up the test graph, For future junits , add more vertices
+ * and edges
+ */
+
+ Vertex l3interipv4addresslist_1 = graph.traversal().addV("aai-node-type", "l3-interface-ipv4-address-list",
+ "l3-interface-ipv4-address", "l3-interface-ipv4-address-1").next();
+ Vertex subnet_2 = graph.traversal().addV("aai-node-type", "subnet", "subnet-id", "subnet-id-2").next();
+ Vertex l3interipv6addresslist_3 = graph.traversal().addV("aai-node-type", "l3-interface-ipv6-address-list",
+ "l3-interface-ipv6-address", "l3-interface-ipv6-address-3").next();
+ Vertex subnet_4 = graph.traversal().addV("aai-node-type", "subnet", "subnet-id", "subnet-id-4").next();
+ Vertex subnet_5 = graph.traversal().addV("aai-node-type", "subnet", "subnet-id", "subnet-id-5").next();
+ Vertex l3network_6 = graph.traversal()
+ .addV("aai-node-type", "l3-network", "network-id", "network-id-6", "network-name", "network-name-6")
+ .next();
+
+ GraphTraversalSource g = graph.traversal();
+ edgeSer.addEdge(g, l3interipv4addresslist_1, subnet_2);
+ edgeSer.addEdge(g, l3interipv6addresslist_3, subnet_4);
+ edgeSer.addTreeEdge(g, subnet_5, l3network_6);
+ }
+
+ public void l3NetworkSetup() throws AAIException {
+ /*
+ * This setus up the test graph, For future junits , add more vertices
+ * and edges
+ */
+
+ Vertex l3network1 = graph.addVertex("aai-node-type", "l3-network", "network-id", "network-id-v1",
+ "network-name", "network-name-v1");
+ Vertex l3network2 = graph.addVertex("aai-node-type", "l3-network", "network-id", "network-id-v2",
+ "network-name", "network-name-v2");
+ Vertex subnet1 = graph.addVertex("aai-node-type", "subnet", "subnet-id", "subnet-id-v1");
+ Vertex subnet2 = graph.addVertex("aai-node-type", "subnet", "subnet-id", "subnet-id-v2");
+
+ Vertex l3interipv4addresslist_1 = graph.addVertex("aai-node-type", "l3-interface-ipv4-address-list",
+ "l3-interface-ipv4-address", "l3-intr-v1");
+ Vertex l3interipv6addresslist_1 = graph.addVertex("aai-node-type", "l3-interface-ipv6-address-list",
+ "l3-interface-ipv6-address", "l3-interface-ipv6-v1");
+
+ GraphTraversalSource g = graph.traversal();
+ edgeSer.addTreeEdge(g, subnet1, l3network1);
+ edgeSer.addEdge(g, l3interipv4addresslist_1, subnet1);
+ edgeSer.addEdge(g, l3interipv6addresslist_1, subnet1);
+
+ edgeSer.addTreeEdge(g, subnet2, l3network2);
+
+ }
+
+ public void vserverSetup() throws AAIException {
+ /*
+ * This setus up the test graph, For future junits , add more vertices
+ * and edges
+ */
+
+ Vertex vserver1 = graph.addVertex("aai-node-type", "vserver", "vserver-id", "vss1",
+ AAIProperties.AAI_URI.toString(),
+ "/cloud-infrastructure/cloud-regions/cloud-region/me/123/tenants/tenant/453/vservers/vserver/vss1");
+
+ Vertex lInterface1 = graph.addVertex("aai-node-type", "l-interface", "interface-name", "lIntr1");
+ Vertex lInterface2 = graph.addVertex("aai-node-type", "l-interface", "interface-name", "lIntr2");
+
+ Vertex logicalLink1 = graph.addVertex("aai-node-type", "logical-link", "link-name", "logLink1");
+ Vertex logicalLink2 = graph.addVertex("aai-node-type", "logical-link", "link-name", "logLink2");
+
+ Vertex l3interipv4addresslist_1 = graph.addVertex("aai-node-type", "l3-interface-ipv4-address-list",
+ "l3-interface-ipv4-address", "l3-intr-ipv4-address-1");
+ Vertex l3interipv6addresslist_2 = graph.addVertex("aai-node-type", "l3-interface-ipv6-address-list",
+ "l3-interface-ipv4-address", "l3-intr-ipv6-address-1");
+
+ GraphTraversalSource g = graph.traversal();
+
+ edgeSer.addTreeEdge(g, lInterface1, vserver1);
+ edgeSer.addTreeEdge(g, lInterface2, vserver1);
+ edgeSer.addTreeEdge(g, l3interipv4addresslist_1, lInterface1);
+ edgeSer.addTreeEdge(g, l3interipv6addresslist_2, lInterface2);
+
+ edgeSer.addEdge(g, lInterface1, logicalLink1);
+ edgeSer.addEdge(g, lInterface2, logicalLink2);
+ }
+ @Test
+ public void subnetDelWithInEdgesIpv4Test() throws AAIException {
+ subnetSetup();
+ String expected_message =
+ "Object is being reference by additional objects preventing it from being deleted. Please clean up references from the following types [l3-interface-ipv4-address-list]";
- }
-
- public void vserverSetup() throws AAIException {
- /*
- * This setus up the test graph, For future junits , add more vertices
- * and edges
- */
-
- Vertex vserver1 = graph.addVertex("aai-node-type", "vserver", "vserver-id", "vss1",
- AAIProperties.AAI_URI.toString(),
- "/cloud-infrastructure/cloud-regions/cloud-region/me/123/tenants/tenant/453/vservers/vserver/vss1");
-
- Vertex lInterface1 = graph.addVertex("aai-node-type", "l-interface", "interface-name", "lIntr1");
- Vertex lInterface2 = graph.addVertex("aai-node-type", "l-interface", "interface-name", "lIntr2");
-
- Vertex logicalLink1 = graph.addVertex("aai-node-type", "logical-link", "link-name", "logLink1");
- Vertex logicalLink2 = graph.addVertex("aai-node-type", "logical-link", "link-name", "logLink2");
-
- Vertex l3interipv4addresslist_1 = graph.addVertex("aai-node-type", "l3-interface-ipv4-address-list",
- "l3-interface-ipv4-address", "l3-intr-ipv4-address-1");
- Vertex l3interipv6addresslist_2 = graph.addVertex("aai-node-type", "l3-interface-ipv6-address-list",
- "l3-interface-ipv4-address", "l3-intr-ipv6-address-1");
-
- GraphTraversalSource g = graph.traversal();
-
- edgeSer.addTreeEdge(g, lInterface1, vserver1);
- edgeSer.addTreeEdge(g, lInterface2, vserver1);
- edgeSer.addTreeEdge(g, l3interipv4addresslist_1, lInterface1);
- edgeSer.addTreeEdge(g, l3interipv6addresslist_2, lInterface2);
-
- edgeSer.addEdge(g, lInterface1, logicalLink1);
- edgeSer.addEdge(g, lInterface2, logicalLink2);
- }
-
- @Test
- public void subnetDelWithInEdgesIpv4Test() throws AAIException {
- subnetSetup();
- String expected_message = "Object is being reference by additional objects preventing it from being deleted. Please clean up references from the following types [l3-interface-ipv4-address-list]";
-
- /*
- * This subnet has in-edges with l3-ipv4 and NOT ok to delete
- */
- Vertex subnet = graph.traversal().V().has("aai-node-type", "subnet").has("subnet-id", "subnet-id-2").next();
+ /*
+ * This subnet has in-edges with l3-ipv4 and NOT ok to delete
+ */
+ Vertex subnet = graph.traversal().V().has("aai-node-type", "subnet").has("subnet-id", "subnet-id-2").next();
- String exceptionMessage = testCascadeDelete(subnet);
- assertEquals(expected_message, exceptionMessage);
+ String exceptionMessage = testCascadeDelete(subnet);
+ assertEquals(expected_message, exceptionMessage);
- }
+ }
- @Test
- public void subnetDelWithInEdgesIpv6Test() throws AAIException {
- subnetSetup();
- String expected_message = "Object is being reference by additional objects preventing it from being deleted. Please clean up references from the following types [l3-interface-ipv6-address-list]";
+ @Test
+ public void subnetDelWithInEdgesIpv6Test() throws AAIException {
+ subnetSetup();
+ String expected_message =
+ "Object is being reference by additional objects preventing it from being deleted. Please clean up references from the following types [l3-interface-ipv6-address-list]";
- /*
- * This subnet has in-edges with l3-ipv6 and NOT ok to delete
- */
- Vertex subnet = graph.traversal().V().has("aai-node-type", "subnet").has("subnet-id", "subnet-id-4").next();
- String exceptionMessage = testCascadeDelete(subnet);
- assertEquals(expected_message, exceptionMessage);
+ /*
+ * This subnet has in-edges with l3-ipv6 and NOT ok to delete
+ */
+ Vertex subnet = graph.traversal().V().has("aai-node-type", "subnet").has("subnet-id", "subnet-id-4").next();
+ String exceptionMessage = testCascadeDelete(subnet);
+ assertEquals(expected_message, exceptionMessage);
- }
+ }
- @Test
- public void subnetDelWithInEdgesL3network() throws AAIException {
- subnetSetup();
- String expected_message = "";
+ @Test
+ public void subnetDelWithInEdgesL3network() throws AAIException {
+ subnetSetup();
+ String expected_message = "";
- /*
- * This subnet has in-edges with l3-network and ok to delete
- */
- Vertex subnet = graph.traversal().V().has("aai-node-type", "subnet").has("subnet-id", "subnet-id-5").next();
+ /*
+ * This subnet has in-edges with l3-network and ok to delete
+ */
+ Vertex subnet = graph.traversal().V().has("aai-node-type", "subnet").has("subnet-id", "subnet-id-5").next();
- String exceptionMessage = testCascadeDelete(subnet);
- assertEquals(expected_message, exceptionMessage);
+ String exceptionMessage = testCascadeDelete(subnet);
+ assertEquals(expected_message, exceptionMessage);
- }
+ }
- public String testCascadeDelete(Vertex v) throws AAIException {
+ public String testCascadeDelete(Vertex v) throws AAIException {
- GraphTraversalSource traversal = graph.traversal();
- when(spy.asAdmin()).thenReturn(adminSpy);
- when(adminSpy.getTraversalSource()).thenReturn(traversal);
- when(adminSpy.getReadOnlyTraversalSource()).thenReturn(traversal);
+ GraphTraversalSource traversal = graph.traversal();
+ when(spy.asAdmin()).thenReturn(adminSpy);
+ when(adminSpy.getTraversalSource()).thenReturn(traversal);
+ when(adminSpy.getReadOnlyTraversalSource()).thenReturn(traversal);
- String exceptionMessage = "";
- DBSerializer serializer = new DBSerializer(version, spy, introspectorFactoryType, "AAI_TEST");
- List<Vertex> deletableVertices = spy.getQueryEngine().findDeletable(v);
+ String exceptionMessage = "";
+ DBSerializer serializer = new DBSerializer(version, spy, introspectorFactoryType, "AAI_TEST");
+ List<Vertex> deletableVertices = spy.getQueryEngine().findDeletable(v);
- try {
- serializer.delete(v, deletableVertices, "resourceVersion", false);
- } catch (AAIException exception) {
- exceptionMessage = exception.getMessage();
- }
- return exceptionMessage;
+ try {
+ serializer.delete(v, deletableVertices, "resourceVersion", false);
+ } catch (AAIException exception) {
+ exceptionMessage = exception.getMessage();
+ }
+ return exceptionMessage;
- }
+ }
- public String testDelete(Vertex v) throws AAIException {
+ public String testDelete(Vertex v) throws AAIException {
- GraphTraversalSource traversal = graph.traversal();
- when(spy.asAdmin()).thenReturn(adminSpy);
- when(adminSpy.getTraversalSource()).thenReturn(traversal);
- when(adminSpy.getReadOnlyTraversalSource()).thenReturn(traversal);
+ GraphTraversalSource traversal = graph.traversal();
+ when(spy.asAdmin()).thenReturn(adminSpy);
+ when(adminSpy.getTraversalSource()).thenReturn(traversal);
+ when(adminSpy.getReadOnlyTraversalSource()).thenReturn(traversal);
- String exceptionMessage = "";
- DBSerializer serializer = new DBSerializer(version, spy, introspectorFactoryType, "AAI_TEST");
+ String exceptionMessage = "";
+ DBSerializer serializer = new DBSerializer(version, spy, introspectorFactoryType, "AAI_TEST");
- try {
- serializer.delete(v, "resourceVersion", false);
- } catch (AAIException exception) {
- exceptionMessage = exception.getMessage();
- }
- return exceptionMessage;
+ try {
+ serializer.delete(v, "resourceVersion", false);
+ } catch (AAIException exception) {
+ exceptionMessage = exception.getMessage();
+ }
+ return exceptionMessage;
- }
+ }
- @Test
- public void createNewVertexTest() throws AAIException {
- engine.startTransaction();
+ @Test
+ public void createNewVertexTest() throws AAIException {
+ engine.startTransaction();
- Introspector testObj = loader.introspectorFromName("generic-vnf");
+ Introspector testObj = loader.introspectorFromName("generic-vnf");
- Vertex testVertex = dbser.createNewVertex(testObj);
- Vertex fromGraph = engine.tx().traversal().V().has("aai-node-type","generic-vnf").toList().get(0);
- assertEquals(testVertex.id(), fromGraph.id());
- assertEquals("AAI-TEST", fromGraph.property(AAIProperties.SOURCE_OF_TRUTH.toString()).value());
+ Vertex testVertex = dbser.createNewVertex(testObj);
+ Vertex fromGraph = engine.tx().traversal().V().has("aai-node-type", "generic-vnf").toList().get(0);
+ assertEquals(testVertex.id(), fromGraph.id());
+ assertEquals("AAI-TEST", fromGraph.property(AAIProperties.SOURCE_OF_TRUTH.toString()).value());
- }
+ }
@Test
- public void touchStandardVertexPropertiesTest() throws AAIException, InterruptedException {
- engine.startTransaction();
+ public void touchStandardVertexPropertiesTest() throws AAIException, InterruptedException {
+ engine.startTransaction();
- //if this test runs through too fast the value may not change, causing the test to fail. sleeping ensures a different value
+ // if this test runs through too fast the value may not change, causing the test to fail. sleeping ensures a
+ // different value
Thread.sleep(2);
- DBSerializer dbser2 = new DBSerializer(version, engine, introspectorFactoryType, "AAI-TEST-2");
- Vertex vert = graph.addVertex("aai-node-type", "generic-vnf");
+ DBSerializer dbser2 = new DBSerializer(version, engine, introspectorFactoryType, "AAI-TEST-2");
+ Vertex vert = graph.addVertex("aai-node-type", "generic-vnf");
- // Upon first creation of the Vertex and the DBSerializer
+ // Upon first creation of the Vertex and the DBSerializer
// the source of truth and created-ts should be the same as their modified counterparts
dbser2.touchStandardVertexProperties(vert, true);
- String createTS = (String)vert.property(AAIProperties.CREATED_TS).value();
- String modTS = (String)vert.property(AAIProperties.LAST_MOD_TS).value();
- String sot = (String)vert.property(AAIProperties.SOURCE_OF_TRUTH).value();
- String lastModSOT = (String)vert.property(AAIProperties.LAST_MOD_SOURCE_OF_TRUTH).value();
+ String createTS = (String) vert.property(AAIProperties.CREATED_TS).value();
+ String modTS = (String) vert.property(AAIProperties.LAST_MOD_TS).value();
+ String sot = (String) vert.property(AAIProperties.SOURCE_OF_TRUTH).value();
+ String lastModSOT = (String) vert.property(AAIProperties.LAST_MOD_SOURCE_OF_TRUTH).value();
assertTrue(createTS.equals(modTS));
assertTrue(sot.equals(lastModSOT));
- //if this test runs through too fast the value may not change, causing the test to fail. sleeping ensures a different value
+ // if this test runs through too fast the value may not change, causing the test to fail. sleeping ensures a
+ // different value
Thread.sleep(2);
// Not new vertex && new DBSerializer (A new serializer since a new one will be created per transaction)
// Here the vertex will be modified by a different source of truth
DBSerializer dbser3 = new DBSerializer(version, engine, introspectorFactoryType, "AAI-TEST-3");
dbser3.touchStandardVertexProperties(vert, false);
- createTS = (String)vert.property(AAIProperties.CREATED_TS).value();
- modTS = (String)vert.property(AAIProperties.LAST_MOD_TS).value();
- sot = (String)vert.property(AAIProperties.SOURCE_OF_TRUTH).value();
- lastModSOT = (String)vert.property(AAIProperties.LAST_MOD_SOURCE_OF_TRUTH).value();
+ createTS = (String) vert.property(AAIProperties.CREATED_TS).value();
+ modTS = (String) vert.property(AAIProperties.LAST_MOD_TS).value();
+ sot = (String) vert.property(AAIProperties.SOURCE_OF_TRUTH).value();
+ lastModSOT = (String) vert.property(AAIProperties.LAST_MOD_SOURCE_OF_TRUTH).value();
assertFalse(createTS.equals(modTS));
assertFalse(sot.equals(lastModSOT));
- //if this test runs through too fast the value may not change, causing the test to fail. sleeping ensures a different value
+ // if this test runs through too fast the value may not change, causing the test to fail. sleeping ensures a
+ // different value
Thread.sleep(2);
// The currentTimeMillis used for the created-ts and modified-ts is created at DBSerializer instantiation
- // Every REST transaction should create a new DBSerializer - thus a new currentTimeMillis is used at the time of transaction.
+ // Every REST transaction should create a new DBSerializer - thus a new currentTimeMillis is used at the time of
+ // transaction.
// Using an existing vertex, but treating it as new && using an older DBSerializer
- dbser.touchStandardVertexProperties(vert, true);
- String resverStart = (String)vert.property(AAIProperties.RESOURCE_VERSION).value();
- String lastModTimeStart = (String)vert.property(AAIProperties.LAST_MOD_TS).value();
- createTS = (String)vert.property(AAIProperties.CREATED_TS).value();
- modTS = (String)vert.property(AAIProperties.LAST_MOD_TS).value();
+ dbser.touchStandardVertexProperties(vert, true);
+ String resverStart = (String) vert.property(AAIProperties.RESOURCE_VERSION).value();
+ String lastModTimeStart = (String) vert.property(AAIProperties.LAST_MOD_TS).value();
+ createTS = (String) vert.property(AAIProperties.CREATED_TS).value();
+ modTS = (String) vert.property(AAIProperties.LAST_MOD_TS).value();
assertTrue(createTS.equals(modTS));
assertEquals("AAI-TEST", vert.property(AAIProperties.LAST_MOD_SOURCE_OF_TRUTH).value());
- //if this test runs through too fast the value may not change, causing the test to fail. sleeping ensures a different value
+ // if this test runs through too fast the value may not change, causing the test to fail. sleeping ensures a
+ // different value
Thread.sleep(2);
- dbser2.touchStandardVertexProperties(vert, false);
- String resourceVer = (String)vert.property(AAIProperties.RESOURCE_VERSION).value();
- String lastModTs = (String)vert.property(AAIProperties.LAST_MOD_TS).value();
- String lastModSoT = (String)vert.property(AAIProperties.LAST_MOD_SOURCE_OF_TRUTH).value();
+ dbser2.touchStandardVertexProperties(vert, false);
+ String resourceVer = (String) vert.property(AAIProperties.RESOURCE_VERSION).value();
+ String lastModTs = (String) vert.property(AAIProperties.LAST_MOD_TS).value();
+ String lastModSoT = (String) vert.property(AAIProperties.LAST_MOD_SOURCE_OF_TRUTH).value();
- assertFalse(resverStart.equals(resourceVer));
- assertFalse(lastModTimeStart.equals(lastModTs));
- assertEquals("AAI-TEST-2", lastModSoT);
- }
+ assertFalse(resverStart.equals(resourceVer));
+ assertFalse(lastModTimeStart.equals(lastModTs));
+ assertEquals("AAI-TEST-2", lastModSoT);
+ }
- @Test
- public void touchStandardVertexPropertiesAAIUUIDTest() throws AAIException, InterruptedException {
- engine.startTransaction();
+ @Test
+ public void touchStandardVertexPropertiesAAIUUIDTest() throws AAIException, InterruptedException {
+ engine.startTransaction();
- Graph graph = TinkerGraph.open();
- Vertex v = graph.addVertex("aai-node-type", "generic-vnf");
+ Graph graph = TinkerGraph.open();
+ Vertex v = graph.addVertex("aai-node-type", "generic-vnf");
- dbser.touchStandardVertexProperties(v, true);
+ dbser.touchStandardVertexProperties(v, true);
- assertTrue(v.property(AAIProperties.AAI_UUID).isPresent());
- try {
- UUID.fromString((String)v.property(AAIProperties.AAI_UUID).value());
- } catch (IllegalArgumentException e) {
- fail("Vertex uuid is not valid uuid");
- }
- }
+ assertTrue(v.property(AAIProperties.AAI_UUID).isPresent());
+ try {
+ UUID.fromString((String) v.property(AAIProperties.AAI_UUID).value());
+ } catch (IllegalArgumentException e) {
+ fail("Vertex uuid is not valid uuid");
+ }
+ }
- @Test
- public void verifyResourceVersion_SunnyDayTest() throws AAIException {
- engine.startTransaction();
+ @Test
+ public void verifyResourceVersion_SunnyDayTest() throws AAIException {
+ engine.startTransaction();
- assertTrue(dbser.verifyResourceVersion("delete", "vnfc", "abc", "abc", "vnfcs/vnfc/vnfcId"));
+ assertTrue(dbser.verifyResourceVersion("delete", "vnfc", "abc", "abc", "vnfcs/vnfc/vnfcId"));
- }
+ }
- @Test
- public void verifyResourceVersion_CreateWithRVTest() throws AAIException {
- engine.startTransaction();
+ @Test
+ public void verifyResourceVersion_CreateWithRVTest() throws AAIException {
+ engine.startTransaction();
- thrown.expect(AAIException.class);
- thrown.expectMessage("resource-version passed for create of generic-vnfs/generic-vnf/myid");
- dbser.verifyResourceVersion("create", "generic-vnf", null, "old-res-ver", "generic-vnfs/generic-vnf/myid");
+ thrown.expect(AAIException.class);
+ thrown.expectMessage("resource-version passed for create of generic-vnfs/generic-vnf/myid");
+ dbser.verifyResourceVersion("create", "generic-vnf", null, "old-res-ver", "generic-vnfs/generic-vnf/myid");
- }
+ }
- @Test
- public void verifyResourceVersion_MissingRVTest() throws AAIException {
- engine.startTransaction();
+ @Test
+ public void verifyResourceVersion_MissingRVTest() throws AAIException {
+ engine.startTransaction();
- thrown.expect(AAIException.class);
- thrown.expectMessage("resource-version not passed for update of generic-vnfs/generic-vnf/myid");
- dbser.verifyResourceVersion("update", "generic-vnf", "current-res-ver", null, "generic-vnfs/generic-vnf/myid");
+ thrown.expect(AAIException.class);
+ thrown.expectMessage("resource-version not passed for update of generic-vnfs/generic-vnf/myid");
+ dbser.verifyResourceVersion("update", "generic-vnf", "current-res-ver", null, "generic-vnfs/generic-vnf/myid");
- }
+ }
- @Test
- public void verifyResourceVersion_MismatchRVTest() throws AAIException {
- engine.startTransaction();
+ @Test
+ public void verifyResourceVersion_MismatchRVTest() throws AAIException {
+ engine.startTransaction();
- thrown.expect(AAIException.class);
- thrown.expectMessage("resource-version MISMATCH for update of generic-vnfs/generic-vnf/myid");
- dbser.verifyResourceVersion("update", "generic-vnf", "current-res-ver", "old-res-ver", "generic-vnfs/generic-vnf/myid");
+ thrown.expect(AAIException.class);
+ thrown.expectMessage("resource-version MISMATCH for update of generic-vnfs/generic-vnf/myid");
+ dbser.verifyResourceVersion("update", "generic-vnf", "current-res-ver", "old-res-ver",
+ "generic-vnfs/generic-vnf/myid");
- }
+ }
- @Test
- public void verifyResourceVersion_DeleteTest() throws AAIException {
- engine.startTransaction();
+ @Test
+ public void verifyResourceVersion_DeleteTest() throws AAIException {
+ engine.startTransaction();
- assertTrue (dbser.verifyResourceVersion("delete", "generic-vnf", "current-res-ver", AAIConstants.AAI_RESVERSION_DISABLED_UUID_DEFAULT,
- "generic-vnfs/generic-vnf/myid"));
+ assertTrue(dbser.verifyResourceVersion("delete", "generic-vnf", "current-res-ver",
+ AAIConstants.AAI_RESVERSION_DISABLED_UUID_DEFAULT, "generic-vnfs/generic-vnf/myid"));
- }
- @Test
- public void trimClassNameTest() throws AAIException {
- assertEquals("GenericVnf", dbser.trimClassName("GenericVnf"));
- assertEquals("GenericVnf", dbser.trimClassName("org.onap.aai.GenericVnf"));
- }
+ }
- @Test
- public void getURIForVertexTest() throws AAIException, URISyntaxException, UnsupportedEncodingException {
- engine.startTransaction();
+ @Test
+ public void trimClassNameTest() throws AAIException {
+ assertEquals("GenericVnf", dbser.trimClassName("GenericVnf"));
+ assertEquals("GenericVnf", dbser.trimClassName("org.onap.aai.GenericVnf"));
+ }
- Vertex cr = engine.tx().addVertex("aai-node-type", "cloud-region", "cloud-owner", "me", "cloud-region-id", "123", "aai-uri", "/cloud-infrastructure/cloud-regions/cloud-region/me/123");
- Vertex ten = engine.tx().addVertex("aai-node-type", "tenant", "tenant-id", "453");
+ @Test
+ public void getURIForVertexTest() throws AAIException, URISyntaxException, UnsupportedEncodingException {
+ engine.startTransaction();
- edgeSer.addTreeEdge(engine.tx().traversal(), cr, ten);
+ Vertex cr = engine.tx().addVertex("aai-node-type", "cloud-region", "cloud-owner", "me", "cloud-region-id",
+ "123", "aai-uri", "/cloud-infrastructure/cloud-regions/cloud-region/me/123");
+ Vertex ten = engine.tx().addVertex("aai-node-type", "tenant", "tenant-id", "453");
- ten.property("aai-uri", "/cloud-infrastructure/cloud-regions/cloud-region/me/123/tenants/tenant/453");
+ edgeSer.addTreeEdge(engine.tx().traversal(), cr, ten);
- URI compare = new URI("/cloud-infrastructure/cloud-regions/cloud-region/me/123/tenants/tenant/453");
- assertEquals(compare, dbser.getURIForVertex(ten));
+ ten.property("aai-uri", "/cloud-infrastructure/cloud-regions/cloud-region/me/123/tenants/tenant/453");
- URI compareFailure = new URI("/unknown-uri");
- ten.property("aai-uri").remove();
- assertEquals(compareFailure, dbser.getURIForVertex(ten));
+ URI compare = new URI("/cloud-infrastructure/cloud-regions/cloud-region/me/123/tenants/tenant/453");
+ assertEquals(compare, dbser.getURIForVertex(ten));
- }
+ URI compareFailure = new URI("/unknown-uri");
+ ten.property("aai-uri").remove();
+ assertEquals(compareFailure, dbser.getURIForVertex(ten));
- @Test
- public void getVertexPropertiesTest() throws AAIException, UnsupportedEncodingException {
- engine.startTransaction();
+ }
- Vertex cr = engine.tx().addVertex("aai-node-type", "cloud-region", "cloud-owner", "me", "cloud-region-id", "123");
+ @Test
+ public void getVertexPropertiesTest() throws AAIException, UnsupportedEncodingException {
+ engine.startTransaction();
- Introspector crIntro = dbser.getVertexProperties(cr);
- assertEquals("cloud-region", crIntro.getDbName());
- assertEquals("me", crIntro.getValue("cloud-owner"));
- assertEquals("123", crIntro.getValue("cloud-region-id"));
+ Vertex cr =
+ engine.tx().addVertex("aai-node-type", "cloud-region", "cloud-owner", "me", "cloud-region-id", "123");
- }
+ Introspector crIntro = dbser.getVertexProperties(cr);
+ assertEquals("cloud-region", crIntro.getDbName());
+ assertEquals("me", crIntro.getValue("cloud-owner"));
+ assertEquals("123", crIntro.getValue("cloud-region-id"));
- @Test
- public void getEdgeBetweenTest() throws AAIException {
- engine.startTransaction();
+ }
- Vertex cr = engine.tx().addVertex("aai-node-type", "cloud-region", "cloud-owner", "me", "cloud-region-id", "123");
- Vertex ten = engine.tx().addVertex("aai-node-type", "tenant", "tenant-id", "453");
+ @Test
+ public void getEdgeBetweenTest() throws AAIException {
+ engine.startTransaction();
- edgeSer.addTreeEdge(engine.tx().traversal(), cr, ten);
+ Vertex cr =
+ engine.tx().addVertex("aai-node-type", "cloud-region", "cloud-owner", "me", "cloud-region-id", "123");
+ Vertex ten = engine.tx().addVertex("aai-node-type", "tenant", "tenant-id", "453");
- Edge e = dbser.getEdgeBetween(EdgeType.TREE, ten, cr, null);
- assertEquals("org.onap.relationships.inventory.BelongsTo", e.label());
+ edgeSer.addTreeEdge(engine.tx().traversal(), cr, ten);
- }
+ Edge e = dbser.getEdgeBetween(EdgeType.TREE, ten, cr, null);
+ assertEquals("org.onap.relationships.inventory.BelongsTo", e.label());
- @Test
- public void deleteEdgeTest() throws AAIException, UnsupportedEncodingException {
- engine.startTransaction();
+ }
- Vertex gvnf = engine.tx().addVertex("aai-node-type","generic-vnf","vnf-id","myvnf", "aai-uri", "/network/generic-vnfs/generic-vnf/myvnf");
- Vertex vnfc = engine.tx().addVertex("aai-node-type","vnfc","vnfc-name","a-name", "aai-uri", "/network/vnfcs/vnfc/a-name");
+ @Test
+ public void deleteEdgeTest() throws AAIException, UnsupportedEncodingException {
+ engine.startTransaction();
- edgeSer.addEdge(engine.tx().traversal(), gvnf, vnfc);
+ Vertex gvnf = engine.tx().addVertex("aai-node-type", "generic-vnf", "vnf-id", "myvnf", "aai-uri",
+ "/network/generic-vnfs/generic-vnf/myvnf");
+ Vertex vnfc = engine.tx().addVertex("aai-node-type", "vnfc", "vnfc-name", "a-name", "aai-uri",
+ "/network/vnfcs/vnfc/a-name");
- Introspector relData = loader.introspectorFromName("relationship-data");
- relData.setValue("relationship-key", "vnfc.vnfc-name");
- relData.setValue("relationship-value", "a-name");
- Introspector relationship = loader.introspectorFromName("relationship");
- relationship.setValue("related-to", "vnfc");
- relationship.setValue("related-link", "/network/vnfcs/vnfc/a-name");
- relationship.setValue("relationship-data",relData);
+ edgeSer.addEdge(engine.tx().traversal(), gvnf, vnfc);
- assertTrue(dbser.deleteEdge(relationship, gvnf));
+ Introspector relData = loader.introspectorFromName("relationship-data");
+ relData.setValue("relationship-key", "vnfc.vnfc-name");
+ relData.setValue("relationship-value", "a-name");
+ Introspector relationship = loader.introspectorFromName("relationship");
+ relationship.setValue("related-to", "vnfc");
+ relationship.setValue("related-link", "/network/vnfcs/vnfc/a-name");
+ relationship.setValue("relationship-data", relData);
- assertFalse(engine.tx().traversal().V(gvnf).both("uses").hasNext());
- assertFalse(engine.tx().traversal().V(vnfc).both("uses").hasNext());
+ assertTrue(dbser.deleteEdge(relationship, gvnf));
- }
+ assertFalse(engine.tx().traversal().V(gvnf).both("uses").hasNext());
+ assertFalse(engine.tx().traversal().V(vnfc).both("uses").hasNext());
- @Test
- public void createEdgeTest() throws AAIException, UnsupportedEncodingException {
- engine.startTransaction();
+ }
- Vertex gvnf = engine.tx().addVertex("aai-node-type","generic-vnf","vnf-id","myvnf", "aai-uri", "/network/generic-vnfs/generic-vnf/myvnf");
- Vertex vnfc = engine.tx().addVertex("aai-node-type","vnfc","vnfc-name","a-name", "aai-uri", "/network/vnfcs/vnfc/a-name");
+ @Test
+ public void createEdgeTest() throws AAIException, UnsupportedEncodingException {
+ engine.startTransaction();
- //sunny day case
- Introspector relData = loader.introspectorFromName("relationship-data");
- relData.setValue("relationship-key", "vnfc.vnfc-name");
- relData.setValue("relationship-value", "a-name");
- Introspector relationship = loader.introspectorFromName("relationship");
- relationship.setValue("related-to", "vnfc");
- relationship.setValue("related-link", "/network/vnfcs/vnfc/a-name");
- relationship.setValue("relationship-data",relData);
+ Vertex gvnf = engine.tx().addVertex("aai-node-type", "generic-vnf", "vnf-id", "myvnf", "aai-uri",
+ "/network/generic-vnfs/generic-vnf/myvnf");
+ Vertex vnfc = engine.tx().addVertex("aai-node-type", "vnfc", "vnfc-name", "a-name", "aai-uri",
+ "/network/vnfcs/vnfc/a-name");
- assertTrue(dbser.createEdge(relationship, gvnf));
- assertTrue(engine.tx().traversal().V(gvnf).both("org.onap.relationships.inventory.BelongsTo").hasNext());
- assertTrue(engine.tx().traversal().V(vnfc).both("org.onap.relationships.inventory.BelongsTo").hasNext());
+ // sunny day case
+ Introspector relData = loader.introspectorFromName("relationship-data");
+ relData.setValue("relationship-key", "vnfc.vnfc-name");
+ relData.setValue("relationship-value", "a-name");
+ Introspector relationship = loader.introspectorFromName("relationship");
+ relationship.setValue("related-to", "vnfc");
+ relationship.setValue("related-link", "/network/vnfcs/vnfc/a-name");
+ relationship.setValue("relationship-data", relData);
- }
+ assertTrue(dbser.createEdge(relationship, gvnf));
+ assertTrue(engine.tx().traversal().V(gvnf).both("org.onap.relationships.inventory.BelongsTo").hasNext());
+ assertTrue(engine.tx().traversal().V(vnfc).both("org.onap.relationships.inventory.BelongsTo").hasNext());
- @Test
- public void createCousinEdgeThatShouldBeTreeTest() throws AAIException, UnsupportedEncodingException, URISyntaxException {
- engine.startTransaction();
+ }
- Vertex gvnf = engine.tx().addVertex("aai-node-type","generic-vnf","vnf-id","myvnf", "aai-uri", "/network/generic-vnfs/generic-vnf/myvnf");
- Vertex vf = engine.tx().addVertex("aai-node-type","vf-module","vf-module-id","vf-id", "aai-uri", "/network/generic-vnfs/generic-vnf/myvnf/vf-modules/vf-module/vf-id");
+ @Test
+ public void createCousinEdgeThatShouldBeTreeTest()
+ throws AAIException, UnsupportedEncodingException, URISyntaxException {
+ engine.startTransaction();
+
+ Vertex gvnf = engine.tx().addVertex("aai-node-type", "generic-vnf", "vnf-id", "myvnf", "aai-uri",
+ "/network/generic-vnfs/generic-vnf/myvnf");
+ Vertex vf = engine.tx().addVertex("aai-node-type", "vf-module", "vf-module-id", "vf-id", "aai-uri",
+ "/network/generic-vnfs/generic-vnf/myvnf/vf-modules/vf-module/vf-id");
+
+ edgeSer.addTreeEdge(engine.tx().traversal(), gvnf, vf);
+
+ Introspector relationship = loader.introspectorFromName("relationship");
+ relationship.setValue("related-to", "vf-module");
+ relationship.setValue("related-link", dbser.getURIForVertex(vf).toString());
+ Introspector relationshipList = loader.introspectorFromName("relationship-list");
+ relationshipList.setValue("relationship", Collections.singletonList(relationship.getUnderlyingObject()));
+
+ Introspector gvnfObj = loader.introspectorFromName("generic-vnf");
+ Vertex gvnf2 = dbser.createNewVertex(gvnfObj);
+ gvnfObj.setValue("relationship-list", relationshipList.getUnderlyingObject());
+ gvnfObj.setValue("vnf-id", "myvnf-1");
+
+ QueryParser uriQuery =
+ dbEngine.getQueryBuilder().createQueryFromURI(new URI("/network/generic-vnfs/generic-vnf/myvnf-1"));
+
+ try {
+ dbser.serializeToDb(gvnfObj, gvnf2, uriQuery, null, "test");
+ } catch (AAIException e) {
+ assertEquals("AAI_6145", e.getCode());
+ }
+ }
+
+ @Test
+ public void createEdgeNodeDoesNotExistExceptionTest() throws AAIException, UnsupportedEncodingException {
+ engine.startTransaction();
+
+ Vertex gvnf = engine.tx().addVertex("aai-node-type", "generic-vnf", "vnf-id", "myvnf", "aai-uri",
+ "/network/generic-vnfs/generic-vnf/myvnf");
+
+ // rainy day case, edge to non-existent object
+ Introspector relData = loader.introspectorFromName("relationship-data");
+ relData.setValue("relationship-key", "vnfc.vnfc-name");
+ relData.setValue("relationship-value", "b-name");
+ Introspector relationship = loader.introspectorFromName("relationship");
+ relationship.setValue("related-to", "vnfc");
+ relationship.setValue("related-link", "/network/vnfcs/vnfc/b-name");
+ relationship.setValue("relationship-data", relData);
+
+ thrown.expect(AAIException.class);
+ thrown.expectMessage("Node of type vnfc. Could not find object at: /network/vnfcs/vnfc/b-name");
+ dbser.createEdge(relationship, gvnf);
+
+ }
- edgeSer.addTreeEdge(engine.tx().traversal(), gvnf, vf);
+ @Test
+ public void serializeSingleVertexTopLevelTest() throws AAIException, UnsupportedEncodingException {
+ engine.startTransaction();
+
+ Introspector gvnf = loader.introspectorFromName("generic-vnf");
+ Vertex gvnfVert = dbser.createNewVertex(gvnf);
+
+ gvnf.setValue("vnf-id", "myvnf");
+ dbser.serializeSingleVertex(gvnfVert, gvnf, "test");
+ assertTrue(engine.tx().traversal().V().has("aai-node-type", "generic-vnf").has("vnf-id", "myvnf").hasNext());
+
+ }
+
+ @Test
+ public void serializeSingleVertexChildTest() throws AAIException, UnsupportedEncodingException {
+ engine.startTransaction();
- Introspector relationship = loader.introspectorFromName("relationship");
- relationship.setValue("related-to", "vf-module");
- relationship.setValue("related-link", dbser.getURIForVertex(vf).toString());
- Introspector relationshipList = loader.introspectorFromName("relationship-list");
- relationshipList.setValue("relationship", Collections.singletonList(relationship.getUnderlyingObject()));
+ Vertex cr = engine.tx().addVertex("aai-node-type", "cloud-region", "cloud-owner", "me", "cloud-region-id",
+ "123", "aai-uri", "/cloud-infrastructure/cloud-regions/cloud-region/me/123");
+ Introspector tenIn = loader.introspectorFromName("tenant");
+ Vertex ten = dbser.createNewVertex(tenIn);
+ ten.property("aai-uri", cr.property("aai-uri").value().toString() + "/tenants/tenant/453");
- Introspector gvnfObj = loader.introspectorFromName("generic-vnf");
- Vertex gvnf2 = dbser.createNewVertex(gvnfObj);
- gvnfObj.setValue("relationship-list", relationshipList.getUnderlyingObject());
- gvnfObj.setValue("vnf-id", "myvnf-1");
+ edgeSer.addTreeEdge(engine.tx().traversal(), cr, ten);
- QueryParser uriQuery = dbEngine.getQueryBuilder().createQueryFromURI(new URI("/network/generic-vnfs/generic-vnf/myvnf-1"));
+ tenIn.setValue("tenant-id", "453");
+ tenIn.setValue("tenant-name", "mytenant");
- try {
- dbser.serializeToDb(gvnfObj, gvnf2, uriQuery, null, "test");
- } catch (AAIException e) {
- assertEquals("AAI_6145", e.getCode());
- }
- }
+ dbser.serializeSingleVertex(ten, tenIn, "test");
- @Test
- public void createEdgeNodeDoesNotExistExceptionTest() throws AAIException, UnsupportedEncodingException {
- engine.startTransaction();
+ assertTrue(engine.tx().traversal().V().has("aai-node-type", "tenant").has("tenant-id", "453")
+ .has("tenant-name", "mytenant").hasNext());
- Vertex gvnf = engine.tx().addVertex("aai-node-type","generic-vnf","vnf-id","myvnf", "aai-uri", "/network/generic-vnfs/generic-vnf/myvnf");
+ }
- //rainy day case, edge to non-existent object
- Introspector relData = loader.introspectorFromName("relationship-data");
- relData.setValue("relationship-key", "vnfc.vnfc-name");
- relData.setValue("relationship-value", "b-name");
- Introspector relationship = loader.introspectorFromName("relationship");
- relationship.setValue("related-to", "vnfc");
- relationship.setValue("related-link", "/network/vnfcs/vnfc/b-name");
- relationship.setValue("relationship-data",relData);
+ @Test
+ public void getVertexPropertiesRelationshipHasLabelTest() throws AAIException, UnsupportedEncodingException {
+ engine.startTransaction();
- thrown.expect(AAIException.class);
- thrown.expectMessage("Node of type vnfc. Could not find object at: /network/vnfcs/vnfc/b-name");
- dbser.createEdge(relationship, gvnf);
+ Vertex gvnf = engine.tx().addVertex("aai-node-type", "generic-vnf", "vnf-id", "vnf-123", "aai-uri",
+ "/network/generic-vnfs/generic-vnf/vnf-123");
+ Vertex vnfc = engine.tx().addVertex("aai-node-type", "vnfc", "vnfc-name", "vnfc-123", "aai-uri",
+ "/network/vnfcs/vnfc/vnfc-123");
- }
+ edgeSer.addEdge(engine.tx().traversal(), gvnf, vnfc);
- @Test
- public void serializeSingleVertexTopLevelTest() throws AAIException, UnsupportedEncodingException {
- engine.startTransaction();
+ Introspector obj = loader.introspectorFromName("generic-vnf");
+ obj = this.dbser.dbToObject(Arrays.asList(gvnf), obj, AAIProperties.MAXIMUM_DEPTH, false, "false");
- Introspector gvnf = loader.introspectorFromName("generic-vnf");
- Vertex gvnfVert = dbser.createNewVertex(gvnf);
+ MarshallerProperties properties =
+ new MarshallerProperties.Builder(org.onap.aai.restcore.MediaType.getEnum("application/json"))
+ .formatted(true).build();
+ System.out.println(obj.marshal(properties));
- gvnf.setValue("vnf-id", "myvnf");
- dbser.serializeSingleVertex(gvnfVert, gvnf, "test");
- assertTrue(engine.tx().traversal().V().has("aai-node-type","generic-vnf").has("vnf-id","myvnf").hasNext());
+ assertEquals("edge label between generic-vnf and vnfs is uses", "org.onap.relationships.inventory.BelongsTo",
+ obj.getWrappedValue("relationship-list").getWrappedListValue("relationship").get(0)
+ .getValue("relationship-label"));
- }
+ }
- @Test
- public void serializeSingleVertexChildTest() throws AAIException, UnsupportedEncodingException {
- engine.startTransaction();
+ @Test
+ public void getVertexPropertiesRelationshipOldVersionNoEdgeLabelTest()
+ throws AAIException, UnsupportedEncodingException {
- Vertex cr = engine.tx().addVertex("aai-node-type", "cloud-region", "cloud-owner", "me", "cloud-region-id", "123", "aai-uri", "/cloud-infrastructure/cloud-regions/cloud-region/me/123");
- Introspector tenIn = loader.introspectorFromName("tenant");
- Vertex ten = dbser.createNewVertex(tenIn);
- ten.property("aai-uri", cr.property("aai-uri").value().toString() + "/tenants/tenant/453");
+ SchemaVersion version = schemaVersions.getAppRootVersion();
+ DBSerializer dbser = new DBSerializer(version, engine, introspectorFactoryType, "AAI-TEST");
+ Loader loader = loaderFactory.createLoaderForVersion(introspectorFactoryType, version);
- edgeSer.addTreeEdge(engine.tx().traversal(), cr, ten);
+ engine.startTransaction();
- tenIn.setValue("tenant-id", "453");
- tenIn.setValue("tenant-name", "mytenant");
+ Vertex gvnf = engine.tx().addVertex("aai-node-type", "generic-vnf", "vnf-id", "vnf-123", "aai-uri",
+ "/network/generic-vnfs/generic-vnf/vnf-123");
+ Vertex vnfc = engine.tx().addVertex("aai-node-type", "vnfc", "vnfc-name", "vnfc-123", "aai-uri",
+ "/network/vnfcs/vnfc/vnfc-123");
- dbser.serializeSingleVertex(ten, tenIn, "test");
+ edgeSer.addEdge(engine.tx().traversal(), gvnf, vnfc);
- assertTrue(engine.tx().traversal().V().has("aai-node-type","tenant").has("tenant-id","453").has("tenant-name","mytenant").hasNext());
+ Introspector obj = loader.introspectorFromName("generic-vnf");
+ obj = dbser.dbToObject(Arrays.asList(gvnf), obj, AAIProperties.MAXIMUM_DEPTH, false, "false");
- }
+ assertEquals("Relationship does not contain edge-property", false, obj.getWrappedValue("relationship-list")
+ .getWrappedListValue("relationship").get(0).hasProperty("relationship-label"));
+ }
- @Test
- public void getVertexPropertiesRelationshipHasLabelTest() throws AAIException, UnsupportedEncodingException {
- engine.startTransaction();
+ @Test
+ public void createEdgeWithInvalidLabelTest() throws AAIException, UnsupportedEncodingException,
+ NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
- Vertex gvnf = engine.tx().addVertex("aai-node-type","generic-vnf","vnf-id","vnf-123","aai-uri", "/network/generic-vnfs/generic-vnf/vnf-123");
- Vertex vnfc = engine.tx().addVertex("aai-node-type","vnfc","vnfc-name","vnfc-123","aai-uri", "/network/vnfcs/vnfc/vnfc-123");
+ engine.startTransaction();
- edgeSer.addEdge(engine.tx().traversal(), gvnf, vnfc);
+ Vertex gvnf = engine.tx().addVertex("aai-node-type", "generic-vnf", "vnf-id", "myvnf", "aai-uri",
+ "/network/generic-vnfs/generic-vnf/myvnf");
+ engine.tx().addVertex("aai-node-type", "vnfc", "vnfc-name", "a-name", "aai-uri", "/network/vnfcs/vnfc/a-name");
- Introspector obj = loader.introspectorFromName("generic-vnf");
- obj = this.dbser.dbToObject(Arrays.asList(gvnf), obj, AAIProperties.MAXIMUM_DEPTH, false, "false");
+ Introspector relData = loader.introspectorFromName("relationship-data");
+ relData.setValue("relationship-key", "vnfc.vnfc-name");
+ relData.setValue("relationship-value", "a-name");
+ Introspector relationship = loader.introspectorFromName("relationship");
+ relationship.setValue("related-to", "vnfc");
+ relationship.setValue("related-link", "/network/vnfcs/vnfc/a-name");
+ relationship.setValue("relationship-data", relData);
+ relationship.setValue("relationship-label", "NA");
+ thrown.expect(AAIException.class);
+ thrown.expectMessage("No rule found");
+ thrown.expectMessage("node type: generic-vnf, node type: vnfc, label: NA, type: COUSIN");
+ dbser.createEdge(relationship, gvnf);
- MarshallerProperties properties = new MarshallerProperties
- .Builder(org.onap.aai.restcore.MediaType.getEnum("application/json")).formatted(true).build();
- System.out.println(obj.marshal(properties));
+ }
- assertEquals("edge label between generic-vnf and vnfs is uses",
- "org.onap.relationships.inventory.BelongsTo",
- obj.getWrappedValue("relationship-list")
- .getWrappedListValue("relationship")
- .get(0)
- .getValue("relationship-label")
- );
+ @Test
+ public void addRelatedToPropertyTest() throws AAIException {
+ engine.startTransaction();
+
+ Vertex gvnf = engine.tx().addVertex("aai-node-type", "generic-vnf", "vnf-id", "myname", "vnf-name", "myname",
+ "aai-uri", "/network/generic-vnfs/generic-vnf/myname");
+ engine.tx().addVertex("aai-node-type", "vnfc", "vnfc-name", "a-name", "aai-uri", "/network/vnfcs/vnfc/a-name");
+ Loader loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getAppRootVersion());
+ Introspector gv = loader.introspectorFromName("generic-vnf");
+ gv.setValue("vnf-name", "myname");
+
+ Introspector rel = loader.introspectorFromName("relationship");
+ DBSerializer dbser = new DBSerializer(schemaVersions.getAppRootVersion(), dbEngine, ModelType.MOXY, "AAI-TEST");
+ dbser.addRelatedToProperty(rel, gvnf, "generic-vnf");
+ List<Introspector> relToProps = rel.getWrappedListValue("related-to-property");
+ assertThat(relToProps.size(), is(1));
+ Introspector relToProp = relToProps.get(0);
+ assertThat(relToProp.getValue("property-key"), is("generic-vnf.vnf-name"));
+ assertThat(relToProp.getValue("property-value"), is("myname"));
+ }
+ @Test
+ public void dbToObjectContainerMismatchTest() throws AAIException, UnsupportedEncodingException {
+ DBSerializer dbser = new DBSerializer(schemaVersions.getAppRootVersion(), dbEngine, ModelType.MOXY, "AAI-TEST");
+ Graph vertexMaker = TinkerGraph.open();
+ Vertex a = vertexMaker.addVertex(T.id, "0");
+ Vertex b = vertexMaker.addVertex(T.id, "1");
+ List<Vertex> vertices = Arrays.asList(a, b);
- }
+ Loader loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getAppRootVersion());
+ Introspector intro = loader.introspectorFromName("image"); // just need any non-container object
- @Test
- public void getVertexPropertiesRelationshipOldVersionNoEdgeLabelTest() throws AAIException, UnsupportedEncodingException {
+ thrown.expect(AAIException.class);
+ thrown.expectMessage("query object mismatch: this object cannot hold multiple items.");
- SchemaVersion version = schemaVersions.getAppRootVersion();
- DBSerializer dbser = new DBSerializer(version, engine, introspectorFactoryType, "AAI-TEST");
- Loader loader = loaderFactory.createLoaderForVersion(introspectorFactoryType, version);
+ dbser.dbToObject(vertices, intro, Integer.MAX_VALUE, true, "doesn't matter");
+ }
- engine.startTransaction();
+ @Test
+ public void dbToObjectTest() throws AAIException, UnsupportedEncodingException {
+ engine.startTransaction();
- Vertex gvnf = engine.tx().addVertex("aai-node-type","generic-vnf","vnf-id","vnf-123", "aai-uri", "/network/generic-vnfs/generic-vnf/vnf-123");
- Vertex vnfc = engine.tx().addVertex("aai-node-type","vnfc","vnfc-name","vnfc-123", "aai-uri", "/network/vnfcs/vnfc/vnfc-123");
+ DBSerializer dbser = new DBSerializer(version, engine, ModelType.MOXY, "AAI-TEST");
+ Vertex gv1 = engine.tx().addVertex("aai-node-type", "generic-vnf", "vnf-id", "id1");
+ Vertex gv2 = engine.tx().addVertex("aai-node-type", "generic-vnf", "vnf-id", "id2");
+ List<Vertex> vertices = Arrays.asList(gv1, gv2);
- edgeSer.addEdge(engine.tx().traversal(), gvnf, vnfc);
+ Loader loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, version);
+ Introspector gvContainer = loader.introspectorFromName("generic-vnfs");
- Introspector obj = loader.introspectorFromName("generic-vnf");
- obj = dbser.dbToObject(Arrays.asList(gvnf), obj, AAIProperties.MAXIMUM_DEPTH, false, "false");
+ Introspector res = dbser.dbToObject(vertices, gvContainer, 0, true, "true");
+ List<Introspector> gvs = res.getWrappedListValue("generic-vnf");
+ assertTrue(gvs.size() == 2);
+ for (Introspector i : gvs) {
+ String vnfId = i.getValue("vnf-id");
+ assertTrue("id1".equals(vnfId) || "id2".equals(vnfId));
+ }
- assertEquals("Relationship does not contain edge-property", false, obj.getWrappedValue("relationship-list").getWrappedListValue("relationship").get(0).hasProperty("relationship-label"));
+ }
+ @Test
+ public void getEdgeBetweenNoLabelTest() throws AAIException {
+ DBSerializer dbser = new DBSerializer(version, engine, ModelType.MOXY, "AAI-TEST");
+ engine.startTransaction();
+ Vertex gv = engine.tx().addVertex("aai-node-type", "generic-vnf", "vnf-id", "id1");
+ Vertex lint = engine.tx().addVertex("aai-node-type", "l-interface", "interface-name", "name1");
+ edgeSer.addTreeEdge(engine.tx().traversal(), gv, lint);
- }
+ Edge res = dbser.getEdgeBetween(EdgeType.TREE, gv, lint);
+ assertEquals("org.onap.relationships.inventory.BelongsTo", res.label());
- @Test
- public void createEdgeWithInvalidLabelTest() throws AAIException, UnsupportedEncodingException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
+ }
- engine.startTransaction();
+ @Test
+ public void deleteItemsWithTraversal() throws AAIException {
+ DBSerializer dbser = new DBSerializer(version, engine, ModelType.MOXY, "AAI-TEST");
+ engine.startTransaction();
+ Vertex gv = engine.tx().addVertex("aai-node-type", "generic-vnf", "vnf-id", "id1");
+ Vertex lint = engine.tx().addVertex("aai-node-type", "l-interface", "interface-name", "name1");
- Vertex gvnf = engine.tx().addVertex("aai-node-type","generic-vnf","vnf-id","myvnf", "aai-uri", "/network/generic-vnfs/generic-vnf/myvnf");
- engine.tx().addVertex("aai-node-type","vnfc","vnfc-name","a-name", "aai-uri", "/network/vnfcs/vnfc/a-name");
+ assertTrue(engine.tx().traversal().V().has("vnf-id", "id1").hasNext());
+ assertTrue(engine.tx().traversal().V().has("interface-name", "name1").hasNext());
- Introspector relData = loader.introspectorFromName("relationship-data");
- relData.setValue("relationship-key", "vnfc.vnfc-name");
- relData.setValue("relationship-value", "a-name");
- Introspector relationship = loader.introspectorFromName("relationship");
- relationship.setValue("related-to", "vnfc");
- relationship.setValue("related-link", "/network/vnfcs/vnfc/a-name");
- relationship.setValue("relationship-data",relData);
- relationship.setValue("relationship-label", "NA");
+ dbser.deleteItemsWithTraversal(Arrays.asList(gv, lint));
- thrown.expect(AAIException.class);
- thrown.expectMessage("No rule found");
- thrown.expectMessage("node type: generic-vnf, node type: vnfc, label: NA, type: COUSIN");
- dbser.createEdge(relationship, gvnf);
+ assertTrue(!engine.tx().traversal().V().has("vnf-id", "id1").hasNext());
+ assertTrue(!engine.tx().traversal().V().has("interface-name", "name1").hasNext());
- }
+ }
- @Test
- public void addRelatedToPropertyTest() throws AAIException {
- engine.startTransaction();
+ @Test
+ public void serializeToDbWithParentTest() throws AAIException, UnsupportedEncodingException, URISyntaxException {
+ DBSerializer dbser = new DBSerializer(version, engine, ModelType.MOXY, "AAI-TEST");
+ engine.startTransaction();
+ Vertex gv = engine.tx().addVertex("aai-node-type", "generic-vnf", "vnf-id", "id1", "aai-uri",
+ "/network/generic-vnfs/generic-vnf/id1");
+ Vertex lint = engine.tx().addVertex("aai-node-type", "l-interface");
+ edgeSer.addTreeEdge(engine.tx().traversal(), gv, lint);
- Vertex gvnf = engine.tx().addVertex("aai-node-type","generic-vnf",
- "vnf-id","myname",
- "vnf-name","myname",
- "aai-uri", "/network/generic-vnfs/generic-vnf/myname"
- );
- engine.tx().addVertex("aai-node-type","vnfc","vnfc-name","a-name", "aai-uri", "/network/vnfcs/vnfc/a-name");
- Loader loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getAppRootVersion());
- Introspector gv = loader.introspectorFromName("generic-vnf");
- gv.setValue("vnf-name", "myname");
+ Introspector lintIntro = loader.introspectorFromName("l-interface");
+ lintIntro.setValue("interface-name", "name1");
+ lintIntro.setValue("interface-role", "actor");
+ URI lintURI = new URI("/network/generic-vnfs/generic-vnf/id1/l-interfaces/l-interface/name1");
+ QueryParser uriQuery = engine.getQueryBuilder(gv).createQueryFromURI(lintURI);
+ dbser.serializeToDb(lintIntro, lint, uriQuery, "test-identifier", "AAI-TEST");
- Introspector rel = loader.introspectorFromName("relationship");
- DBSerializer dbser = new DBSerializer(schemaVersions.getAppRootVersion(), dbEngine,
- ModelType.MOXY, "AAI-TEST");
- dbser.addRelatedToProperty(rel, gvnf, "generic-vnf");
- List<Introspector> relToProps = rel.getWrappedListValue("related-to-property");
- assertThat(relToProps.size(), is(1));
- Introspector relToProp = relToProps.get(0);
- assertThat(relToProp.getValue("property-key"), is("generic-vnf.vnf-name"));
- assertThat(relToProp.getValue("property-value"), is("myname"));
- }
+ assertTrue(engine.tx().traversal().V(lint).has("interface-role", "actor").hasNext());
- @Test
- public void dbToObjectContainerMismatchTest() throws AAIException, UnsupportedEncodingException {
- DBSerializer dbser = new DBSerializer(schemaVersions.getAppRootVersion(), dbEngine,
- ModelType.MOXY, "AAI-TEST");
- Graph vertexMaker = TinkerGraph.open();
- Vertex a = vertexMaker.addVertex(T.id, "0");
- Vertex b = vertexMaker.addVertex(T.id, "1");
- List<Vertex> vertices = Arrays.asList(a,b);
+ }
- Loader loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getAppRootVersion());
- Introspector intro = loader.introspectorFromName("image"); //just need any non-container object
+ @Test
+ public void getLatestVersionViewTest() throws AAIException, UnsupportedEncodingException {
+ DBSerializer dbser = new DBSerializer(version, engine, ModelType.MOXY, "AAI-TEST");
+ engine.startTransaction();
+ Vertex phys = engine.tx().addVertex("aai-node-type", "physical-link", "link-name", "zaldo", "speed-value",
+ "very-fast", "service-provider-bandwidth-up-units", "things");
+
+ Introspector res = dbser.getLatestVersionView(phys);
+ assertTrue("zaldo".equals(res.getValue("link-name")));
+ assertTrue("very-fast".equals(res.getValue("speed-value")));
+ assertTrue("things".equals(res.getValue("service-provider-bandwidth-up-units")));
+ }
- thrown.expect(AAIException.class);
- thrown.expectMessage("query object mismatch: this object cannot hold multiple items.");
-
- dbser.dbToObject(vertices, intro, Integer.MAX_VALUE, true, "doesn't matter");
- }
-
- @Test
- public void dbToObjectTest() throws AAIException, UnsupportedEncodingException {
- engine.startTransaction();
-
- DBSerializer dbser = new DBSerializer(version, engine,
- ModelType.MOXY, "AAI-TEST");
- Vertex gv1 = engine.tx().addVertex("aai-node-type", "generic-vnf", "vnf-id", "id1");
- Vertex gv2 = engine.tx().addVertex("aai-node-type", "generic-vnf", "vnf-id", "id2");
- List<Vertex> vertices = Arrays.asList(gv1, gv2);
-
- Loader loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, version);
- Introspector gvContainer = loader.introspectorFromName("generic-vnfs");
-
- Introspector res = dbser.dbToObject(vertices, gvContainer, 0, true, "true");
- List<Introspector> gvs = res.getWrappedListValue("generic-vnf");
- assertTrue(gvs.size() == 2);
- for (Introspector i : gvs) {
- String vnfId = i.getValue("vnf-id");
- assertTrue("id1".equals(vnfId) || "id2".equals(vnfId));
- }
-
-
- }
-
- @Test
- public void getEdgeBetweenNoLabelTest() throws AAIException {
- DBSerializer dbser = new DBSerializer(version, engine,
- ModelType.MOXY, "AAI-TEST");
- engine.startTransaction();
- Vertex gv = engine.tx().addVertex("aai-node-type", "generic-vnf", "vnf-id", "id1");
- Vertex lint = engine.tx().addVertex("aai-node-type", "l-interface", "interface-name", "name1");
- edgeSer.addTreeEdge(engine.tx().traversal(), gv, lint);
-
- Edge res = dbser.getEdgeBetween(EdgeType.TREE, gv, lint);
- assertEquals("org.onap.relationships.inventory.BelongsTo", res.label());
-
- }
-
- @Test
- public void deleteItemsWithTraversal() throws AAIException {
- DBSerializer dbser = new DBSerializer(version, engine,
- ModelType.MOXY, "AAI-TEST");
- engine.startTransaction();
- Vertex gv = engine.tx().addVertex("aai-node-type", "generic-vnf", "vnf-id", "id1");
- Vertex lint = engine.tx().addVertex("aai-node-type", "l-interface", "interface-name", "name1");
-
- assertTrue(engine.tx().traversal().V().has("vnf-id", "id1").hasNext());
- assertTrue(engine.tx().traversal().V().has("interface-name", "name1").hasNext());
-
- dbser.deleteItemsWithTraversal(Arrays.asList(gv, lint));
-
- assertTrue(!engine.tx().traversal().V().has("vnf-id", "id1").hasNext());
- assertTrue(!engine.tx().traversal().V().has("interface-name", "name1").hasNext());
-
-
- }
-
- @Test
- public void serializeToDbWithParentTest() throws AAIException, UnsupportedEncodingException, URISyntaxException {
- DBSerializer dbser = new DBSerializer(version, engine,
- ModelType.MOXY, "AAI-TEST");
- engine.startTransaction();
- Vertex gv = engine.tx().addVertex("aai-node-type", "generic-vnf", "vnf-id", "id1", "aai-uri", "/network/generic-vnfs/generic-vnf/id1");
- Vertex lint = engine.tx().addVertex("aai-node-type", "l-interface");
- edgeSer.addTreeEdge(engine.tx().traversal(), gv, lint);
-
- Introspector lintIntro = loader.introspectorFromName("l-interface");
- lintIntro.setValue("interface-name", "name1");
- lintIntro.setValue("interface-role", "actor");
- URI lintURI = new URI("/network/generic-vnfs/generic-vnf/id1/l-interfaces/l-interface/name1");
- QueryParser uriQuery = engine.getQueryBuilder(gv).createQueryFromURI(lintURI);
- dbser.serializeToDb(lintIntro, lint, uriQuery, "test-identifier", "AAI-TEST");
-
- assertTrue(engine.tx().traversal().V(lint).has("interface-role", "actor").hasNext());
-
-
- }
-
- @Test
- public void getLatestVersionViewTest() throws AAIException, UnsupportedEncodingException {
- DBSerializer dbser = new DBSerializer(version, engine,
- ModelType.MOXY, "AAI-TEST");
- engine.startTransaction();
- Vertex phys = engine.tx().addVertex("aai-node-type", "physical-link", "link-name", "zaldo",
- "speed-value", "very-fast", "service-provider-bandwidth-up-units", "things");
-
- Introspector res = dbser.getLatestVersionView(phys);
- assertTrue("zaldo".equals(res.getValue("link-name")));
- assertTrue("very-fast".equals(res.getValue("speed-value")));
- assertTrue("things".equals(res.getValue("service-provider-bandwidth-up-units")));
- }
+ @Test
+ public void cascadeVserverDeleteTest() throws AAIException {
+ vserverSetup();
+ String expected_message = "";
- @Test
- public void cascadeVserverDeleteTest() throws AAIException {
- vserverSetup();
- String expected_message = "";
+ /*
+ * vserver-->l-interface -->logical-link
+ * -->l3-ipvx-list
+ */
+ Vertex vserver = graph.traversal().V().has("aai-node-type", "vserver").has("vserver-id", "vss1").next();
- /* vserver-->l-interface -->logical-link
- * -->l3-ipvx-list
- */
- Vertex vserver = graph.traversal().V().has("aai-node-type", "vserver").has("vserver-id", "vss1").next();
-
- String exceptionMessage = testCascadeDelete(vserver);
- assertEquals(expected_message, exceptionMessage);
-
- }
-
- @Test
- public void cascadeL3NetworkPreventDeleteTest() throws AAIException {
- l3NetworkSetup();
- ArrayList expected_messages = new ArrayList<String>();
- expected_messages.add("Object is being reference by additional objects preventing it from being deleted. Please clean up references from the following types [l3-interface-ipv4-address-list, l3-interface-ipv6-address-list]");
- expected_messages.add("Object is being reference by additional objects preventing it from being deleted. Please clean up references from the following types [l3-interface-ipv6-address-list, l3-interface-ipv4-address-list]");
-
- /* vserver-->l-interface -->logical-link
- * -->l3-ipvx-list
- */
- Vertex l3network = graph.traversal().V().has("aai-node-type", "l3-network").has("network-id", "network-id-v1").next();
+ String exceptionMessage = testCascadeDelete(vserver);
+ assertEquals(expected_message, exceptionMessage);
- String exceptionMessage = testCascadeDelete(l3network);
- assertTrue(expected_messages.contains(exceptionMessage));
+ }
- }
+ @Test
+ public void cascadeL3NetworkPreventDeleteTest() throws AAIException {
+ l3NetworkSetup();
+ ArrayList expected_messages = new ArrayList<String>();
+ expected_messages.add(
+ "Object is being reference by additional objects preventing it from being deleted. Please clean up references from the following types [l3-interface-ipv4-address-list, l3-interface-ipv6-address-list]");
+ expected_messages.add(
+ "Object is being reference by additional objects preventing it from being deleted. Please clean up references from the following types [l3-interface-ipv6-address-list, l3-interface-ipv4-address-list]");
+
+ /*
+ * vserver-->l-interface -->logical-link
+ * -->l3-ipvx-list
+ */
+ Vertex l3network =
+ graph.traversal().V().has("aai-node-type", "l3-network").has("network-id", "network-id-v1").next();
+
+ String exceptionMessage = testCascadeDelete(l3network);
+ assertTrue(expected_messages.contains(exceptionMessage));
+
+ }
- @Test
- public void cascadeL3NetworkDeleteTest() throws AAIException {
- l3NetworkSetup();
- String expected_message = "";
+ @Test
+ public void cascadeL3NetworkDeleteTest() throws AAIException {
+ l3NetworkSetup();
+ String expected_message = "";
- /* vserver-->l-interface -->logical-link
- * -->l3-ipvx-list
- */
- Vertex l3network = graph.traversal().V().has("aai-node-type", "l3-network").has("network-id", "network-id-v2").next();
+ /*
+ * vserver-->l-interface -->logical-link
+ * -->l3-ipvx-list
+ */
+ Vertex l3network =
+ graph.traversal().V().has("aai-node-type", "l3-network").has("network-id", "network-id-v2").next();
- String exceptionMessage = testCascadeDelete(l3network);
- assertEquals(expected_message, exceptionMessage);
+ String exceptionMessage = testCascadeDelete(l3network);
+ assertEquals(expected_message, exceptionMessage);
- }
+ }
}
diff --git a/aai-core/src/test/java/org/onap/aai/serialization/db/DbSerializer_needsFakeRulesTest.java b/aai-core/src/test/java/org/onap/aai/serialization/db/DbSerializer_needsFakeRulesTest.java
index 1ddef28c..808dd631 100644
--- a/aai-core/src/test/java/org/onap/aai/serialization/db/DbSerializer_needsFakeRulesTest.java
+++ b/aai-core/src/test/java/org/onap/aai/serialization/db/DbSerializer_needsFakeRulesTest.java
@@ -17,18 +17,25 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.serialization.db;
-import org.onap.aai.config.ConfigConfiguration;
-import org.onap.aai.setup.SchemaVersion;
-import org.onap.aai.setup.SchemaVersions;
-import org.onap.aai.util.AAIConstants;
-import org.janusgraph.core.JanusGraphFactory;
+import static org.junit.Assert.*;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.when;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.*;
+
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.structure.*;
+import org.janusgraph.core.JanusGraphFactory;
import org.junit.*;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
+import org.onap.aai.config.ConfigConfiguration;
import org.onap.aai.config.IntrospectionConfig;
import org.onap.aai.config.SpringContextAware;
import org.onap.aai.db.props.AAIProperties;
@@ -38,609 +45,678 @@ import org.onap.aai.exceptions.AAIException;
import org.onap.aai.introspection.*;
import org.onap.aai.nodes.NodeIngestor;
import org.onap.aai.parsers.query.QueryParser;
-import org.onap.aai.serialization.engines.QueryStyle;
import org.onap.aai.serialization.engines.JanusGraphDBEngine;
+import org.onap.aai.serialization.engines.QueryStyle;
import org.onap.aai.serialization.engines.TransactionalGraphEngine;
import org.onap.aai.serialization.queryformats.QueryFormatTestHelper;
import org.onap.aai.setup.SchemaLocationsBean;
+import org.onap.aai.setup.SchemaVersion;
+import org.onap.aai.setup.SchemaVersions;
+import org.onap.aai.util.AAIConstants;
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.SpringJUnit4ClassRunner;
-import java.io.UnsupportedEncodingException;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.util.*;
-
-import static org.junit.Assert.*;
-import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.when;
-
//@RunWith(value = Parameterized.class) TODO replace this functionality
@RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration(classes = {
- ConfigConfiguration.class,
- AAICoreFakeEdgesConfigTranslator.class,
- NodeIngestor.class,
- EdgeIngestor.class,
- EdgeSerializer.class,
- SpringContextAware.class,
- IntrospectionConfig.class
-})
-@TestPropertySource(properties = {
- "schema.translator.list = config",
- "schema.nodes.location=src/test/resources/onap/oxm",
- "schema.edges.location=src/test/resources/onap/dbedgerules"
-})
+@ContextConfiguration(
+ classes = {ConfigConfiguration.class, AAICoreFakeEdgesConfigTranslator.class, NodeIngestor.class,
+ EdgeIngestor.class, EdgeSerializer.class, SpringContextAware.class, IntrospectionConfig.class})
+@TestPropertySource(
+ properties = {"schema.translator.list = config", "schema.nodes.location=src/test/resources/onap/oxm",
+ "schema.edges.location=src/test/resources/onap/dbedgerules"})
public class DbSerializer_needsFakeRulesTest {
- //to use, set thrown.expect to whatever your test needs
- //this line establishes default of expecting no exception to be thrown
- @Rule
- public ExpectedException thrown = ExpectedException.none();
-
- protected static Graph graph;
-
- @Autowired
- protected EdgeSerializer edgeSer;
- @Autowired
- protected EdgeIngestor ei;
- @Autowired
- protected SchemaVersions schemaVersions;
-
- private SchemaVersion version;
- private final ModelType introspectorFactoryType = ModelType.MOXY;
- private final DBConnectionType type = DBConnectionType.REALTIME;
- private Loader loader;
- private TransactionalGraphEngine dbEngine;
- private TransactionalGraphEngine engine; //for tests that aren't mocking the engine
- private DBSerializer dbser;
- TransactionalGraphEngine spy;
- TransactionalGraphEngine.Admin adminSpy;
-
- //@Parameterized.Parameter(value = 0)
- public QueryStyle queryStyle = QueryStyle.TRAVERSAL;
-
- /*@Parameterized.Parameters(name = "QueryStyle.{0}")
- public static Collection<Object[]> data() {
- return Arrays.asList(new Object[][]{
- {QueryStyle.TRAVERSAL},
- {QueryStyle.TRAVERSAL_URI}
- });
- }*/
-
- @BeforeClass
- public static void init() throws Exception {
- graph = JanusGraphFactory.build().set("storage.backend", "inmemory").open();
- System.setProperty("AJSC_HOME", ".");
+ // to use, set thrown.expect to whatever your test needs
+ // this line establishes default of expecting no exception to be thrown
+ @Rule
+ public ExpectedException thrown = ExpectedException.none();
+
+ protected static Graph graph;
+
+ @Autowired
+ protected EdgeSerializer edgeSer;
+ @Autowired
+ protected EdgeIngestor ei;
+ @Autowired
+ protected SchemaVersions schemaVersions;
+
+ private SchemaVersion version;
+ private final ModelType introspectorFactoryType = ModelType.MOXY;
+ private final DBConnectionType type = DBConnectionType.REALTIME;
+ private Loader loader;
+ private TransactionalGraphEngine dbEngine;
+ private TransactionalGraphEngine engine; // for tests that aren't mocking the engine
+ private DBSerializer dbser;
+ TransactionalGraphEngine spy;
+ TransactionalGraphEngine.Admin adminSpy;
+
+ // @Parameterized.Parameter(value = 0)
+ public QueryStyle queryStyle = QueryStyle.TRAVERSAL;
+
+ /*
+ * @Parameterized.Parameters(name = "QueryStyle.{0}")
+ * public static Collection<Object[]> data() {
+ * return Arrays.asList(new Object[][]{
+ * {QueryStyle.TRAVERSAL},
+ * {QueryStyle.TRAVERSAL_URI}
+ * });
+ * }
+ */
+
+ @BeforeClass
+ public static void init() throws Exception {
+ graph = JanusGraphFactory.build().set("storage.backend", "inmemory").open();
+ System.setProperty("AJSC_HOME", ".");
System.setProperty("BUNDLECONFIG_DIR", "src/test/resources/bundleconfig-local");
- QueryFormatTestHelper.setFinalStatic(AAIConstants.class.getField("AAI_HOME_ETC_OXM"), "src/test/resources/bundleconfig-local/etc/oxm/");
+ QueryFormatTestHelper.setFinalStatic(AAIConstants.class.getField("AAI_HOME_ETC_OXM"),
+ "src/test/resources/bundleconfig-local/etc/oxm/");
- }
+ }
- @Before
- public void setup() throws Exception {
- //createGraph();
+ @Before
+ public void setup() throws Exception {
+ // createGraph();
version = schemaVersions.getDefaultVersion();
- loader = SpringContextAware.getBean(LoaderFactory.class).createLoaderForVersion(introspectorFactoryType, version);
- dbEngine = new JanusGraphDBEngine(queryStyle, type, loader);
- spy = spy(dbEngine);
- adminSpy = spy(dbEngine.asAdmin());
-
-
- engine = new JanusGraphDBEngine(queryStyle, type, loader);
- dbser = new DBSerializer(version, engine, introspectorFactoryType, "AAI-TEST");
- }
-
- @After
- public void tearDown() throws Exception {
- engine.rollback();
- }
-
- @AfterClass
- public static void destroy() throws Exception {
- graph.close();
- }
-
- public void subnetSetup() throws AAIException {
- /*
- * This setus up the test graph, For future junits , add more vertices
- * and edges
- */
-
- Vertex l3interipv4addresslist_1 = graph.traversal().addV("aai-node-type", "l3-interface-ipv4-address-list",
- "l3-interface-ipv4-address", "l3-interface-ipv4-address-1").next();
- Vertex subnet_2 = graph.traversal().addV("aai-node-type", "subnet", "subnet-id", "subnet-id-2").next();
- Vertex l3interipv6addresslist_3 = graph.traversal().addV("aai-node-type", "l3-interface-ipv6-address-list",
- "l3-interface-ipv6-address", "l3-interface-ipv6-address-3").next();
- Vertex subnet_4 = graph.traversal().addV("aai-node-type", "subnet", "subnet-id", "subnet-id-4").next();
- Vertex subnet_5 = graph.traversal().addV("aai-node-type", "subnet", "subnet-id", "subnet-id-5").next();
- Vertex l3network_6 = graph.traversal()
- .addV("aai-node-type", "l3-network", "network-id", "network-id-6", "network-name", "network-name-6")
- .next();
-
- GraphTraversalSource g = graph.traversal();
- edgeSer.addEdge(g, l3interipv4addresslist_1, subnet_2);
- edgeSer.addEdge(g, l3interipv6addresslist_3, subnet_4);
- edgeSer.addTreeEdge(g, subnet_5, l3network_6);
- }
-
- public String testDelete(Vertex v) throws AAIException {
-
- GraphTraversalSource traversal = graph.traversal();
- when(spy.asAdmin()).thenReturn(adminSpy);
- when(adminSpy.getTraversalSource()).thenReturn(traversal);
- when(adminSpy.getReadOnlyTraversalSource()).thenReturn(traversal);
-
- String exceptionMessage = "";
- DBSerializer serializer = new DBSerializer(version, spy, introspectorFactoryType, "AAI_TEST");
- try {
- serializer.delete(v, "resourceVersion", false);
- } catch (AAIException exception) {
- exceptionMessage = exception.getMessage();
- }
- return exceptionMessage;
-
- }
-
- @Test
- public void serializeToDbNewVertexAndEdgeAAIUUIDTest() throws AAIException, UnsupportedEncodingException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, URISyntaxException {
- String testName = new Object() {}.getClass().getEnclosingMethod().getName();
- DBSerializer localDbser = getDBSerializerWithSpecificEdgeRules();
-
- engine.startTransaction();
-
- engine.tx().addVertex("aai-node-type","vnfc","vnfc-name","vnfc-" + testName, AAIProperties.AAI_URI, "/network/vnfcs/vnfc/vnfc-" + testName);
-
- Introspector relationship = loader.introspectorFromName("relationship");
- relationship.setValue("related-to", "vnfc");
- relationship.setValue("related-link", "/network/vnfcs/vnfc/vnfc-" + testName);
-
- Introspector relationshipList = loader.introspectorFromName("relationship-list");
- relationshipList.setValue("relationship", Collections.singletonList(relationship.getUnderlyingObject()));
-
- Introspector gvnfObj = loader.introspectorFromName("generic-vnf");
- Vertex gvnf = localDbser.createNewVertex(gvnfObj);
- gvnfObj.setValue("relationship-list", relationshipList.getUnderlyingObject());
- gvnfObj.setValue("vnf-id", "vnf-" + testName);
-
- QueryParser uriQuery = dbEngine.getQueryBuilder().createQueryFromURI(new URI("/network/generic-vnfs/generic-vnf/vnf-" + testName));
-
- localDbser.serializeToDb(gvnfObj, gvnf, uriQuery, null, "test");
- assertTrue("Generic-vnf has uuid ", gvnf.property(AAIProperties.AAI_UUID).isPresent());
- assertTrue("Edge has uuid ", gvnf.edges(Direction.BOTH).next().property(AAIProperties.AAI_UUID).isPresent());
-
- }
-
- @Test
- public void createEdgeWithValidLabelTest() throws AAIException, UnsupportedEncodingException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
-
- DBSerializer localDbser = getDBSerializerWithSpecificEdgeRules();
-
- engine.startTransaction();
-
- Vertex gvnf = engine.tx().addVertex("aai-node-type","generic-vnf","vnf-id","myvnf", "aai-uri", "/network/generic-vnfs/generic-vnf/myvnf");
- Vertex vnfc = engine.tx().addVertex("aai-node-type","vnfc","vnfc-name","a-name", "aai-uri", "/network/vnfcs/vnfc/a-name");
-
- //sunny day case
- Introspector relData = loader.introspectorFromName("relationship-data");
- relData.setValue("relationship-key", "vnfc.vnfc-name");
- relData.setValue("relationship-value", "a-name");
- Introspector relationship = loader.introspectorFromName("relationship");
- relationship.setValue("related-to", "vnfc");
- relationship.setValue("related-link", "/network/vnfcs/vnfc/a-name");
- relationship.setValue("relationship-data",relData);
- relationship.setValue("relationship-label", "over-uses");
-
- assertTrue(localDbser.createEdge(relationship, gvnf));
- assertTrue(engine.tx().traversal().V(gvnf).both("over-uses").hasNext());
- assertTrue(engine.tx().traversal().V(vnfc).both("over-uses").hasNext());
-
- }
-
- @Test
- public void createEdgeWithValidLabelWhenSameEdgeExistsTest() throws AAIException, UnsupportedEncodingException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
-
- DBSerializer localDbser = getDBSerializerWithSpecificEdgeRules();
- engine.startTransaction();
-
- Vertex gvnf = engine.tx().addVertex("aai-node-type","generic-vnf","vnf-id","myvnf", "aai-uri", "/network/generic-vnfs/generic-vnf/myvnf");
- Vertex vnfc = engine.tx().addVertex("aai-node-type","vnfc","vnfc-name","a-name", "aai-uri", "/network/vnfcs/vnfc/a-name");
- edgeSer.addEdge(graph.traversal(), gvnf, vnfc, "re-uses");
-
- Introspector relData = loader.introspectorFromName("relationship-data");
- relData.setValue("relationship-key", "vnfc.vnfc-name");
- relData.setValue("relationship-value", "a-name");
- Introspector relationship = loader.introspectorFromName("relationship");
- relationship.setValue("related-to", "vnfc");
- relationship.setValue("related-link", "/network/vnfcs/vnfc/a-name");
- relationship.setValue("relationship-data",relData);
- relationship.setValue("relationship-label", "re-uses");
-
- assertTrue(localDbser.createEdge(relationship, gvnf));
- assertTrue(engine.tx().traversal().V(gvnf).both("re-uses").hasNext());
- assertTrue(engine.tx().traversal().V(vnfc).both("re-uses").hasNext());
- assertEquals("Number of edges between vertexes is 1", Long.valueOf(1), engine.tx().traversal().V(vnfc).both().count().next());
-
- }
-
- @Test
- public void createEdgeWithValidLabelWhenDiffEdgeExistsTest() throws AAIException, UnsupportedEncodingException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
-
- DBSerializer localDbser = getDBSerializerWithSpecificEdgeRules();
- engine.startTransaction();
-
- Vertex gvnf = engine.tx().addVertex("aai-node-type","generic-vnf","vnf-id","myvnf", "aai-uri", "/network/generic-vnfs/generic-vnf/myvnf");
- Vertex vnfc = engine.tx().addVertex("aai-node-type","vnfc","vnfc-name","a-name", "aai-uri", "/network/vnfcs/vnfc/a-name");
- edgeSer.addEdge(graph.traversal(), gvnf, vnfc, "uses");
-
- Introspector relData = loader.introspectorFromName("relationship-data");
- relData.setValue("relationship-key", "vnfc.vnfc-name");
- relData.setValue("relationship-value", "a-name");
- Introspector relationship = loader.introspectorFromName("relationship");
- relationship.setValue("related-to", "vnfc");
- relationship.setValue("related-link", "/network/vnfcs/vnfc/a-name");
- relationship.setValue("relationship-data",relData);
- relationship.setValue("relationship-label", "uses");
- localDbser.createEdge(relationship, gvnf);
-
- relationship.setValue("relationship-label", "re-uses");
-
- assertTrue(localDbser.createEdge(relationship, gvnf));
- assertTrue(engine.tx().traversal().V(gvnf).both("re-uses").hasNext());
- assertTrue(engine.tx().traversal().V(vnfc).both("re-uses").hasNext());
- assertTrue(engine.tx().traversal().V(gvnf).both("uses").hasNext());
- assertTrue(engine.tx().traversal().V(vnfc).both("uses").hasNext());
- assertEquals("Number of edges between vertexes is 2", Long.valueOf(2), engine.tx().traversal().V(vnfc).both().count().next());
- assertEquals("Number of edges between vertexes is 2", Long.valueOf(2), engine.tx().traversal().V(gvnf).both().count().next());
-
- }
-
- @Test
- public void createEdgeWithNoLabelTest() throws AAIException, UnsupportedEncodingException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
-
- DBSerializer localDbser = getDBSerializerWithSpecificEdgeRules();
- engine.startTransaction();
-
- Vertex gvnf = engine.tx().addVertex("aai-node-type","generic-vnf","vnf-id","myvnf", "aai-uri", "/network/generic-vnfs/generic-vnf/myvnf");
- Vertex vnfc = engine.tx().addVertex("aai-node-type","vnfc","vnfc-name","a-name", "aai-uri", "/network/vnfcs/vnfc/a-name");
-
- Introspector relData = loader.introspectorFromName("relationship-data");
- relData.setValue("relationship-key", "vnfc.vnfc-name");
- relData.setValue("relationship-value", "a-name");
- Introspector relationship = loader.introspectorFromName("relationship");
- relationship.setValue("related-to", "vnfc");
- relationship.setValue("related-link", "/network/vnfcs/vnfc/a-name");
- relationship.setValue("relationship-data",relData);
- localDbser.createEdge(relationship, gvnf);
-
- assertTrue(localDbser.createEdge(relationship, gvnf));
- assertTrue(engine.tx().traversal().V(gvnf).both("uses").hasNext());
- assertTrue(engine.tx().traversal().V(vnfc).both("uses").hasNext());
- assertEquals("Number of edges between vertexes is 1", Long.valueOf(1), engine.tx().traversal().V(vnfc).both().count().next());
- assertEquals("Number of edges between vertexes is 1", Long.valueOf(1), engine.tx().traversal().V(gvnf).both().count().next());
-
-
- }
-
- @Test
- public void deleteEdgeWithNoLabelWhenMultipleExistsTest() throws AAIException, UnsupportedEncodingException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
-
- DBSerializer localDbser = getDBSerializerWithSpecificEdgeRules();
- engine.startTransaction();
-
- Vertex gvnf = engine.tx().addVertex("aai-node-type","generic-vnf","vnf-id","myvnf", "aai-uri", "/network/generic-vnfs/generic-vnf/myvnf");
- Vertex vnfc = engine.tx().addVertex("aai-node-type","vnfc","vnfc-name","a-name", "aai-uri", "/network/vnfcs/vnfc/a-name");
- edgeSer.addEdge(graph.traversal(), gvnf, vnfc, "uses");
- edgeSer.addEdge(graph.traversal(), gvnf, vnfc, "re-uses");
- edgeSer.addEdge(graph.traversal(), gvnf, vnfc, "over-uses");
-
- Introspector relData = loader.introspectorFromName("relationship-data");
- relData.setValue("relationship-key", "vnfc.vnfc-name");
- relData.setValue("relationship-value", "a-name");
- Introspector relationship = loader.introspectorFromName("relationship");
- relationship.setValue("related-to", "vnfc");
- relationship.setValue("related-link", "/network/vnfcs/vnfc/a-name");
- relationship.setValue("relationship-data",relData);
-
- assertTrue(localDbser.deleteEdge(relationship, gvnf));
- assertFalse("generic-vnf has no edge uses", engine.tx().traversal().V(gvnf).both("uses").hasNext());
- assertFalse("vnfc has no edge uses", engine.tx().traversal().V(vnfc).both("uses").hasNext());
- assertTrue("generic-vnf has edge re-uses", engine.tx().traversal().V(gvnf).both("re-uses").hasNext());
- assertTrue("vnfc has edge re-uses", engine.tx().traversal().V(vnfc).both("re-uses").hasNext());
- assertTrue("generic-vnf has edge re-uses", engine.tx().traversal().V(gvnf).both("over-uses").hasNext());
- assertTrue("vnfc has edge re-uses", engine.tx().traversal().V(vnfc).both("over-uses").hasNext());
- assertEquals("Number of edges between vertexes is 2", Long.valueOf(2), engine.tx().traversal().V(vnfc).both().count().next());
- assertEquals("Number of edges between vertexes is 2", Long.valueOf(2), engine.tx().traversal().V(gvnf).both().count().next());
-
- }
-
- @Test
- public void deleteEdgeWithValidLabelWhenMultipleExistsTest() throws AAIException, UnsupportedEncodingException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
-
- DBSerializer localDbser = getDBSerializerWithSpecificEdgeRules();
-
- engine.startTransaction();
-
- Vertex gvnf = engine.tx().addVertex("aai-node-type","generic-vnf","vnf-id","myvnf", "aai-uri", "/network/generic-vnfs/generic-vnf/myvnf");
- Vertex vnfc = engine.tx().addVertex("aai-node-type","vnfc","vnfc-name","a-name", "aai-uri", "/network/vnfcs/vnfc/a-name");
- edgeSer.addEdge(graph.traversal(), gvnf, vnfc, "uses");
- edgeSer.addEdge(graph.traversal(), gvnf, vnfc, "re-uses");
- edgeSer.addEdge(graph.traversal(), gvnf, vnfc, "over-uses");
-
- Introspector relData = loader.introspectorFromName("relationship-data");
- relData.setValue("relationship-key", "vnfc.vnfc-name");
- relData.setValue("relationship-value", "a-name");
- Introspector relationship = loader.introspectorFromName("relationship");
- relationship.setValue("related-to", "vnfc");
- relationship.setValue("related-link", "/network/vnfcs/vnfc/a-name");
- relationship.setValue("relationship-data",relData);
- relationship.setValue("relationship-label", "re-uses");
-
- assertTrue(localDbser.deleteEdge(relationship, gvnf));
- assertTrue("generic-vnf has edge uses", engine.tx().traversal().V(gvnf).both("uses").hasNext());
- assertTrue("vnfc has edge uses", engine.tx().traversal().V(vnfc).both("uses").hasNext());
- assertFalse("generic-vnf has no edge re-uses", engine.tx().traversal().V(gvnf).both("re-uses").hasNext());
- assertFalse("vnfc has no edge re-uses", engine.tx().traversal().V(vnfc).both("re-uses").hasNext());
- assertTrue("generic-vnf has edge re-uses", engine.tx().traversal().V(gvnf).both("over-uses").hasNext());
- assertTrue("vnfc has edge re-uses", engine.tx().traversal().V(vnfc).both("over-uses").hasNext());
- assertEquals("Number of edges between vertexes is 2", Long.valueOf(2), engine.tx().traversal().V(vnfc).both().count().next());
- assertEquals("Number of edges between vertexes is 2", Long.valueOf(2), engine.tx().traversal().V(gvnf).both().count().next());
-
- }
-
- @Test
- public void deleteEdgeWithValidInvalidLabelWhenMultipleExistsTest() throws AAIException, UnsupportedEncodingException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
-
- DBSerializer localDbser = getDBSerializerWithSpecificEdgeRules();
-
- engine.startTransaction();
-
- Vertex gvnf = engine.tx().addVertex("aai-node-type","generic-vnf","vnf-id","myvnf", "aai-uri", "/network/generic-vnfs/generic-vnf/myvnf");
- Vertex vnfc = engine.tx().addVertex("aai-node-type","vnfc","vnfc-name","a-name", "aai-uri", "/network/vnfcs/vnfc/a-name");
- edgeSer.addEdge(graph.traversal(), gvnf, vnfc, "uses");
- edgeSer.addEdge(graph.traversal(), gvnf, vnfc, "re-uses");
- edgeSer.addEdge(graph.traversal(), gvnf, vnfc, "over-uses");
-
- Introspector relData = loader.introspectorFromName("relationship-data");
- relData.setValue("relationship-key", "vnfc.vnfc-name");
- relData.setValue("relationship-value", "a-name");
- Introspector relationship = loader.introspectorFromName("relationship");
- relationship.setValue("related-to", "vnfc");
- relationship.setValue("related-link", "/network/vnfcs/vnfc/a-name");
- relationship.setValue("relationship-data",relData);
- relationship.setValue("relationship-label", "NA");
-
- thrown.expect(AAIException.class);
- thrown.expectMessage("No rule found");
- thrown.expectMessage("node type: generic-vnf, node type: vnfc, label: NA, type: COUSIN");
- localDbser.deleteEdge(relationship, gvnf);
- }
-
- @Test
- public void serializeToDbWithLabelTest() throws AAIException, UnsupportedEncodingException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, URISyntaxException {
-
- DBSerializer localDbser = getDBSerializerWithSpecificEdgeRules();
-
- engine.startTransaction();
-
- engine.tx().addVertex("aai-node-type","vnfc","vnfc-name","a-name", "aai-uri", "/network/vnfcs/vnfc/a-name");
-
- Introspector relationship = loader.introspectorFromName("relationship");
- relationship.setValue("related-to", "vnfc");
- relationship.setValue("related-link", "/network/vnfcs/vnfc/a-name");
- relationship.setValue("relationship-label", "re-uses");
- Introspector relationshipList = loader.introspectorFromName("relationship-list");
- relationshipList.setValue("relationship", Collections.singletonList(relationship.getUnderlyingObject()));
-
- Introspector gvnfObj = loader.introspectorFromName("generic-vnf");
- Vertex gvnf = localDbser.createNewVertex(gvnfObj);
- gvnfObj.setValue("relationship-list", relationshipList.getUnderlyingObject());
- gvnfObj.setValue("vnf-id", "myvnf");
-
- QueryParser uriQuery = dbEngine.getQueryBuilder().createQueryFromURI(new URI("/network/generic-vnfs/generic-vnf/myvnf"));
-
- localDbser.serializeToDb(gvnfObj, gvnf, uriQuery, null, "test");
-
- assertTrue("vertex with vnf-id myvnf exists", engine.tx().traversal().V().has("vnf-id", "myvnf").hasNext());
- assertTrue("vertex with vnfc-name a-name exists", engine.tx().traversal().V().has("vnfc-name", "a-name").hasNext());
- assertFalse("generic-vnf has no edge re-uses", engine.tx().traversal().V().has("vnf-id", "myvnf").both("uses").hasNext());
- assertFalse("vnfc has no edge re-uses", engine.tx().traversal().V().has("vnfc-name", "a-name").both("uses").hasNext());
- assertTrue("generic-vnf has edge re-uses", engine.tx().traversal().V().has("vnf-id", "myvnf").both("re-uses").hasNext());
- assertTrue("vnfc has edge re-uses", engine.tx().traversal().V().has("vnfc-name", "a-name").both("re-uses").hasNext());
- assertFalse("generic-vnf has no edge re-uses", engine.tx().traversal().V().has("vnf-id", "myvnf").both("over-uses").hasNext());
- assertFalse("vnfc has no edge re-uses", engine.tx().traversal().V().has("vnfc-name", "a-name").both("over-uses").hasNext());
- assertEquals("Number of edges between vertexes is 1", Long.valueOf(1), engine.tx().traversal().V().has("vnfc-name", "a-name").both().count().next());
- assertEquals("Number of edges between vertexes is 1", Long.valueOf(1), engine.tx().traversal().V().has("vnf-id", "myvnf").both().count().next());
-
- }
-
- @Test
- public void serializeToDbWithoutLabelTest() throws AAIException, UnsupportedEncodingException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, URISyntaxException {
-
- DBSerializer localDbser = getDBSerializerWithSpecificEdgeRules();
-
- engine.startTransaction();
-
- engine.tx().addVertex("aai-node-type","vnfc","vnfc-name","a-name", "aai-uri", "/network/vnfcs/vnfc/a-name");
-
- Introspector relationship = loader.introspectorFromName("relationship");
- relationship.setValue("related-to", "vnfc");
- relationship.setValue("related-link", "/network/vnfcs/vnfc/a-name");
-
- Introspector relationshipList = loader.introspectorFromName("relationship-list");
- relationshipList.setValue("relationship", Collections.singletonList(relationship.getUnderlyingObject()));
-
- Introspector gvnfObj = loader.introspectorFromName("generic-vnf");
- Vertex gvnf = localDbser.createNewVertex(gvnfObj);
- gvnfObj.setValue("relationship-list", relationshipList.getUnderlyingObject());
- gvnfObj.setValue("vnf-id", "myvnf");
-
- QueryParser uriQuery = dbEngine.getQueryBuilder().createQueryFromURI(new URI("/network/generic-vnfs/generic-vnf/myvnf"));
-
- localDbser.serializeToDb(gvnfObj, gvnf, uriQuery, null, "test");
-
- assertTrue("vertex with vnf-id myvnf exists", engine.tx().traversal().V().has("vnf-id", "myvnf").hasNext());
- assertTrue("vertex with vnfc-name a-name exists", engine.tx().traversal().V().has("vnfc-name", "a-name").hasNext());
- assertTrue("generic-vnf has edge uses", engine.tx().traversal().V().has("vnf-id", "myvnf").both("uses").hasNext());
- assertTrue("vnfc has edge uses", engine.tx().traversal().V().has("vnfc-name", "a-name").both("uses").hasNext());
- assertFalse("generic-vnf has no edge re-uses", engine.tx().traversal().V().has("vnf-id", "myvnf").both("re-uses").hasNext());
- assertFalse("vnfc has no edge re-uses", engine.tx().traversal().V().has("vnfc-name", "a-name").both("re-uses").hasNext());
- assertFalse("generic-vnf has no edge over-uses", engine.tx().traversal().V().has("vnf-id", "myvnf").both("over-uses").hasNext());
- assertFalse("vnfc has no edge over-uses", engine.tx().traversal().V().has("vnfc-name", "a-name").both("over-uses").hasNext());
- assertEquals("Number of edges between vertexes is 1", Long.valueOf(1), engine.tx().traversal().V().has("vnfc-name", "a-name").both().count().next());
- assertEquals("Number of edges between vertexes is 1", Long.valueOf(1), engine.tx().traversal().V().has("vnf-id", "myvnf").both().count().next());
-
- }
-
- @Test
- public void serializeToDbWithInvalidLabelTest() throws AAIException, UnsupportedEncodingException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, URISyntaxException {
-
- DBSerializer localDbser = getDBSerializerWithSpecificEdgeRules();
-
- engine.startTransaction();
-
- engine.tx().addVertex("aai-node-type","vnfc","vnfc-name","a-name", "aai-uri", "/network/vnfcs/vnfc/a-name");
-
- Introspector relationship = loader.introspectorFromName("relationship");
- relationship.setValue("related-to", "vnfc");
- relationship.setValue("related-link", "/network/vnfcs/vnfc/a-name");
- relationship.setValue("relationship-label", "NA");
- Introspector relationshipList = loader.introspectorFromName("relationship-list");
- relationshipList.setValue("relationship", Collections.singletonList(relationship.getUnderlyingObject()));
-
- Introspector gvnfObj = loader.introspectorFromName("generic-vnf");
- Vertex gvnf = localDbser.createNewVertex(gvnfObj);
- gvnfObj.setValue("relationship-list", relationshipList.getUnderlyingObject());
- gvnfObj.setValue("vnf-id", "myvnf");
-
- QueryParser uriQuery = dbEngine.getQueryBuilder().createQueryFromURI(new URI("/network/generic-vnfs/generic-vnf/myvnf"));
-
- thrown.expect(AAIException.class);
- thrown.expectMessage("No EdgeRule found for passed nodeTypes: generic-vnf, vnfc with label NA.");
- localDbser.serializeToDb(gvnfObj, gvnf, uriQuery, null, "test");
-
- }
-
- @Test
- public void serializeToDbWithLabelAndEdgeExistsTest() throws AAIException, UnsupportedEncodingException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, URISyntaxException {
-
- DBSerializer localDbser = getDBSerializerWithSpecificEdgeRules();
-
- engine.startTransaction();
- engine.tx().addVertex("aai-node-type","vnfc","vnfc-name","a-name", "aai-uri", "/network/vnfcs/vnfc/a-name");
-
- Introspector relationship;
- Introspector relationshipList;
- List<Object> relList = new ArrayList<>();
-
- // create generic-vnf
- Introspector gvnfObj = loader.introspectorFromName("generic-vnf");
- Vertex gvnf = localDbser.createNewVertex(gvnfObj);
- gvnfObj.setValue("vnf-id", "myvnf");
- QueryParser uriQuery = dbEngine.getQueryBuilder().createQueryFromURI(new URI("/network/generic-vnfs/generic-vnf/myvnf"));
-
- // create relationship to vnfc
- relationship = loader.introspectorFromName("relationship");
- relationship.setValue("related-to", "vnfc");
- relationship.setValue("related-link", "/network/vnfcs/vnfc/a-name");
- relList.add(relationship.getUnderlyingObject());
- relationshipList = loader.introspectorFromName("relationship-list");
- relationshipList.setValue("relationship", relList);
- gvnfObj.setValue("relationship-list", relationshipList.getUnderlyingObject());
-
- // add gvnf to graph
- localDbser.serializeToDb(gvnfObj, gvnf, uriQuery, null, "test");
-
- // add second relationship
- relationship = loader.introspectorFromName("relationship");
- relationship.setValue("related-to", "vnfc");
- relationship.setValue("related-link", "/network/vnfcs/vnfc/a-name");
- relationship.setValue("relationship-label", "re-uses");
- relList.add(relationship.getUnderlyingObject());
- relationshipList = loader.introspectorFromName("relationship-list");
- relationshipList.setValue("relationship", relList);
- gvnfObj.setValue("relationship-list", relationshipList.getUnderlyingObject());
-
- localDbser.serializeToDb(gvnfObj, gvnf, uriQuery, null, "test");
-
- assertTrue("vertex with vnf-id myvnf exists", engine.tx().traversal().V().has("vnf-id", "myvnf").hasNext());
- assertTrue("vertex with vnfc-name a-name exists", engine.tx().traversal().V().has("vnfc-name", "a-name").hasNext());
- assertTrue("generic-vnf has edge uses", engine.tx().traversal().V().has("vnf-id", "myvnf").both("uses").hasNext());
- assertTrue("vnfc has edge uses", engine.tx().traversal().V().has("vnfc-name", "a-name").both("uses").hasNext());
- assertTrue("generic-vnf has edge re-uses", engine.tx().traversal().V().has("vnf-id", "myvnf").both("re-uses").hasNext());
- assertTrue("vnfc has edge re-uses", engine.tx().traversal().V().has("vnfc-name", "a-name").both("re-uses").hasNext());
- assertFalse("generic-vnf has no edge over-uses", engine.tx().traversal().V().has("vnf-id", "myvnf").both("over-uses").hasNext());
- assertFalse("vnfc has no edge over-uses", engine.tx().traversal().V().has("vnfc-name", "a-name").both("over-uses").hasNext());
- assertEquals("Number of edges between vertexes is 2", Long.valueOf(2), engine.tx().traversal().V().has("vnfc-name", "a-name").both().count().next());
- assertEquals("Number of edges between vertexes is 2", Long.valueOf(2), engine.tx().traversal().V().has("vnf-id", "myvnf").both().count().next());
-
- }
-
- @Test
- public void serializeToDbWithLabelDroppingRelationshipTest() throws AAIException, UnsupportedEncodingException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, URISyntaxException {
-
- DBSerializer localDbser = getDBSerializerWithSpecificEdgeRules();
-
- engine.startTransaction();
- engine.tx().addVertex("aai-node-type","vnfc","vnfc-name","a-name", "aai-uri", "/network/vnfcs/vnfc/a-name");
-
-
- Introspector relationship;
- Introspector relationshipList;
- List<Object> relList = new ArrayList<>();
-
- // create generic-vnf
- Introspector gvnfObj = loader.introspectorFromName("generic-vnf");
- Vertex gvnf = localDbser.createNewVertex(gvnfObj);
- gvnfObj.setValue("vnf-id", "myvnf");
- QueryParser uriQuery = dbEngine.getQueryBuilder().createQueryFromURI(new URI("/network/generic-vnfs/generic-vnf/myvnf"));
-
- // create relationship to vnfc
- relationship = loader.introspectorFromName("relationship");
- relationship.setValue("related-to", "vnfc");
- relationship.setValue("related-link", "/network/vnfcs/vnfc/a-name");
- relList.add(relationship.getUnderlyingObject());
- // add second relationship
- relationship = loader.introspectorFromName("relationship");
- relationship.setValue("related-to", "vnfc");
- relationship.setValue("related-link", "/network/vnfcs/vnfc/a-name");
- relationship.setValue("relationship-label", "re-uses");
- relList.add(relationship.getUnderlyingObject());
- relationshipList = loader.introspectorFromName("relationship-list");
- relationshipList.setValue("relationship", relList);
- gvnfObj.setValue("relationship-list", relationshipList.getUnderlyingObject());
-
- // add gvnf to graph
- localDbser.serializeToDb(gvnfObj, gvnf, uriQuery, null, "test");
-
- // drop second relationship
- relList.remove(1);
- relationshipList = loader.introspectorFromName("relationship-list");
- relationshipList.setValue("relationship", relList);
- gvnfObj.setValue("relationship-list", relationshipList.getUnderlyingObject());
-
- localDbser.serializeToDb(gvnfObj, gvnf, uriQuery, null, "test");
-
- assertTrue("vertex with vnf-id myvnf exists", engine.tx().traversal().V().has("vnf-id", "myvnf").hasNext());
- assertTrue("vertex with vnfc-name a-name exists", engine.tx().traversal().V().has("vnfc-name", "a-name").hasNext());
- assertTrue("generic-vnf has edge uses", engine.tx().traversal().V().has("vnf-id", "myvnf").both("uses").hasNext());
- assertTrue("vnfc has edge uses", engine.tx().traversal().V().has("vnfc-name", "a-name").both("uses").hasNext());
- assertFalse("generic-vnf no longer has edge re-uses", engine.tx().traversal().V().has("vnf-id", "myvnf").both("re-uses").hasNext());
- assertFalse("vnfc no longer has edge re-uses", engine.tx().traversal().V().has("vnfc-name", "a-name").both("re-uses").hasNext());
- assertFalse("generic-vnf has no edge over-uses", engine.tx().traversal().V().has("vnf-id", "myvnf").both("over-uses").hasNext());
- assertFalse("vnfc has no edge over-uses", engine.tx().traversal().V().has("vnfc-name", "a-name").both("over-uses").hasNext());
- assertEquals("Number of edges between vertexes is 1", Long.valueOf(1), engine.tx().traversal().V().has("vnfc-name", "a-name").both().count().next());
- assertEquals("Number of edges between vertexes is 1", Long.valueOf(1), engine.tx().traversal().V().has("vnf-id", "myvnf").both().count().next());
-
- }
-
- private DBSerializer getDBSerializerWithSpecificEdgeRules()
- throws NoSuchFieldException, AAIException, IllegalAccessException {
-
-
- DBSerializer localDbser = new DBSerializer(version, engine, introspectorFactoryType, "AAI-TEST");
- return localDbser;
- }
+ loader = SpringContextAware.getBean(LoaderFactory.class).createLoaderForVersion(introspectorFactoryType,
+ version);
+ dbEngine = new JanusGraphDBEngine(queryStyle, type, loader);
+ spy = spy(dbEngine);
+ adminSpy = spy(dbEngine.asAdmin());
+
+ engine = new JanusGraphDBEngine(queryStyle, type, loader);
+ dbser = new DBSerializer(version, engine, introspectorFactoryType, "AAI-TEST");
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ engine.rollback();
+ }
+
+ @AfterClass
+ public static void destroy() throws Exception {
+ graph.close();
+ }
+
+ public void subnetSetup() throws AAIException {
+ /*
+ * This setus up the test graph, For future junits , add more vertices
+ * and edges
+ */
+
+ Vertex l3interipv4addresslist_1 = graph.traversal().addV("aai-node-type", "l3-interface-ipv4-address-list",
+ "l3-interface-ipv4-address", "l3-interface-ipv4-address-1").next();
+ Vertex subnet_2 = graph.traversal().addV("aai-node-type", "subnet", "subnet-id", "subnet-id-2").next();
+ Vertex l3interipv6addresslist_3 = graph.traversal().addV("aai-node-type", "l3-interface-ipv6-address-list",
+ "l3-interface-ipv6-address", "l3-interface-ipv6-address-3").next();
+ Vertex subnet_4 = graph.traversal().addV("aai-node-type", "subnet", "subnet-id", "subnet-id-4").next();
+ Vertex subnet_5 = graph.traversal().addV("aai-node-type", "subnet", "subnet-id", "subnet-id-5").next();
+ Vertex l3network_6 = graph.traversal()
+ .addV("aai-node-type", "l3-network", "network-id", "network-id-6", "network-name", "network-name-6")
+ .next();
+
+ GraphTraversalSource g = graph.traversal();
+ edgeSer.addEdge(g, l3interipv4addresslist_1, subnet_2);
+ edgeSer.addEdge(g, l3interipv6addresslist_3, subnet_4);
+ edgeSer.addTreeEdge(g, subnet_5, l3network_6);
+ }
+
+ public String testDelete(Vertex v) throws AAIException {
+
+ GraphTraversalSource traversal = graph.traversal();
+ when(spy.asAdmin()).thenReturn(adminSpy);
+ when(adminSpy.getTraversalSource()).thenReturn(traversal);
+ when(adminSpy.getReadOnlyTraversalSource()).thenReturn(traversal);
+
+ String exceptionMessage = "";
+ DBSerializer serializer = new DBSerializer(version, spy, introspectorFactoryType, "AAI_TEST");
+ try {
+ serializer.delete(v, "resourceVersion", false);
+ } catch (AAIException exception) {
+ exceptionMessage = exception.getMessage();
+ }
+ return exceptionMessage;
+
+ }
+
+ @Test
+ public void serializeToDbNewVertexAndEdgeAAIUUIDTest()
+ throws AAIException, UnsupportedEncodingException, NoSuchFieldException, SecurityException,
+ IllegalArgumentException, IllegalAccessException, URISyntaxException {
+ String testName = new Object() {}.getClass().getEnclosingMethod().getName();
+ DBSerializer localDbser = getDBSerializerWithSpecificEdgeRules();
+
+ engine.startTransaction();
+
+ engine.tx().addVertex("aai-node-type", "vnfc", "vnfc-name", "vnfc-" + testName, AAIProperties.AAI_URI,
+ "/network/vnfcs/vnfc/vnfc-" + testName);
+
+ Introspector relationship = loader.introspectorFromName("relationship");
+ relationship.setValue("related-to", "vnfc");
+ relationship.setValue("related-link", "/network/vnfcs/vnfc/vnfc-" + testName);
+
+ Introspector relationshipList = loader.introspectorFromName("relationship-list");
+ relationshipList.setValue("relationship", Collections.singletonList(relationship.getUnderlyingObject()));
+
+ Introspector gvnfObj = loader.introspectorFromName("generic-vnf");
+ Vertex gvnf = localDbser.createNewVertex(gvnfObj);
+ gvnfObj.setValue("relationship-list", relationshipList.getUnderlyingObject());
+ gvnfObj.setValue("vnf-id", "vnf-" + testName);
+
+ QueryParser uriQuery = dbEngine.getQueryBuilder()
+ .createQueryFromURI(new URI("/network/generic-vnfs/generic-vnf/vnf-" + testName));
+
+ localDbser.serializeToDb(gvnfObj, gvnf, uriQuery, null, "test");
+ assertTrue("Generic-vnf has uuid ", gvnf.property(AAIProperties.AAI_UUID).isPresent());
+ assertTrue("Edge has uuid ", gvnf.edges(Direction.BOTH).next().property(AAIProperties.AAI_UUID).isPresent());
+
+ }
+
+ @Test
+ public void createEdgeWithValidLabelTest() throws AAIException, UnsupportedEncodingException, NoSuchFieldException,
+ SecurityException, IllegalArgumentException, IllegalAccessException {
+
+ DBSerializer localDbser = getDBSerializerWithSpecificEdgeRules();
+
+ engine.startTransaction();
+
+ Vertex gvnf = engine.tx().addVertex("aai-node-type", "generic-vnf", "vnf-id", "myvnf", "aai-uri",
+ "/network/generic-vnfs/generic-vnf/myvnf");
+ Vertex vnfc = engine.tx().addVertex("aai-node-type", "vnfc", "vnfc-name", "a-name", "aai-uri",
+ "/network/vnfcs/vnfc/a-name");
+
+ // sunny day case
+ Introspector relData = loader.introspectorFromName("relationship-data");
+ relData.setValue("relationship-key", "vnfc.vnfc-name");
+ relData.setValue("relationship-value", "a-name");
+ Introspector relationship = loader.introspectorFromName("relationship");
+ relationship.setValue("related-to", "vnfc");
+ relationship.setValue("related-link", "/network/vnfcs/vnfc/a-name");
+ relationship.setValue("relationship-data", relData);
+ relationship.setValue("relationship-label", "over-uses");
+
+ assertTrue(localDbser.createEdge(relationship, gvnf));
+ assertTrue(engine.tx().traversal().V(gvnf).both("over-uses").hasNext());
+ assertTrue(engine.tx().traversal().V(vnfc).both("over-uses").hasNext());
+
+ }
+
+ @Test
+ public void createEdgeWithValidLabelWhenSameEdgeExistsTest() throws AAIException, UnsupportedEncodingException,
+ NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
+
+ DBSerializer localDbser = getDBSerializerWithSpecificEdgeRules();
+ engine.startTransaction();
+
+ Vertex gvnf = engine.tx().addVertex("aai-node-type", "generic-vnf", "vnf-id", "myvnf", "aai-uri",
+ "/network/generic-vnfs/generic-vnf/myvnf");
+ Vertex vnfc = engine.tx().addVertex("aai-node-type", "vnfc", "vnfc-name", "a-name", "aai-uri",
+ "/network/vnfcs/vnfc/a-name");
+ edgeSer.addEdge(graph.traversal(), gvnf, vnfc, "re-uses");
+
+ Introspector relData = loader.introspectorFromName("relationship-data");
+ relData.setValue("relationship-key", "vnfc.vnfc-name");
+ relData.setValue("relationship-value", "a-name");
+ Introspector relationship = loader.introspectorFromName("relationship");
+ relationship.setValue("related-to", "vnfc");
+ relationship.setValue("related-link", "/network/vnfcs/vnfc/a-name");
+ relationship.setValue("relationship-data", relData);
+ relationship.setValue("relationship-label", "re-uses");
+
+ assertTrue(localDbser.createEdge(relationship, gvnf));
+ assertTrue(engine.tx().traversal().V(gvnf).both("re-uses").hasNext());
+ assertTrue(engine.tx().traversal().V(vnfc).both("re-uses").hasNext());
+ assertEquals("Number of edges between vertexes is 1", Long.valueOf(1),
+ engine.tx().traversal().V(vnfc).both().count().next());
+
+ }
+
+ @Test
+ public void createEdgeWithValidLabelWhenDiffEdgeExistsTest() throws AAIException, UnsupportedEncodingException,
+ NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
+
+ DBSerializer localDbser = getDBSerializerWithSpecificEdgeRules();
+ engine.startTransaction();
+
+ Vertex gvnf = engine.tx().addVertex("aai-node-type", "generic-vnf", "vnf-id", "myvnf", "aai-uri",
+ "/network/generic-vnfs/generic-vnf/myvnf");
+ Vertex vnfc = engine.tx().addVertex("aai-node-type", "vnfc", "vnfc-name", "a-name", "aai-uri",
+ "/network/vnfcs/vnfc/a-name");
+ edgeSer.addEdge(graph.traversal(), gvnf, vnfc, "uses");
+
+ Introspector relData = loader.introspectorFromName("relationship-data");
+ relData.setValue("relationship-key", "vnfc.vnfc-name");
+ relData.setValue("relationship-value", "a-name");
+ Introspector relationship = loader.introspectorFromName("relationship");
+ relationship.setValue("related-to", "vnfc");
+ relationship.setValue("related-link", "/network/vnfcs/vnfc/a-name");
+ relationship.setValue("relationship-data", relData);
+ relationship.setValue("relationship-label", "uses");
+ localDbser.createEdge(relationship, gvnf);
+
+ relationship.setValue("relationship-label", "re-uses");
+
+ assertTrue(localDbser.createEdge(relationship, gvnf));
+ assertTrue(engine.tx().traversal().V(gvnf).both("re-uses").hasNext());
+ assertTrue(engine.tx().traversal().V(vnfc).both("re-uses").hasNext());
+ assertTrue(engine.tx().traversal().V(gvnf).both("uses").hasNext());
+ assertTrue(engine.tx().traversal().V(vnfc).both("uses").hasNext());
+ assertEquals("Number of edges between vertexes is 2", Long.valueOf(2),
+ engine.tx().traversal().V(vnfc).both().count().next());
+ assertEquals("Number of edges between vertexes is 2", Long.valueOf(2),
+ engine.tx().traversal().V(gvnf).both().count().next());
+
+ }
+
+ @Test
+ public void createEdgeWithNoLabelTest() throws AAIException, UnsupportedEncodingException, NoSuchFieldException,
+ SecurityException, IllegalArgumentException, IllegalAccessException {
+
+ DBSerializer localDbser = getDBSerializerWithSpecificEdgeRules();
+ engine.startTransaction();
+
+ Vertex gvnf = engine.tx().addVertex("aai-node-type", "generic-vnf", "vnf-id", "myvnf", "aai-uri",
+ "/network/generic-vnfs/generic-vnf/myvnf");
+ Vertex vnfc = engine.tx().addVertex("aai-node-type", "vnfc", "vnfc-name", "a-name", "aai-uri",
+ "/network/vnfcs/vnfc/a-name");
+
+ Introspector relData = loader.introspectorFromName("relationship-data");
+ relData.setValue("relationship-key", "vnfc.vnfc-name");
+ relData.setValue("relationship-value", "a-name");
+ Introspector relationship = loader.introspectorFromName("relationship");
+ relationship.setValue("related-to", "vnfc");
+ relationship.setValue("related-link", "/network/vnfcs/vnfc/a-name");
+ relationship.setValue("relationship-data", relData);
+ localDbser.createEdge(relationship, gvnf);
+
+ assertTrue(localDbser.createEdge(relationship, gvnf));
+ assertTrue(engine.tx().traversal().V(gvnf).both("uses").hasNext());
+ assertTrue(engine.tx().traversal().V(vnfc).both("uses").hasNext());
+ assertEquals("Number of edges between vertexes is 1", Long.valueOf(1),
+ engine.tx().traversal().V(vnfc).both().count().next());
+ assertEquals("Number of edges between vertexes is 1", Long.valueOf(1),
+ engine.tx().traversal().V(gvnf).both().count().next());
+
+ }
+
+ @Test
+ public void deleteEdgeWithNoLabelWhenMultipleExistsTest() throws AAIException, UnsupportedEncodingException,
+ NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
+
+ DBSerializer localDbser = getDBSerializerWithSpecificEdgeRules();
+ engine.startTransaction();
+
+ Vertex gvnf = engine.tx().addVertex("aai-node-type", "generic-vnf", "vnf-id", "myvnf", "aai-uri",
+ "/network/generic-vnfs/generic-vnf/myvnf");
+ Vertex vnfc = engine.tx().addVertex("aai-node-type", "vnfc", "vnfc-name", "a-name", "aai-uri",
+ "/network/vnfcs/vnfc/a-name");
+ edgeSer.addEdge(graph.traversal(), gvnf, vnfc, "uses");
+ edgeSer.addEdge(graph.traversal(), gvnf, vnfc, "re-uses");
+ edgeSer.addEdge(graph.traversal(), gvnf, vnfc, "over-uses");
+
+ Introspector relData = loader.introspectorFromName("relationship-data");
+ relData.setValue("relationship-key", "vnfc.vnfc-name");
+ relData.setValue("relationship-value", "a-name");
+ Introspector relationship = loader.introspectorFromName("relationship");
+ relationship.setValue("related-to", "vnfc");
+ relationship.setValue("related-link", "/network/vnfcs/vnfc/a-name");
+ relationship.setValue("relationship-data", relData);
+
+ assertTrue(localDbser.deleteEdge(relationship, gvnf));
+ assertFalse("generic-vnf has no edge uses", engine.tx().traversal().V(gvnf).both("uses").hasNext());
+ assertFalse("vnfc has no edge uses", engine.tx().traversal().V(vnfc).both("uses").hasNext());
+ assertTrue("generic-vnf has edge re-uses", engine.tx().traversal().V(gvnf).both("re-uses").hasNext());
+ assertTrue("vnfc has edge re-uses", engine.tx().traversal().V(vnfc).both("re-uses").hasNext());
+ assertTrue("generic-vnf has edge re-uses", engine.tx().traversal().V(gvnf).both("over-uses").hasNext());
+ assertTrue("vnfc has edge re-uses", engine.tx().traversal().V(vnfc).both("over-uses").hasNext());
+ assertEquals("Number of edges between vertexes is 2", Long.valueOf(2),
+ engine.tx().traversal().V(vnfc).both().count().next());
+ assertEquals("Number of edges between vertexes is 2", Long.valueOf(2),
+ engine.tx().traversal().V(gvnf).both().count().next());
+
+ }
+
+ @Test
+ public void deleteEdgeWithValidLabelWhenMultipleExistsTest() throws AAIException, UnsupportedEncodingException,
+ NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
+
+ DBSerializer localDbser = getDBSerializerWithSpecificEdgeRules();
+
+ engine.startTransaction();
+
+ Vertex gvnf = engine.tx().addVertex("aai-node-type", "generic-vnf", "vnf-id", "myvnf", "aai-uri",
+ "/network/generic-vnfs/generic-vnf/myvnf");
+ Vertex vnfc = engine.tx().addVertex("aai-node-type", "vnfc", "vnfc-name", "a-name", "aai-uri",
+ "/network/vnfcs/vnfc/a-name");
+ edgeSer.addEdge(graph.traversal(), gvnf, vnfc, "uses");
+ edgeSer.addEdge(graph.traversal(), gvnf, vnfc, "re-uses");
+ edgeSer.addEdge(graph.traversal(), gvnf, vnfc, "over-uses");
+
+ Introspector relData = loader.introspectorFromName("relationship-data");
+ relData.setValue("relationship-key", "vnfc.vnfc-name");
+ relData.setValue("relationship-value", "a-name");
+ Introspector relationship = loader.introspectorFromName("relationship");
+ relationship.setValue("related-to", "vnfc");
+ relationship.setValue("related-link", "/network/vnfcs/vnfc/a-name");
+ relationship.setValue("relationship-data", relData);
+ relationship.setValue("relationship-label", "re-uses");
+
+ assertTrue(localDbser.deleteEdge(relationship, gvnf));
+ assertTrue("generic-vnf has edge uses", engine.tx().traversal().V(gvnf).both("uses").hasNext());
+ assertTrue("vnfc has edge uses", engine.tx().traversal().V(vnfc).both("uses").hasNext());
+ assertFalse("generic-vnf has no edge re-uses", engine.tx().traversal().V(gvnf).both("re-uses").hasNext());
+ assertFalse("vnfc has no edge re-uses", engine.tx().traversal().V(vnfc).both("re-uses").hasNext());
+ assertTrue("generic-vnf has edge re-uses", engine.tx().traversal().V(gvnf).both("over-uses").hasNext());
+ assertTrue("vnfc has edge re-uses", engine.tx().traversal().V(vnfc).both("over-uses").hasNext());
+ assertEquals("Number of edges between vertexes is 2", Long.valueOf(2),
+ engine.tx().traversal().V(vnfc).both().count().next());
+ assertEquals("Number of edges between vertexes is 2", Long.valueOf(2),
+ engine.tx().traversal().V(gvnf).both().count().next());
+
+ }
+
+ @Test
+ public void deleteEdgeWithValidInvalidLabelWhenMultipleExistsTest()
+ throws AAIException, UnsupportedEncodingException, NoSuchFieldException, SecurityException,
+ IllegalArgumentException, IllegalAccessException {
+
+ DBSerializer localDbser = getDBSerializerWithSpecificEdgeRules();
+
+ engine.startTransaction();
+
+ Vertex gvnf = engine.tx().addVertex("aai-node-type", "generic-vnf", "vnf-id", "myvnf", "aai-uri",
+ "/network/generic-vnfs/generic-vnf/myvnf");
+ Vertex vnfc = engine.tx().addVertex("aai-node-type", "vnfc", "vnfc-name", "a-name", "aai-uri",
+ "/network/vnfcs/vnfc/a-name");
+ edgeSer.addEdge(graph.traversal(), gvnf, vnfc, "uses");
+ edgeSer.addEdge(graph.traversal(), gvnf, vnfc, "re-uses");
+ edgeSer.addEdge(graph.traversal(), gvnf, vnfc, "over-uses");
+
+ Introspector relData = loader.introspectorFromName("relationship-data");
+ relData.setValue("relationship-key", "vnfc.vnfc-name");
+ relData.setValue("relationship-value", "a-name");
+ Introspector relationship = loader.introspectorFromName("relationship");
+ relationship.setValue("related-to", "vnfc");
+ relationship.setValue("related-link", "/network/vnfcs/vnfc/a-name");
+ relationship.setValue("relationship-data", relData);
+ relationship.setValue("relationship-label", "NA");
+
+ thrown.expect(AAIException.class);
+ thrown.expectMessage("No rule found");
+ thrown.expectMessage("node type: generic-vnf, node type: vnfc, label: NA, type: COUSIN");
+ localDbser.deleteEdge(relationship, gvnf);
+ }
+
+ @Test
+ public void serializeToDbWithLabelTest() throws AAIException, UnsupportedEncodingException, NoSuchFieldException,
+ SecurityException, IllegalArgumentException, IllegalAccessException, URISyntaxException {
+
+ DBSerializer localDbser = getDBSerializerWithSpecificEdgeRules();
+
+ engine.startTransaction();
+
+ engine.tx().addVertex("aai-node-type", "vnfc", "vnfc-name", "a-name", "aai-uri", "/network/vnfcs/vnfc/a-name");
+
+ Introspector relationship = loader.introspectorFromName("relationship");
+ relationship.setValue("related-to", "vnfc");
+ relationship.setValue("related-link", "/network/vnfcs/vnfc/a-name");
+ relationship.setValue("relationship-label", "re-uses");
+ Introspector relationshipList = loader.introspectorFromName("relationship-list");
+ relationshipList.setValue("relationship", Collections.singletonList(relationship.getUnderlyingObject()));
+
+ Introspector gvnfObj = loader.introspectorFromName("generic-vnf");
+ Vertex gvnf = localDbser.createNewVertex(gvnfObj);
+ gvnfObj.setValue("relationship-list", relationshipList.getUnderlyingObject());
+ gvnfObj.setValue("vnf-id", "myvnf");
+
+ QueryParser uriQuery =
+ dbEngine.getQueryBuilder().createQueryFromURI(new URI("/network/generic-vnfs/generic-vnf/myvnf"));
+
+ localDbser.serializeToDb(gvnfObj, gvnf, uriQuery, null, "test");
+
+ assertTrue("vertex with vnf-id myvnf exists", engine.tx().traversal().V().has("vnf-id", "myvnf").hasNext());
+ assertTrue("vertex with vnfc-name a-name exists",
+ engine.tx().traversal().V().has("vnfc-name", "a-name").hasNext());
+ assertFalse("generic-vnf has no edge re-uses",
+ engine.tx().traversal().V().has("vnf-id", "myvnf").both("uses").hasNext());
+ assertFalse("vnfc has no edge re-uses",
+ engine.tx().traversal().V().has("vnfc-name", "a-name").both("uses").hasNext());
+ assertTrue("generic-vnf has edge re-uses",
+ engine.tx().traversal().V().has("vnf-id", "myvnf").both("re-uses").hasNext());
+ assertTrue("vnfc has edge re-uses",
+ engine.tx().traversal().V().has("vnfc-name", "a-name").both("re-uses").hasNext());
+ assertFalse("generic-vnf has no edge re-uses",
+ engine.tx().traversal().V().has("vnf-id", "myvnf").both("over-uses").hasNext());
+ assertFalse("vnfc has no edge re-uses",
+ engine.tx().traversal().V().has("vnfc-name", "a-name").both("over-uses").hasNext());
+ assertEquals("Number of edges between vertexes is 1", Long.valueOf(1),
+ engine.tx().traversal().V().has("vnfc-name", "a-name").both().count().next());
+ assertEquals("Number of edges between vertexes is 1", Long.valueOf(1),
+ engine.tx().traversal().V().has("vnf-id", "myvnf").both().count().next());
+
+ }
+
+ @Test
+ public void serializeToDbWithoutLabelTest() throws AAIException, UnsupportedEncodingException, NoSuchFieldException,
+ SecurityException, IllegalArgumentException, IllegalAccessException, URISyntaxException {
+
+ DBSerializer localDbser = getDBSerializerWithSpecificEdgeRules();
+
+ engine.startTransaction();
+
+ engine.tx().addVertex("aai-node-type", "vnfc", "vnfc-name", "a-name", "aai-uri", "/network/vnfcs/vnfc/a-name");
+
+ Introspector relationship = loader.introspectorFromName("relationship");
+ relationship.setValue("related-to", "vnfc");
+ relationship.setValue("related-link", "/network/vnfcs/vnfc/a-name");
+
+ Introspector relationshipList = loader.introspectorFromName("relationship-list");
+ relationshipList.setValue("relationship", Collections.singletonList(relationship.getUnderlyingObject()));
+
+ Introspector gvnfObj = loader.introspectorFromName("generic-vnf");
+ Vertex gvnf = localDbser.createNewVertex(gvnfObj);
+ gvnfObj.setValue("relationship-list", relationshipList.getUnderlyingObject());
+ gvnfObj.setValue("vnf-id", "myvnf");
+
+ QueryParser uriQuery =
+ dbEngine.getQueryBuilder().createQueryFromURI(new URI("/network/generic-vnfs/generic-vnf/myvnf"));
+
+ localDbser.serializeToDb(gvnfObj, gvnf, uriQuery, null, "test");
+
+ assertTrue("vertex with vnf-id myvnf exists", engine.tx().traversal().V().has("vnf-id", "myvnf").hasNext());
+ assertTrue("vertex with vnfc-name a-name exists",
+ engine.tx().traversal().V().has("vnfc-name", "a-name").hasNext());
+ assertTrue("generic-vnf has edge uses",
+ engine.tx().traversal().V().has("vnf-id", "myvnf").both("uses").hasNext());
+ assertTrue("vnfc has edge uses", engine.tx().traversal().V().has("vnfc-name", "a-name").both("uses").hasNext());
+ assertFalse("generic-vnf has no edge re-uses",
+ engine.tx().traversal().V().has("vnf-id", "myvnf").both("re-uses").hasNext());
+ assertFalse("vnfc has no edge re-uses",
+ engine.tx().traversal().V().has("vnfc-name", "a-name").both("re-uses").hasNext());
+ assertFalse("generic-vnf has no edge over-uses",
+ engine.tx().traversal().V().has("vnf-id", "myvnf").both("over-uses").hasNext());
+ assertFalse("vnfc has no edge over-uses",
+ engine.tx().traversal().V().has("vnfc-name", "a-name").both("over-uses").hasNext());
+ assertEquals("Number of edges between vertexes is 1", Long.valueOf(1),
+ engine.tx().traversal().V().has("vnfc-name", "a-name").both().count().next());
+ assertEquals("Number of edges between vertexes is 1", Long.valueOf(1),
+ engine.tx().traversal().V().has("vnf-id", "myvnf").both().count().next());
+
+ }
+
+ @Test
+ public void serializeToDbWithInvalidLabelTest()
+ throws AAIException, UnsupportedEncodingException, NoSuchFieldException, SecurityException,
+ IllegalArgumentException, IllegalAccessException, URISyntaxException {
+
+ DBSerializer localDbser = getDBSerializerWithSpecificEdgeRules();
+
+ engine.startTransaction();
+
+ engine.tx().addVertex("aai-node-type", "vnfc", "vnfc-name", "a-name", "aai-uri", "/network/vnfcs/vnfc/a-name");
+
+ Introspector relationship = loader.introspectorFromName("relationship");
+ relationship.setValue("related-to", "vnfc");
+ relationship.setValue("related-link", "/network/vnfcs/vnfc/a-name");
+ relationship.setValue("relationship-label", "NA");
+ Introspector relationshipList = loader.introspectorFromName("relationship-list");
+ relationshipList.setValue("relationship", Collections.singletonList(relationship.getUnderlyingObject()));
+
+ Introspector gvnfObj = loader.introspectorFromName("generic-vnf");
+ Vertex gvnf = localDbser.createNewVertex(gvnfObj);
+ gvnfObj.setValue("relationship-list", relationshipList.getUnderlyingObject());
+ gvnfObj.setValue("vnf-id", "myvnf");
+
+ QueryParser uriQuery =
+ dbEngine.getQueryBuilder().createQueryFromURI(new URI("/network/generic-vnfs/generic-vnf/myvnf"));
+
+ thrown.expect(AAIException.class);
+ thrown.expectMessage("No EdgeRule found for passed nodeTypes: generic-vnf, vnfc with label NA.");
+ localDbser.serializeToDb(gvnfObj, gvnf, uriQuery, null, "test");
+
+ }
+
+ @Test
+ public void serializeToDbWithLabelAndEdgeExistsTest()
+ throws AAIException, UnsupportedEncodingException, NoSuchFieldException, SecurityException,
+ IllegalArgumentException, IllegalAccessException, URISyntaxException {
+
+ DBSerializer localDbser = getDBSerializerWithSpecificEdgeRules();
+
+ engine.startTransaction();
+ engine.tx().addVertex("aai-node-type", "vnfc", "vnfc-name", "a-name", "aai-uri", "/network/vnfcs/vnfc/a-name");
+
+ Introspector relationship;
+ Introspector relationshipList;
+ List<Object> relList = new ArrayList<>();
+
+ // create generic-vnf
+ Introspector gvnfObj = loader.introspectorFromName("generic-vnf");
+ Vertex gvnf = localDbser.createNewVertex(gvnfObj);
+ gvnfObj.setValue("vnf-id", "myvnf");
+ QueryParser uriQuery =
+ dbEngine.getQueryBuilder().createQueryFromURI(new URI("/network/generic-vnfs/generic-vnf/myvnf"));
+
+ // create relationship to vnfc
+ relationship = loader.introspectorFromName("relationship");
+ relationship.setValue("related-to", "vnfc");
+ relationship.setValue("related-link", "/network/vnfcs/vnfc/a-name");
+ relList.add(relationship.getUnderlyingObject());
+ relationshipList = loader.introspectorFromName("relationship-list");
+ relationshipList.setValue("relationship", relList);
+ gvnfObj.setValue("relationship-list", relationshipList.getUnderlyingObject());
+
+ // add gvnf to graph
+ localDbser.serializeToDb(gvnfObj, gvnf, uriQuery, null, "test");
+
+ // add second relationship
+ relationship = loader.introspectorFromName("relationship");
+ relationship.setValue("related-to", "vnfc");
+ relationship.setValue("related-link", "/network/vnfcs/vnfc/a-name");
+ relationship.setValue("relationship-label", "re-uses");
+ relList.add(relationship.getUnderlyingObject());
+ relationshipList = loader.introspectorFromName("relationship-list");
+ relationshipList.setValue("relationship", relList);
+ gvnfObj.setValue("relationship-list", relationshipList.getUnderlyingObject());
+
+ localDbser.serializeToDb(gvnfObj, gvnf, uriQuery, null, "test");
+
+ assertTrue("vertex with vnf-id myvnf exists", engine.tx().traversal().V().has("vnf-id", "myvnf").hasNext());
+ assertTrue("vertex with vnfc-name a-name exists",
+ engine.tx().traversal().V().has("vnfc-name", "a-name").hasNext());
+ assertTrue("generic-vnf has edge uses",
+ engine.tx().traversal().V().has("vnf-id", "myvnf").both("uses").hasNext());
+ assertTrue("vnfc has edge uses",
+ engine.tx().traversal().V().has("vnfc-name", "a-name").both("uses").hasNext());
+ assertTrue("generic-vnf has edge re-uses",
+ engine.tx().traversal().V().has("vnf-id", "myvnf").both("re-uses").hasNext());
+ assertTrue("vnfc has edge re-uses",
+ engine.tx().traversal().V().has("vnfc-name", "a-name").both("re-uses").hasNext());
+ assertFalse("generic-vnf has no edge over-uses",
+ engine.tx().traversal().V().has("vnf-id", "myvnf").both("over-uses").hasNext());
+ assertFalse("vnfc has no edge over-uses",
+ engine.tx().traversal().V().has("vnfc-name", "a-name").both("over-uses").hasNext());
+ assertEquals("Number of edges between vertexes is 2", Long.valueOf(2),
+ engine.tx().traversal().V().has("vnfc-name", "a-name").both().count().next());
+ assertEquals("Number of edges between vertexes is 2", Long.valueOf(2),
+ engine.tx().traversal().V().has("vnf-id", "myvnf").both().count().next());
+
+ }
+
+ @Test
+ public void serializeToDbWithLabelDroppingRelationshipTest()
+ throws AAIException, UnsupportedEncodingException, NoSuchFieldException, SecurityException,
+ IllegalArgumentException, IllegalAccessException, URISyntaxException {
+
+ DBSerializer localDbser = getDBSerializerWithSpecificEdgeRules();
+
+ engine.startTransaction();
+ engine.tx().addVertex("aai-node-type", "vnfc", "vnfc-name", "a-name", "aai-uri", "/network/vnfcs/vnfc/a-name");
+
+ Introspector relationship;
+ Introspector relationshipList;
+ List<Object> relList = new ArrayList<>();
+
+ // create generic-vnf
+ Introspector gvnfObj = loader.introspectorFromName("generic-vnf");
+ Vertex gvnf = localDbser.createNewVertex(gvnfObj);
+ gvnfObj.setValue("vnf-id", "myvnf");
+ QueryParser uriQuery =
+ dbEngine.getQueryBuilder().createQueryFromURI(new URI("/network/generic-vnfs/generic-vnf/myvnf"));
+
+ // create relationship to vnfc
+ relationship = loader.introspectorFromName("relationship");
+ relationship.setValue("related-to", "vnfc");
+ relationship.setValue("related-link", "/network/vnfcs/vnfc/a-name");
+ relList.add(relationship.getUnderlyingObject());
+ // add second relationship
+ relationship = loader.introspectorFromName("relationship");
+ relationship.setValue("related-to", "vnfc");
+ relationship.setValue("related-link", "/network/vnfcs/vnfc/a-name");
+ relationship.setValue("relationship-label", "re-uses");
+ relList.add(relationship.getUnderlyingObject());
+ relationshipList = loader.introspectorFromName("relationship-list");
+ relationshipList.setValue("relationship", relList);
+ gvnfObj.setValue("relationship-list", relationshipList.getUnderlyingObject());
+
+ // add gvnf to graph
+ localDbser.serializeToDb(gvnfObj, gvnf, uriQuery, null, "test");
+
+ // drop second relationship
+ relList.remove(1);
+ relationshipList = loader.introspectorFromName("relationship-list");
+ relationshipList.setValue("relationship", relList);
+ gvnfObj.setValue("relationship-list", relationshipList.getUnderlyingObject());
+
+ localDbser.serializeToDb(gvnfObj, gvnf, uriQuery, null, "test");
+
+ assertTrue("vertex with vnf-id myvnf exists", engine.tx().traversal().V().has("vnf-id", "myvnf").hasNext());
+ assertTrue("vertex with vnfc-name a-name exists",
+ engine.tx().traversal().V().has("vnfc-name", "a-name").hasNext());
+ assertTrue("generic-vnf has edge uses",
+ engine.tx().traversal().V().has("vnf-id", "myvnf").both("uses").hasNext());
+ assertTrue("vnfc has edge uses",
+ engine.tx().traversal().V().has("vnfc-name", "a-name").both("uses").hasNext());
+ assertFalse("generic-vnf no longer has edge re-uses",
+ engine.tx().traversal().V().has("vnf-id", "myvnf").both("re-uses").hasNext());
+ assertFalse("vnfc no longer has edge re-uses",
+ engine.tx().traversal().V().has("vnfc-name", "a-name").both("re-uses").hasNext());
+ assertFalse("generic-vnf has no edge over-uses",
+ engine.tx().traversal().V().has("vnf-id", "myvnf").both("over-uses").hasNext());
+ assertFalse("vnfc has no edge over-uses",
+ engine.tx().traversal().V().has("vnfc-name", "a-name").both("over-uses").hasNext());
+ assertEquals("Number of edges between vertexes is 1", Long.valueOf(1),
+ engine.tx().traversal().V().has("vnfc-name", "a-name").both().count().next());
+ assertEquals("Number of edges between vertexes is 1", Long.valueOf(1),
+ engine.tx().traversal().V().has("vnf-id", "myvnf").both().count().next());
+
+ }
+
+ private DBSerializer getDBSerializerWithSpecificEdgeRules()
+ throws NoSuchFieldException, AAIException, IllegalAccessException {
+
+ DBSerializer localDbser = new DBSerializer(version, engine, introspectorFactoryType, "AAI-TEST");
+ return localDbser;
+ }
}
diff --git a/aai-core/src/test/java/org/onap/aai/serialization/db/EdgePropertyMapTest.java b/aai-core/src/test/java/org/onap/aai/serialization/db/EdgePropertyMapTest.java
index 2f3854e4..91097826 100644
--- a/aai-core/src/test/java/org/onap/aai/serialization/db/EdgePropertyMapTest.java
+++ b/aai-core/src/test/java/org/onap/aai/serialization/db/EdgePropertyMapTest.java
@@ -17,26 +17,27 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.serialization.db;
-import org.junit.Test;
+import static org.junit.Assert.assertEquals;
import java.util.Map;
-import static org.junit.Assert.assertEquals;
+import org.junit.Test;
public class EdgePropertyMapTest {
- @Test
- public void run() {
- Map<String, String> map = new EdgePropertyMap<>();
- map.put("direction", "OUT");
- map.put("test", "hello");
- map.put("isParent", "${direction}");
- map.put("SVC-INFRA", "!${direction}");
-
- assertEquals("normal retrieval", "hello", map.get("test"));
- assertEquals("variable retrieval", "OUT", map.get("isParent"));
- assertEquals("negate variable retrieval", "IN", map.get("SVC-INFRA"));
- }
+ @Test
+ public void run() {
+ Map<String, String> map = new EdgePropertyMap<>();
+ map.put("direction", "OUT");
+ map.put("test", "hello");
+ map.put("isParent", "${direction}");
+ map.put("SVC-INFRA", "!${direction}");
+
+ assertEquals("normal retrieval", "hello", map.get("test"));
+ assertEquals("variable retrieval", "OUT", map.get("isParent"));
+ assertEquals("negate variable retrieval", "IN", map.get("SVC-INFRA"));
+ }
}
diff --git a/aai-core/src/test/java/org/onap/aai/serialization/db/EdgeRulesTest.java b/aai-core/src/test/java/org/onap/aai/serialization/db/EdgeRulesTest.java
index 0bb07895..69206a40 100644
--- a/aai-core/src/test/java/org/onap/aai/serialization/db/EdgeRulesTest.java
+++ b/aai-core/src/test/java/org/onap/aai/serialization/db/EdgeRulesTest.java
@@ -19,10 +19,17 @@
*
* ECOMP is a trademark and service mark of AT&T Intellectual Property.
*/
+
package org.onap.aai.serialization.db;
+import static junit.framework.TestCase.fail;
+import static org.junit.Assert.assertEquals;
import com.google.common.collect.Multimap;
+
+import java.util.*;
+import java.util.stream.Collectors;
+
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.junit.Rule;
import org.junit.Test;
@@ -37,64 +44,49 @@ import org.onap.aai.edges.exceptions.EdgeRuleNotFoundException;
import org.onap.aai.setup.SchemaVersion;
import org.springframework.beans.factory.annotation.Autowired;
-import java.util.*;
-import java.util.stream.Collectors;
-
-import static junit.framework.TestCase.fail;
-import static org.junit.Assert.assertEquals;
-
public class EdgeRulesTest extends AAISetup {
- //set thrown.expect to whatever a specific test needs
- //this establishes a default of expecting no exceptions to be thrown
- @Rule
- public ExpectedException thrown = ExpectedException.none();
+ // set thrown.expect to whatever a specific test needs
+ // this establishes a default of expecting no exceptions to be thrown
+ @Rule
+ public ExpectedException thrown = ExpectedException.none();
- @Autowired
- private EdgeIngestor edgeIngestor;
+ @Autowired
+ private EdgeIngestor edgeIngestor;
- @Test
- public void verifyOutDirection() throws EdgeRuleNotFoundException, AmbiguousRuleChoiceException {
+ @Test
+ public void verifyOutDirection() throws EdgeRuleNotFoundException, AmbiguousRuleChoiceException {
- EdgeRuleQuery ruleQuery = new EdgeRuleQuery
- .Builder("cloud-region", "flavor")
- .edgeType(EdgeType.TREE)
- .build();
+ EdgeRuleQuery ruleQuery = new EdgeRuleQuery.Builder("cloud-region", "flavor").edgeType(EdgeType.TREE).build();
- EdgeRule rule = edgeIngestor.getRule(ruleQuery);
+ EdgeRule rule = edgeIngestor.getRule(ruleQuery);
- assertEquals("out direction", rule.getDirection(), Direction.IN);
- }
+ assertEquals("out direction", rule.getDirection(), Direction.IN);
+ }
- @Test
- public void verifyOutFlippedDirection() throws EdgeRuleNotFoundException, AmbiguousRuleChoiceException {
+ @Test
+ public void verifyOutFlippedDirection() throws EdgeRuleNotFoundException, AmbiguousRuleChoiceException {
- EdgeRuleQuery ruleQuery = new EdgeRuleQuery
- .Builder("flavor", "cloud-region")
- .edgeType(EdgeType.TREE)
- .build();
+ EdgeRuleQuery ruleQuery = new EdgeRuleQuery.Builder("flavor", "cloud-region").edgeType(EdgeType.TREE).build();
EdgeRule rule = edgeIngestor.getRule(ruleQuery);
- assertEquals("in direction", rule.getDirection(), Direction.OUT);
- }
+ assertEquals("in direction", rule.getDirection(), Direction.OUT);
+ }
- @Test
- public void verifyMultipleGet() throws EdgeRuleNotFoundException {
+ @Test
+ public void verifyMultipleGet() throws EdgeRuleNotFoundException {
- EdgeRuleQuery ruleQuery = new EdgeRuleQuery
- .Builder("model-element", "model-ver")
- .edgeType(EdgeType.TREE)
- .build();
+ EdgeRuleQuery ruleQuery =
+ new EdgeRuleQuery.Builder("model-element", "model-ver").edgeType(EdgeType.TREE).build();
- Multimap<String, EdgeRule> ruleMap = edgeIngestor.getRules(ruleQuery);
+ Multimap<String, EdgeRule> ruleMap = edgeIngestor.getRules(ruleQuery);
for (EdgeRule edgeRule : ruleMap.get("model|model-ver")) {
- assertEquals("has isA rule", "org.onap.relationships.inventory.IsA",
- edgeRule.getLabel());
+ assertEquals("has isA rule", "org.onap.relationships.inventory.IsA", edgeRule.getLabel());
}
- }
+ }
@Test
public void verifyAllRules() throws EdgeRuleNotFoundException {
@@ -105,29 +97,30 @@ public class EdgeRulesTest extends AAISetup {
for (SchemaVersion v : schemaVersions.getVersions()) {
Multimap<String, EdgeRule> all = edgeIngestor.getAllRules(schemaVersions.getDefaultVersion());
- //this part verifies the default properties
+ // this part verifies the default properties
// 1) can have only at most 1 containment edge between same node type pair
// 2) if there is at least 1 cousin edge, there must be exactly 1 cousin edge with default=true
for (String key : all.keySet()) {
Collection<EdgeRule> edgeRuleCollection = all.get(key);
- boolean foundContainment = false; //can have at most 1 containment rel btwn same pair of node types
+ boolean foundContainment = false; // can have at most 1 containment rel btwn same pair of node types
boolean foundCousin = false;
- boolean cousinDefault = false; //if there is a cousin edge there must be at least 1 default cousin defined
- Set<String> labels = new HashSet<>(); //all edges between the same pair must have different labels
+ boolean cousinDefault = false; // if there is a cousin edge there must be at least 1 default cousin
+ // defined
+ Set<String> labels = new HashSet<>(); // all edges between the same pair must have different labels
int cousinCount = 0;
- for(EdgeRule rule: edgeRuleCollection){
+ for (EdgeRule rule : edgeRuleCollection) {
EdgeRule match = rule;
- //check containment
+ // check containment
if (!("NONE".equals(match.getContains()))) {
if (foundContainment) {
fail("more than one containment edge defined for " + v.toString() + " " + key);
} else {
foundContainment = true;
}
- } else { //check cousin stuff
+ } else { // check cousin stuff
foundCousin = true;
cousinCount++;
if (match.isDefault()) {
@@ -139,7 +132,7 @@ public class EdgeRulesTest extends AAISetup {
}
}
- //check labels
+ // check labels
String label = match.getLabel();
if (labels.contains(label)) {
fail("same label found for multiple edges for " + v.toString() + " " + key);
@@ -148,7 +141,8 @@ public class EdgeRulesTest extends AAISetup {
}
}
if (foundCousin && !cousinDefault && cousinCount > 1) {
- fail("there is at least one cousin edge but none are designated the default for " + v.toString() + " " + key);
+ fail("there is at least one cousin edge but none are designated the default for " + v.toString()
+ + " " + key);
}
}
}
diff --git a/aai-core/src/test/java/org/onap/aai/serialization/db/EdgeSerializerTest.java b/aai-core/src/test/java/org/onap/aai/serialization/db/EdgeSerializerTest.java
index 0cba621c..0c8bf8b5 100644
--- a/aai-core/src/test/java/org/onap/aai/serialization/db/EdgeSerializerTest.java
+++ b/aai-core/src/test/java/org/onap/aai/serialization/db/EdgeSerializerTest.java
@@ -17,8 +17,12 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.serialization.db;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Graph;
@@ -34,77 +38,77 @@ import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.EdgeMultiplicityException;
import org.springframework.beans.factory.annotation.Autowired;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
public class EdgeSerializerTest extends AAISetup {
- @Autowired
- EdgeSerializer rules;
-
- @Rule
- public ExpectedException thrown = ExpectedException.none();
-
- @Test
- public void addTreeEdgeTest() throws AAIException {
- Graph graph = TinkerGraph.open();
- Vertex v1 = graph.addVertex(T.id, "1", "aai-node-type", "cloud-region");
- Vertex v2 = graph.addVertex(T.id, "10", "aai-node-type", "tenant");
- GraphTraversalSource g = graph.traversal();
- rules.addTreeEdge(g, v1, v2);
- assertEquals(true, g.V(v1).in("org.onap.relationships.inventory.BelongsTo").has("aai-node-type", "tenant").hasNext());
+ @Autowired
+ EdgeSerializer rules;
+
+ @Rule
+ public ExpectedException thrown = ExpectedException.none();
+
+ @Test
+ public void addTreeEdgeTest() throws AAIException {
+ Graph graph = TinkerGraph.open();
+ Vertex v1 = graph.addVertex(T.id, "1", "aai-node-type", "cloud-region");
+ Vertex v2 = graph.addVertex(T.id, "10", "aai-node-type", "tenant");
+ GraphTraversalSource g = graph.traversal();
+ rules.addTreeEdge(g, v1, v2);
+ assertEquals(true,
+ g.V(v1).in("org.onap.relationships.inventory.BelongsTo").has("aai-node-type", "tenant").hasNext());
+
+ Vertex v3 = graph.addVertex(T.id, "2", "aai-node-type", "cloud-region");
+ assertEquals(null, rules.addTreeEdgeIfPossible(g, v3, v2));
+ }
- Vertex v3 = graph.addVertex(T.id, "2", "aai-node-type", "cloud-region");
- assertEquals(null, rules.addTreeEdgeIfPossible(g, v3, v2));
- }
+ @Test
+ public void addCousinEdgeTest() throws AAIException {
+ Graph graph = TinkerGraph.open();
+ Vertex v1 = graph.addVertex(T.id, "1", "aai-node-type", "flavor");
+ Vertex v2 = graph.addVertex(T.id, "10", "aai-node-type", "vserver");
+ GraphTraversalSource g = graph.traversal();
+ rules.addEdge(g, v1, v2);
+ assertEquals(true,
+ g.V(v2).out("org.onap.relationships.inventory.Uses").has("aai-node-type", "flavor").hasNext());
- @Test
- public void addCousinEdgeTest() throws AAIException {
- Graph graph = TinkerGraph.open();
- Vertex v1 = graph.addVertex(T.id, "1", "aai-node-type", "flavor");
- Vertex v2 = graph.addVertex(T.id, "10", "aai-node-type", "vserver");
- GraphTraversalSource g = graph.traversal();
- rules.addEdge(g, v1, v2);
- assertEquals(true, g.V(v2).out("org.onap.relationships.inventory.Uses").has("aai-node-type", "flavor").hasNext());
+ Vertex v3 = graph.addVertex(T.id, "2", "aai-node-type", "flavor");
+ assertEquals(null, rules.addEdgeIfPossible(g, v3, v2));
+ }
- Vertex v3 = graph.addVertex(T.id, "2", "aai-node-type", "flavor");
- assertEquals(null, rules.addEdgeIfPossible(g, v3, v2));
- }
+ @Test
+ public void multiplicityViolationTest() throws AAIException {
+ thrown.expect(EdgeMultiplicityException.class);
+ thrown.expectMessage(
+ "multiplicity rule violated: only one edge can exist with label: org.onap.relationships.inventory.Uses between vf-module and volume-group");
- @Test
- public void multiplicityViolationTest() throws AAIException {
- thrown.expect(EdgeMultiplicityException.class);
- thrown.expectMessage("multiplicity rule violated: only one edge can exist with label: org.onap.relationships.inventory.Uses between vf-module and volume-group");
+ Graph graph = TinkerGraph.open();
+ Vertex v1 = graph.addVertex(T.id, "1", "aai-node-type", "vf-module");
+ Vertex v2 = graph.addVertex(T.id, "10", "aai-node-type", "volume-group");
+ GraphTraversalSource g = graph.traversal();
- Graph graph = TinkerGraph.open();
- Vertex v1 = graph.addVertex(T.id, "1", "aai-node-type", "vf-module");
- Vertex v2 = graph.addVertex(T.id, "10", "aai-node-type", "volume-group");
- GraphTraversalSource g = graph.traversal();
+ rules.addEdge(g, v2, v1);
+ Vertex v3 = graph.addVertex(T.id, "3", "aai-node-type", "vf-module");
+ rules.addEdge(g, v2, v3);
+ }
- rules.addEdge(g, v2, v1);
- Vertex v3 = graph.addVertex(T.id, "3", "aai-node-type", "vf-module");
- rules.addEdge(g, v2, v3);
- }
-
- @Test
- public void addEdgeVerifyAAIUUIDCousinTest() throws AAIException {
- Graph graph = TinkerGraph.open();
- Vertex v1 = graph.addVertex(T.id, "1", "aai-node-type", "flavor");
- Vertex v2 = graph.addVertex(T.id, "10", "aai-node-type", "vserver");
- GraphTraversalSource g = graph.traversal();
- Edge e = rules.addEdge(g, v1, v2);
- assertTrue(e.property(AAIProperties.AAI_UUID).isPresent());
- //assertTrue(e.property(AAIProperties.AAI_UUID).value().toString().matches("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"));
- }
+ @Test
+ public void addEdgeVerifyAAIUUIDCousinTest() throws AAIException {
+ Graph graph = TinkerGraph.open();
+ Vertex v1 = graph.addVertex(T.id, "1", "aai-node-type", "flavor");
+ Vertex v2 = graph.addVertex(T.id, "10", "aai-node-type", "vserver");
+ GraphTraversalSource g = graph.traversal();
+ Edge e = rules.addEdge(g, v1, v2);
+ assertTrue(e.property(AAIProperties.AAI_UUID).isPresent());
+ // assertTrue(e.property(AAIProperties.AAI_UUID).value().toString().matches("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"));
+ }
- @Test
- public void addEdgeVerifyAAIUUIDTreeTest() throws AAIException {
- Graph graph = TinkerGraph.open();
- Vertex v1 = graph.addVertex(T.id, "1", "aai-node-type", "tenant");
- Vertex v2 = graph.addVertex(T.id, "10", "aai-node-type", "vserver");
- GraphTraversalSource g = graph.traversal();
- Edge e = rules.addTreeEdge(g, v1, v2);
- assertTrue(e.property(AAIProperties.AAI_UUID).isPresent());
- //assertTrue(e.property(AAIProperties.AAI_UUID).value().toString().matches("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"));
- }
+ @Test
+ public void addEdgeVerifyAAIUUIDTreeTest() throws AAIException {
+ Graph graph = TinkerGraph.open();
+ Vertex v1 = graph.addVertex(T.id, "1", "aai-node-type", "tenant");
+ Vertex v2 = graph.addVertex(T.id, "10", "aai-node-type", "vserver");
+ GraphTraversalSource g = graph.traversal();
+ Edge e = rules.addTreeEdge(g, v1, v2);
+ assertTrue(e.property(AAIProperties.AAI_UUID).isPresent());
+ // assertTrue(e.property(AAIProperties.AAI_UUID).value().toString().matches("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"));
+ }
-} \ No newline at end of file
+}
diff --git a/aai-core/src/test/java/org/onap/aai/serialization/engines/query/GraphTraversalQueryEngineTest.java b/aai-core/src/test/java/org/onap/aai/serialization/engines/query/GraphTraversalQueryEngineTest.java
index b9431217..5201cc5e 100644
--- a/aai-core/src/test/java/org/onap/aai/serialization/engines/query/GraphTraversalQueryEngineTest.java
+++ b/aai-core/src/test/java/org/onap/aai/serialization/engines/query/GraphTraversalQueryEngineTest.java
@@ -17,9 +17,20 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.serialization.engines.query;
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
+import static org.onap.aai.edges.enums.EdgeField.CONTAINS;
+
import com.jayway.jsonpath.JsonPath;
+
+import java.io.InputStream;
+import java.util.*;
+
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.process.traversal.step.util.Tree;
import org.apache.tinkerpop.gremlin.structure.*;
@@ -35,72 +46,65 @@ import org.onap.aai.serialization.db.EdgeSerializer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.DirtiesContext;
-import java.io.InputStream;
-import java.util.*;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
-import static org.onap.aai.edges.enums.EdgeField.CONTAINS;
-
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
public class GraphTraversalQueryEngineTest extends AAISetup {
- @Autowired
- EdgeSerializer edgeSer;
+ @Autowired
+ EdgeSerializer edgeSer;
- @Test
- public void testFindParents() throws AAIException {
- //setup
- Graph graph = TinkerGraph.open();
+ @Test
+ public void testFindParents() throws AAIException {
+ // setup
+ Graph graph = TinkerGraph.open();
- Vertex cloudreg = graph.addVertex(T.id, "00", "aai-node-type", "cloud-region");
- Vertex tenant = graph.addVertex(T.id, "10", "aai-node-type", "tenant");
- Vertex vserver = graph.addVertex(T.id, "20", "aai-node-type", "vserver");
+ Vertex cloudreg = graph.addVertex(T.id, "00", "aai-node-type", "cloud-region");
+ Vertex tenant = graph.addVertex(T.id, "10", "aai-node-type", "tenant");
+ Vertex vserver = graph.addVertex(T.id, "20", "aai-node-type", "vserver");
- GraphTraversalSource g = graph.traversal();
+ GraphTraversalSource g = graph.traversal();
- edgeSer.addTreeEdge(g, cloudreg, tenant);
- edgeSer.addTreeEdge(g, tenant, vserver);
+ edgeSer.addTreeEdge(g, cloudreg, tenant);
+ edgeSer.addTreeEdge(g, tenant, vserver);
- //expect start vertex back plus any parents
- List<Vertex> crExpected = new ArrayList<>(Arrays.asList(cloudreg)); //no parents
- List<Vertex> tenExpected = new ArrayList<>(Arrays.asList(tenant, cloudreg)); //only has the immediate parent
- List<Vertex> vsExpected = new ArrayList<>(Arrays.asList(vserver, tenant, cloudreg)); //parent & grandparent
+ // expect start vertex back plus any parents
+ List<Vertex> crExpected = new ArrayList<>(Arrays.asList(cloudreg)); // no parents
+ List<Vertex> tenExpected = new ArrayList<>(Arrays.asList(tenant, cloudreg)); // only has the immediate parent
+ List<Vertex> vsExpected = new ArrayList<>(Arrays.asList(vserver, tenant, cloudreg)); // parent & grandparent
- GraphTraversalQueryEngine engine = new GraphTraversalQueryEngine(g);
+ GraphTraversalQueryEngine engine = new GraphTraversalQueryEngine(g);
- //test
- List<Vertex> crRes = engine.findParents(cloudreg);
- assertTrue(crRes.containsAll(crExpected) && crExpected.containsAll(crRes));
+ // test
+ List<Vertex> crRes = engine.findParents(cloudreg);
+ assertTrue(crRes.containsAll(crExpected) && crExpected.containsAll(crRes));
- List<Vertex> tenRes = engine.findParents(tenant);
- assertTrue(tenRes.containsAll(tenExpected) && tenExpected.containsAll(tenRes));
+ List<Vertex> tenRes = engine.findParents(tenant);
+ assertTrue(tenRes.containsAll(tenExpected) && tenExpected.containsAll(tenRes));
- List<Vertex> vsRes = engine.findParents(vserver);
- assertTrue(vsRes.containsAll(vsExpected) && vsExpected.containsAll(vsRes));
- //verify expected ordering - start, parent, grandparent
- assertTrue(vsRes.get(0).equals(vserver));
- assertTrue(vsRes.get(1).equals(tenant));
- assertTrue(vsRes.get(2).equals(cloudreg));
- }
+ List<Vertex> vsRes = engine.findParents(vserver);
+ assertTrue(vsRes.containsAll(vsExpected) && vsExpected.containsAll(vsRes));
+ // verify expected ordering - start, parent, grandparent
+ assertTrue(vsRes.get(0).equals(vserver));
+ assertTrue(vsRes.get(1).equals(tenant));
+ assertTrue(vsRes.get(2).equals(cloudreg));
+ }
- @Test
- public void testFindAllParentsGivenAaiUris(){
+ @Test
+ public void testFindAllParentsGivenAaiUris() {
- //setup
+ // setup
Graph graph = TinkerGraph.open();
- Vertex cloudreg = graph.addVertex(T.id, "00", "aai-node-type", "cloud-region", "aai-uri", "/cloud-infrastructure/cloud-regions/cloud-region/testowner/testid");
- Vertex tenant = graph.addVertex(T.id, "10", "aai-node-type", "tenant", "aai-uri", "/cloud-infrastructure/cloud-regions/cloud-region/testowner/testid/tenants/tenant/testTenant1");
- Vertex vserver = graph.addVertex(T.id, "20", "aai-node-type", "vserver", "aai-uri", "/cloud-infrastructure/cloud-regions/cloud-region/testowner/testid/tenants/tenant/testTenant1/vservers/vserver/testVserver1");
+ Vertex cloudreg = graph.addVertex(T.id, "00", "aai-node-type", "cloud-region", "aai-uri",
+ "/cloud-infrastructure/cloud-regions/cloud-region/testowner/testid");
+ Vertex tenant = graph.addVertex(T.id, "10", "aai-node-type", "tenant", "aai-uri",
+ "/cloud-infrastructure/cloud-regions/cloud-region/testowner/testid/tenants/tenant/testTenant1");
+ Vertex vserver = graph.addVertex(T.id, "20", "aai-node-type", "vserver", "aai-uri",
+ "/cloud-infrastructure/cloud-regions/cloud-region/testowner/testid/tenants/tenant/testTenant1/vservers/vserver/testVserver1");
- String [] uris = new String[]{
- "/cloud-infrastructure/cloud-regions/cloud-region/testowner/testid/tenants/tenant/testTenant1",
- "/cloud-infrastructure/cloud-regions/cloud-region/testowner/testid/tenants/tenant/testTenant1/vservers/vserver/testVserver1",
- "/cloud-infrastructure/cloud-regions/cloud-region/testowner/testid"
- };
+ String[] uris = new String[] {
+ "/cloud-infrastructure/cloud-regions/cloud-region/testowner/testid/tenants/tenant/testTenant1",
+ "/cloud-infrastructure/cloud-regions/cloud-region/testowner/testid/tenants/tenant/testTenant1/vservers/vserver/testVserver1",
+ "/cloud-infrastructure/cloud-regions/cloud-region/testowner/testid"};
GraphTraversalSource g = graph.traversal();
GraphTraversalQueryEngine queryEngine = new GraphTraversalQueryEngine(g);
@@ -112,266 +116,267 @@ public class GraphTraversalQueryEngineTest extends AAISetup {
assertThat("Expected the element back to be cloud region", vertices.get(2), is(cloudreg));
}
- @Test
- public void testFindAllChildren() throws AAIException {
- //setup
- Graph graph = TinkerGraph.open();
+ @Test
+ public void testFindAllChildren() throws AAIException {
+ // setup
+ Graph graph = TinkerGraph.open();
+
+ Vertex cloudreg = graph.addVertex(T.id, "00", "aai-node-type", "cloud-region");
+ Vertex tenant = graph.addVertex(T.id, "10", "aai-node-type", "tenant");
+ Vertex vserver = graph.addVertex(T.id, "20", "aai-node-type", "vserver");
+ Vertex vserver2 = graph.addVertex(T.id, "21", "aai-node-type", "vserver");
+ Vertex oam = graph.addVertex(T.id, "30", "aai-node-type", "oam-network");
+
+ GraphTraversalSource g = graph.traversal();
+
+ edgeSer.addTreeEdge(g, cloudreg, tenant);
+ edgeSer.addTreeEdge(g, tenant, vserver);
+ edgeSer.addTreeEdge(g, tenant, vserver2);
+ edgeSer.addTreeEdge(g, cloudreg, oam);
+
+ List<Vertex> crExpected = new ArrayList<>(Arrays.asList(cloudreg, tenant, vserver, vserver2, oam));
+ List<Vertex> vsExpected = new ArrayList<>(Arrays.asList(vserver));
+
+ GraphTraversalQueryEngine engine = new GraphTraversalQueryEngine(g);
+
+ // test
+ List<Vertex> crRes = engine.findAllChildren(cloudreg);
+ assertTrue(crRes.containsAll(crExpected) && crExpected.containsAll(crRes));
+
+ List<Vertex> vsRes = engine.findAllChildren(vserver);
+ assertTrue(vsRes.containsAll(vsExpected) && vsExpected.containsAll(vsRes));
+ }
+
+ @Test
+ public void testFindChildrenOfType() throws AAIException {
+ // setup
+ Graph graph = TinkerGraph.open();
+
+ Vertex gv = graph.addVertex(T.id, "00", "aai-node-type", "generic-vnf");
+ Vertex lint1 = graph.addVertex(T.id, "10", "aai-node-type", "l-interface");
+ Vertex lint2 = graph.addVertex(T.id, "11", "aai-node-type", "l-interface");
+ Vertex lag = graph.addVertex(T.id, "20", "aai-node-type", "lag-interface");
+ Vertex lint3 = graph.addVertex(T.id, "12", "aai-node-type", "l-interface");
+
+ GraphTraversalSource g = graph.traversal();
+
+ edgeSer.addTreeEdge(g, gv, lint1);
+ edgeSer.addTreeEdge(g, gv, lint2);
+ edgeSer.addTreeEdge(g, gv, lag);
+ edgeSer.addTreeEdge(g, lag, lint3);
+
+ List<Vertex> expected = new ArrayList<>(Arrays.asList(lint1, lint2));
+
+ GraphTraversalQueryEngine engine = new GraphTraversalQueryEngine(g);
+
+ // test
+ List<Vertex> results = engine.findChildrenOfType(gv, "l-interface");
+ assertTrue(results.containsAll(expected) && expected.containsAll(results));
+ }
+
+ @Test
+ public void testFindChildren() throws AAIException {
+ // setup
+ Graph graph = TinkerGraph.open();
+
+ Vertex gv = graph.addVertex(T.id, "00", "aai-node-type", "generic-vnf");
+ Vertex lint1 = graph.addVertex(T.id, "10", "aai-node-type", "l-interface");
+ Vertex lint2 = graph.addVertex(T.id, "11", "aai-node-type", "l-interface");
+ Vertex lag = graph.addVertex(T.id, "20", "aai-node-type", "lag-interface");
+ Vertex lint3 = graph.addVertex(T.id, "12", "aai-node-type", "l-interface");
+
+ GraphTraversalSource g = graph.traversal();
+
+ edgeSer.addTreeEdge(g, gv, lint1);
+ edgeSer.addTreeEdge(g, gv, lint2);
+ edgeSer.addTreeEdge(g, gv, lag);
+ edgeSer.addTreeEdge(g, lag, lint3);
+
+ List<Vertex> expected = new ArrayList<>(Arrays.asList(lint1, lint2, lag));
+
+ GraphTraversalQueryEngine engine = new GraphTraversalQueryEngine(g);
+
+ // test
+ List<Vertex> results = engine.findChildren(gv);
+ assertTrue(results.containsAll(expected) && expected.containsAll(results));
+ }
+
+ @Test
+ public void testFindRelatedVertices() throws AAIException {
+ // setup
+
+ Graph graph = TinkerGraph.open();
- Vertex cloudreg = graph.addVertex(T.id, "00", "aai-node-type", "cloud-region");
- Vertex tenant = graph.addVertex(T.id, "10", "aai-node-type", "tenant");
- Vertex vserver = graph.addVertex(T.id, "20", "aai-node-type", "vserver");
- Vertex vserver2 = graph.addVertex(T.id, "21", "aai-node-type", "vserver");
- Vertex oam = graph.addVertex(T.id, "30", "aai-node-type", "oam-network");
+ Vertex gv = graph.addVertex(T.id, "00", "aai-node-type", "generic-vnf");
+ Vertex lint = graph.addVertex(T.id, "10", "aai-node-type", "l-interface");
+ Vertex lint2 = graph.addVertex(T.id, "11", "aai-node-type", "l-interface");
+ Vertex log = graph.addVertex(T.id, "20", "aai-node-type", "logical-link");
- GraphTraversalSource g = graph.traversal();
+ GraphTraversalSource g = graph.traversal();
- edgeSer.addTreeEdge(g, cloudreg, tenant);
- edgeSer.addTreeEdge(g, tenant, vserver);
- edgeSer.addTreeEdge(g, tenant, vserver2);
- edgeSer.addTreeEdge(g, cloudreg, oam);
+ edgeSer.addTreeEdge(g, gv, lint);
+ edgeSer.addEdge(g, lint, log);
+ edgeSer.addEdge(g, log, lint2);
- List<Vertex> crExpected = new ArrayList<>(Arrays.asList(cloudreg, tenant, vserver, vserver2, oam));
- List<Vertex> vsExpected = new ArrayList<>(Arrays.asList(vserver));
+ List<Vertex> outExpected = new ArrayList<>(Arrays.asList(lint));
+ List<Vertex> inExpected = new ArrayList<>(Arrays.asList(lint, lint2));
+ List<Vertex> bothExpected = new ArrayList<>(Arrays.asList(log));
- GraphTraversalQueryEngine engine = new GraphTraversalQueryEngine(g);
+ GraphTraversalQueryEngine engine = new GraphTraversalQueryEngine(g);
- //test
- List<Vertex> crRes = engine.findAllChildren(cloudreg);
- assertTrue(crRes.containsAll(crExpected) && crExpected.containsAll(crRes));
+ // test
+ List<Vertex> outRes = engine.findRelatedVertices(gv, Direction.IN, "org.onap.relationships.inventory.BelongsTo",
+ "l-interface");
+ assertTrue(outRes.containsAll(outExpected) && outExpected.containsAll(outRes));
- List<Vertex> vsRes = engine.findAllChildren(vserver);
- assertTrue(vsRes.containsAll(vsExpected) && vsExpected.containsAll(vsRes));
- }
+ List<Vertex> inRes =
+ engine.findRelatedVertices(log, Direction.IN, "tosca.relationships.network.LinksTo", "l-interface");
+ assertTrue(inRes.containsAll(inExpected) && inExpected.containsAll(inRes));
- @Test
- public void testFindChildrenOfType() throws AAIException {
- //setup
- Graph graph = TinkerGraph.open();
+ List<Vertex> bothRes =
+ engine.findRelatedVertices(lint, Direction.BOTH, "tosca.relationships.network.LinksTo", "logical-link");
+ assertTrue(bothRes.containsAll(bothExpected) && bothExpected.containsAll(bothRes));
+ }
+
+ @Test
+ public void testFindSubGraph() throws AAIException, EdgeRuleNotFoundException, AmbiguousRuleChoiceException {
+ // setup
+ Graph graph = TinkerGraph.open();
- Vertex gv = graph.addVertex(T.id, "00", "aai-node-type", "generic-vnf");
- Vertex lint1 = graph.addVertex(T.id, "10", "aai-node-type", "l-interface");
- Vertex lint2 = graph.addVertex(T.id, "11", "aai-node-type", "l-interface");
- Vertex lag = graph.addVertex(T.id, "20", "aai-node-type", "lag-interface");
- Vertex lint3 = graph.addVertex(T.id, "12", "aai-node-type", "l-interface");
+ Vertex cr = graph.addVertex(T.id, "00", "aai-node-type", "cloud-region");
+ Vertex ten = graph.addVertex(T.id, "10", "aai-node-type", "tenant");
+ Vertex ten2 = graph.addVertex(T.id, "11", "aai-node-type", "tenant");
+ Vertex vs = graph.addVertex(T.id, "20", "aai-node-type", "vserver");
+ Vertex vs2 = graph.addVertex(T.id, "21", "aai-node-type", "vserver");
+ Vertex lint = graph.addVertex(T.id, "30", "aai-node-type", "l-interface");
+ Vertex comp = graph.addVertex(T.id, "40", "aai-node-type", "complex");
+ Vertex ctag = graph.addVertex(T.id, "50", "aai-node-type", "ctag-pool");
+ Vertex gv = graph.addVertex(T.id, "60", "aai-node-type", "generic-vnf");
+ Vertex lag = graph.addVertex(T.id, "70", "aai-node-type", "lag-interface");
+ Vertex lint2 = graph.addVertex(T.id, "31", "aai-node-type", "l-interface");
+ Vertex log = graph.addVertex(T.id, "80", "aai-node-type", "logical-link");
+ Vertex vnfc = graph.addVertex(T.id, "90", "aai-node-type", "vnfc");
+ Vertex modelVer = graph.addVertex(T.id, "100", "aai-node-type", "model-ver");
- GraphTraversalSource g = graph.traversal();
+ GraphTraversalSource g = graph.traversal();
- edgeSer.addTreeEdge(g, gv, lint1);
- edgeSer.addTreeEdge(g, gv, lint2);
- edgeSer.addTreeEdge(g, gv, lag);
- edgeSer.addTreeEdge(g, lag, lint3);
-
- List<Vertex> expected = new ArrayList<>(Arrays.asList(lint1, lint2));
-
- GraphTraversalQueryEngine engine = new GraphTraversalQueryEngine(g);
-
- //test
- List<Vertex> results = engine.findChildrenOfType(gv, "l-interface");
- assertTrue(results.containsAll(expected) && expected.containsAll(results));
- }
-
- @Test
- public void testFindChildren() throws AAIException {
- //setup
- Graph graph = TinkerGraph.open();
-
- Vertex gv = graph.addVertex(T.id, "00", "aai-node-type", "generic-vnf");
- Vertex lint1 = graph.addVertex(T.id, "10", "aai-node-type", "l-interface");
- Vertex lint2 = graph.addVertex(T.id, "11", "aai-node-type", "l-interface");
- Vertex lag = graph.addVertex(T.id, "20", "aai-node-type", "lag-interface");
- Vertex lint3 = graph.addVertex(T.id, "12", "aai-node-type", "l-interface");
-
- GraphTraversalSource g = graph.traversal();
-
- edgeSer.addTreeEdge(g, gv, lint1);
- edgeSer.addTreeEdge(g, gv, lint2);
- edgeSer.addTreeEdge(g, gv, lag);
- edgeSer.addTreeEdge(g, lag, lint3);
-
- List<Vertex> expected = new ArrayList<>(Arrays.asList(lint1, lint2, lag));
-
- GraphTraversalQueryEngine engine = new GraphTraversalQueryEngine(g);
-
- //test
- List<Vertex> results = engine.findChildren(gv);
- assertTrue(results.containsAll(expected) && expected.containsAll(results));
- }
-
- @Test
- public void testFindRelatedVertices() throws AAIException {
- //setup
-
- Graph graph = TinkerGraph.open();
-
- Vertex gv = graph.addVertex(T.id, "00", "aai-node-type", "generic-vnf");
- Vertex lint = graph.addVertex(T.id, "10", "aai-node-type", "l-interface");
- Vertex lint2 = graph.addVertex(T.id, "11", "aai-node-type", "l-interface");
- Vertex log = graph.addVertex(T.id, "20", "aai-node-type", "logical-link");
-
- GraphTraversalSource g = graph.traversal();
-
- edgeSer.addTreeEdge(g, gv, lint);
- edgeSer.addEdge(g, lint, log);
- edgeSer.addEdge(g, log, lint2);
-
- List<Vertex> outExpected = new ArrayList<>(Arrays.asList(lint));
- List<Vertex> inExpected = new ArrayList<>(Arrays.asList(lint, lint2));
- List<Vertex> bothExpected = new ArrayList<>(Arrays.asList(log));
-
- GraphTraversalQueryEngine engine = new GraphTraversalQueryEngine(g);
-
- //test
- List<Vertex> outRes = engine.findRelatedVertices(gv, Direction.IN, "org.onap.relationships.inventory.BelongsTo", "l-interface");
- assertTrue(outRes.containsAll(outExpected) && outExpected.containsAll(outRes));
-
- List<Vertex> inRes = engine.findRelatedVertices(log, Direction.IN, "tosca.relationships.network.LinksTo", "l-interface");
- assertTrue(inRes.containsAll(inExpected) && inExpected.containsAll(inRes));
-
- List<Vertex> bothRes = engine.findRelatedVertices(lint, Direction.BOTH, "tosca.relationships.network.LinksTo", "logical-link");
- assertTrue(bothRes.containsAll(bothExpected) && bothExpected.containsAll(bothRes));
- }
-
- @Test
- public void testFindSubGraph() throws AAIException, EdgeRuleNotFoundException, AmbiguousRuleChoiceException {
- //setup
- Graph graph = TinkerGraph.open();
-
- Vertex cr = graph.addVertex(T.id, "00", "aai-node-type", "cloud-region");
- Vertex ten = graph.addVertex(T.id, "10", "aai-node-type", "tenant");
- Vertex ten2 = graph.addVertex(T.id, "11", "aai-node-type", "tenant");
- Vertex vs = graph.addVertex(T.id, "20", "aai-node-type", "vserver");
- Vertex vs2 = graph.addVertex(T.id, "21", "aai-node-type", "vserver");
- Vertex lint = graph.addVertex(T.id, "30", "aai-node-type", "l-interface");
- Vertex comp = graph.addVertex(T.id, "40", "aai-node-type", "complex");
- Vertex ctag = graph.addVertex(T.id, "50", "aai-node-type", "ctag-pool");
- Vertex gv = graph.addVertex(T.id, "60", "aai-node-type", "generic-vnf");
- Vertex lag = graph.addVertex(T.id, "70", "aai-node-type", "lag-interface");
- Vertex lint2 = graph.addVertex(T.id, "31", "aai-node-type", "l-interface");
- Vertex log = graph.addVertex(T.id, "80", "aai-node-type", "logical-link");
- Vertex vnfc = graph.addVertex(T.id, "90", "aai-node-type", "vnfc");
- Vertex modelVer = graph.addVertex(T.id, "100", "aai-node-type", "model-ver");
-
- GraphTraversalSource g = graph.traversal();
-
- Edge crTen = edgeSer.addTreeEdge(g, cr, ten);
- Edge crTen2 = edgeSer.addTreeEdge(g, cr, ten2);
- Edge tenVs = edgeSer.addTreeEdge(g, ten, vs);
- Edge tenVs2 = edgeSer.addTreeEdge(g, ten, vs2);
- Edge vsLInt = edgeSer.addTreeEdge(g, vs, lint);
- Edge lintLog = edgeSer.addEdge(g, lint, log);
- Edge vsGv = edgeSer.addEdge(g, vs, gv);
- edgeSer.addEdge(g, gv, vnfc);
-
- edgeSer.addTreeEdge(g, gv, lag);
- edgeSer.addTreeEdge(g, lag, lint2);
+ Edge crTen = edgeSer.addTreeEdge(g, cr, ten);
+ Edge crTen2 = edgeSer.addTreeEdge(g, cr, ten2);
+ Edge tenVs = edgeSer.addTreeEdge(g, ten, vs);
+ Edge tenVs2 = edgeSer.addTreeEdge(g, ten, vs2);
+ Edge vsLInt = edgeSer.addTreeEdge(g, vs, lint);
+ Edge lintLog = edgeSer.addEdge(g, lint, log);
+ Edge vsGv = edgeSer.addEdge(g, vs, gv);
+ edgeSer.addEdge(g, gv, vnfc);
+
+ edgeSer.addTreeEdge(g, gv, lag);
+ edgeSer.addTreeEdge(g, lag, lint2);
Edge modelVerEdge = edgeSer.addPrivateEdge(g, gv, modelVer, null);
- edgeSer.addTreeEdge(g, comp, ctag);
- Edge crComp = edgeSer.addEdge(g, cr, comp);
-
- //findSubGraph(cr, 0, true)
- List<Element> expected1 = new ArrayList<>(Arrays.asList(cr));
- //findSubGraph(cr, 2, true)
- List<Element> expected2 = new ArrayList<>(Arrays.asList(cr, ten, ten2, vs, vs2,
- crTen, crTen2, tenVs, tenVs2));
- //findSubGraph(cr)
- List<Element> expected3 = new ArrayList<>(Arrays.asList(cr, ten, ten2, comp, vs, vs2, lint, gv, log,
- crTen, crTen2, crComp, tenVs, tenVs2, vsLInt,
- vsGv, lintLog));
-
- GraphTraversalQueryEngine engine = new GraphTraversalQueryEngine(g);
-
- //test
- Tree<Element> res1 = engine.findSubGraph(cr, 0, true);
- Set<Element> resList1 = treeToList(res1);
- assertTrue(resList1.containsAll(expected1) && expected1.containsAll(resList1));
-
- Tree<Element> res2 = engine.findSubGraph(cr, 2, true);
- Set<Element> resList2 = treeToList(res2);
- assertTrue(resList2.containsAll(expected2) && expected2.containsAll(resList2));
-
- Tree<Element> res3 = engine.findSubGraph(cr);
- Set<Element> resList3 = treeToList(res3);
- assertThat(resList3, containsInAnyOrder(expected3.toArray()));
-// assertTrue(resList3.containsAll(expected3) && expected3.containsAll(resList3));
- }
-
- /**
- * convenience helper method to make it easier to check the contents of the tree against
- * a list of expected results
- * @param tree - the tree whose contents you want in collection form
- * @return set of the contents of the tree
- */
- private Set<Element> treeToList(Tree<Element> tree) {
- Set<Element> ret = new HashSet<>();
-
- for (Element key : tree.keySet()) {
- ret.add(key);
- ret.addAll(treeToList(tree.get(key)));
- }
-
- return ret;
- }
-
- @Test
- public void testFindEdgesForVersion() throws AAIException, EdgeRuleNotFoundException, AmbiguousRuleChoiceException {
- //setup
- Graph graph = TinkerGraph.open();
-
- Vertex gv = graph.addVertex(T.id, "00", "aai-node-type", "generic-vnf");
- Vertex vnfc = graph.addVertex(T.id, "10", "aai-node-type", "vnfc");
- Vertex lob = graph.addVertex(T.id, "20", "aai-node-type", "line-of-business");
- Vertex lint = graph.addVertex(T.id, "30", "aai-node-type", "l-interface");
- Vertex mv = graph.addVertex(T.id, "40", "aai-node-type", "model-ver");
- Vertex cr = graph.addVertex(T.id, "50", "aai-node-type", "cloud-region");
- Vertex tn = graph.addVertex(T.id, "60", "aai-node-type", "tenant");
-
- Edge cloudRegionToTenantEdge = tn
- .addEdge("some-edge", cr, CONTAINS.toString(), "NONE");
-
- GraphTraversalSource g = graph.traversal();
-
- edgeSer.addTreeEdge(g, gv, lint); //tree edge so shouldn't appear in results
- Edge gvVnfc = edgeSer.addEdge(g, gv, vnfc);
- edgeSer.addEdge(g, gv, lob); //v11/12 not v10
+ edgeSer.addTreeEdge(g, comp, ctag);
+ Edge crComp = edgeSer.addEdge(g, cr, comp);
+
+ // findSubGraph(cr, 0, true)
+ List<Element> expected1 = new ArrayList<>(Arrays.asList(cr));
+ // findSubGraph(cr, 2, true)
+ List<Element> expected2 = new ArrayList<>(Arrays.asList(cr, ten, ten2, vs, vs2, crTen, crTen2, tenVs, tenVs2));
+ // findSubGraph(cr)
+ List<Element> expected3 = new ArrayList<>(Arrays.asList(cr, ten, ten2, comp, vs, vs2, lint, gv, log, crTen,
+ crTen2, crComp, tenVs, tenVs2, vsLInt, vsGv, lintLog));
+
+ GraphTraversalQueryEngine engine = new GraphTraversalQueryEngine(g);
+
+ // test
+ Tree<Element> res1 = engine.findSubGraph(cr, 0, true);
+ Set<Element> resList1 = treeToList(res1);
+ assertTrue(resList1.containsAll(expected1) && expected1.containsAll(resList1));
+
+ Tree<Element> res2 = engine.findSubGraph(cr, 2, true);
+ Set<Element> resList2 = treeToList(res2);
+ assertTrue(resList2.containsAll(expected2) && expected2.containsAll(resList2));
+
+ Tree<Element> res3 = engine.findSubGraph(cr);
+ Set<Element> resList3 = treeToList(res3);
+ assertThat(resList3, containsInAnyOrder(expected3.toArray()));
+ // assertTrue(resList3.containsAll(expected3) && expected3.containsAll(resList3));
+ }
+
+ /**
+ * convenience helper method to make it easier to check the contents of the tree against
+ * a list of expected results
+ *
+ * @param tree - the tree whose contents you want in collection form
+ * @return set of the contents of the tree
+ */
+ private Set<Element> treeToList(Tree<Element> tree) {
+ Set<Element> ret = new HashSet<>();
+
+ for (Element key : tree.keySet()) {
+ ret.add(key);
+ ret.addAll(treeToList(tree.get(key)));
+ }
+
+ return ret;
+ }
+
+ @Test
+ public void testFindEdgesForVersion() throws AAIException, EdgeRuleNotFoundException, AmbiguousRuleChoiceException {
+ // setup
+ Graph graph = TinkerGraph.open();
+
+ Vertex gv = graph.addVertex(T.id, "00", "aai-node-type", "generic-vnf");
+ Vertex vnfc = graph.addVertex(T.id, "10", "aai-node-type", "vnfc");
+ Vertex lob = graph.addVertex(T.id, "20", "aai-node-type", "line-of-business");
+ Vertex lint = graph.addVertex(T.id, "30", "aai-node-type", "l-interface");
+ Vertex mv = graph.addVertex(T.id, "40", "aai-node-type", "model-ver");
+ Vertex cr = graph.addVertex(T.id, "50", "aai-node-type", "cloud-region");
+ Vertex tn = graph.addVertex(T.id, "60", "aai-node-type", "tenant");
+
+ Edge cloudRegionToTenantEdge = tn.addEdge("some-edge", cr, CONTAINS.toString(), "NONE");
+
+ GraphTraversalSource g = graph.traversal();
+
+ edgeSer.addTreeEdge(g, gv, lint); // tree edge so shouldn't appear in results
+ Edge gvVnfc = edgeSer.addEdge(g, gv, vnfc);
+ edgeSer.addEdge(g, gv, lob); // v11/12 not v10
Edge gvMvEdge = edgeSer.addPrivateEdge(g, gv, mv, null);
- List<Edge> expected = new ArrayList<>(Arrays.asList(gvVnfc));
+ List<Edge> expected = new ArrayList<>(Arrays.asList(gvVnfc));
- GraphTraversalQueryEngine engine = new GraphTraversalQueryEngine(g);
+ GraphTraversalQueryEngine engine = new GraphTraversalQueryEngine(g);
- //test
- Loader loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getRelatedLinkVersion());
- List<Edge> results = engine.findEdgesForVersion(gv, loader);
- assertThat(results, containsInAnyOrder(expected.toArray()));
+ // test
+ Loader loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getRelatedLinkVersion());
+ List<Edge> results = engine.findEdgesForVersion(gv, loader);
+ assertThat(results, containsInAnyOrder(expected.toArray()));
expected = new ArrayList<>(Arrays.asList(cloudRegionToTenantEdge));
- results = engine.findEdgesForVersion(cr, loader);
- assertThat(results, containsInAnyOrder(expected.toArray()));
- }
+ results = engine.findEdgesForVersion(cr, loader);
+ assertThat(results, containsInAnyOrder(expected.toArray()));
+ }
- @Test
- public void testFindCousinVertices() throws AAIException {
- //setup
- Graph graph = TinkerGraph.open();
+ @Test
+ public void testFindCousinVertices() throws AAIException {
+ // setup
+ Graph graph = TinkerGraph.open();
- Vertex gv = graph.addVertex(T.id, "00", "aai-node-type", "generic-vnf");
- Vertex vnfc = graph.addVertex(T.id, "10", "aai-node-type", "vnfc");
- Vertex lob = graph.addVertex(T.id, "20", "aai-node-type", "line-of-business");
- Vertex lint = graph.addVertex(T.id, "30", "aai-node-type", "l-interface");
+ Vertex gv = graph.addVertex(T.id, "00", "aai-node-type", "generic-vnf");
+ Vertex vnfc = graph.addVertex(T.id, "10", "aai-node-type", "vnfc");
+ Vertex lob = graph.addVertex(T.id, "20", "aai-node-type", "line-of-business");
+ Vertex lint = graph.addVertex(T.id, "30", "aai-node-type", "l-interface");
- GraphTraversalSource g = graph.traversal();
+ GraphTraversalSource g = graph.traversal();
- edgeSer.addTreeEdge(g, gv, lint); //tree edge so shouldn't appear in results
- edgeSer.addEdge(g, gv, vnfc);
- edgeSer.addEdge(g, gv, lob);
+ edgeSer.addTreeEdge(g, gv, lint); // tree edge so shouldn't appear in results
+ edgeSer.addEdge(g, gv, vnfc);
+ edgeSer.addEdge(g, gv, lob);
- List<Vertex> expected = new ArrayList<>(Arrays.asList(vnfc, lob));
+ List<Vertex> expected = new ArrayList<>(Arrays.asList(vnfc, lob));
- GraphTraversalQueryEngine engine = new GraphTraversalQueryEngine(g);
+ GraphTraversalQueryEngine engine = new GraphTraversalQueryEngine(g);
- //test
- List<Vertex> results = engine.findCousinVertices(gv);
- assertTrue(results.containsAll(expected) && expected.containsAll(results));
- }
+ // test
+ List<Vertex> results = engine.findCousinVertices(gv);
+ assertTrue(results.containsAll(expected) && expected.containsAll(results));
+ }
}
diff --git a/aai-core/src/test/java/org/onap/aai/serialization/engines/query/GraphTraversalQueryEngine_needsFakeEdgeRulesTest.java b/aai-core/src/test/java/org/onap/aai/serialization/engines/query/GraphTraversalQueryEngine_needsFakeEdgeRulesTest.java
index 34ba2ab8..8c603558 100644
--- a/aai-core/src/test/java/org/onap/aai/serialization/engines/query/GraphTraversalQueryEngine_needsFakeEdgeRulesTest.java
+++ b/aai-core/src/test/java/org/onap/aai/serialization/engines/query/GraphTraversalQueryEngine_needsFakeEdgeRulesTest.java
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.serialization.engines.query;
import static org.junit.Assert.*;
@@ -45,46 +46,43 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration(classes = {
- ConfigConfiguration.class,
- AAICoreFakeEdgesConfigTranslator.class,
- EdgeIngestor.class,
- EdgeSerializer.class
-})
+@ContextConfiguration(
+ classes = {ConfigConfiguration.class, AAICoreFakeEdgesConfigTranslator.class, EdgeIngestor.class,
+ EdgeSerializer.class})
@DirtiesContext
public class GraphTraversalQueryEngine_needsFakeEdgeRulesTest {
- @Autowired
- EdgeSerializer edgeSer;
-
- @Test
- public void testFindDeletable() throws AAIException {
- //setup
- Graph graph = TinkerGraph.open();
- Vertex parent = graph.addVertex(T.id, "00", "aai-node-type", "test-parent");
- Vertex child = graph.addVertex(T.id, "10", "aai-node-type", "test-child");
- Vertex cousin = graph.addVertex(T.id, "20", "aai-node-type", "test-cousin");
- Vertex grandchild = graph.addVertex(T.id, "30", "aai-node-type", "test-grandchild");
+ @Autowired
+ EdgeSerializer edgeSer;
+
+ @Test
+ public void testFindDeletable() throws AAIException {
+ // setup
+ Graph graph = TinkerGraph.open();
+ Vertex parent = graph.addVertex(T.id, "00", "aai-node-type", "test-parent");
+ Vertex child = graph.addVertex(T.id, "10", "aai-node-type", "test-child");
+ Vertex cousin = graph.addVertex(T.id, "20", "aai-node-type", "test-cousin");
+ Vertex grandchild = graph.addVertex(T.id, "30", "aai-node-type", "test-grandchild");
+
+ GraphTraversalSource g = graph.traversal();
+
+ edgeSer.addTreeEdge(g, parent, child); // delete-other-v=none, no cascade
+ edgeSer.addTreeEdge(g, child, grandchild); // d-o-v=out, yes from child
+ edgeSer.addEdge(g, cousin, child); // d-o-v=out, yes from cousin
+
+ List<Vertex> parentExpected = new ArrayList<>(Arrays.asList(parent));
+ List<Vertex> childExpected = new ArrayList<>(Arrays.asList(child, grandchild));
+ List<Vertex> cousinExpected = new ArrayList<>(Arrays.asList(cousin, child, grandchild));
+
+ GraphTraversalQueryEngine engine = new GraphTraversalQueryEngine(g);
+
+ // tests
+ List<Vertex> parentDeletes = engine.findDeletable(parent);
+ assertTrue(parentExpected.containsAll(parentDeletes) && parentDeletes.containsAll(parentExpected));
+
+ List<Vertex> childDeletes = engine.findDeletable(child);
+ assertTrue(childExpected.containsAll(childDeletes) && childDeletes.containsAll(childExpected));
- GraphTraversalSource g = graph.traversal();
-
- edgeSer.addTreeEdge(g, parent, child); //delete-other-v=none, no cascade
- edgeSer.addTreeEdge(g, child, grandchild); //d-o-v=out, yes from child
- edgeSer.addEdge(g, cousin, child); //d-o-v=out, yes from cousin
-
- List<Vertex> parentExpected = new ArrayList<>(Arrays.asList(parent));
- List<Vertex> childExpected = new ArrayList<>(Arrays.asList(child, grandchild));
- List<Vertex> cousinExpected = new ArrayList<>(Arrays.asList(cousin, child, grandchild));
-
- GraphTraversalQueryEngine engine = new GraphTraversalQueryEngine(g);
-
- //tests
- List<Vertex> parentDeletes = engine.findDeletable(parent);
- assertTrue(parentExpected.containsAll(parentDeletes) && parentDeletes.containsAll(parentExpected));
-
- List<Vertex> childDeletes = engine.findDeletable(child);
- assertTrue(childExpected.containsAll(childDeletes) && childDeletes.containsAll(childExpected));
-
- List<Vertex> cousinDeletes = engine.findDeletable(cousin);
- assertTrue(cousinExpected.containsAll(cousinDeletes) && cousinDeletes.containsAll(cousinExpected));
- }
+ List<Vertex> cousinDeletes = engine.findDeletable(cousin);
+ assertTrue(cousinExpected.containsAll(cousinDeletes) && cousinDeletes.containsAll(cousinExpected));
+ }
}
diff --git a/aai-core/src/test/java/org/onap/aai/serialization/queryformats/ConsoleTest.java b/aai-core/src/test/java/org/onap/aai/serialization/queryformats/ConsoleTest.java
index 501fdbf1..d33b4af9 100644
--- a/aai-core/src/test/java/org/onap/aai/serialization/queryformats/ConsoleTest.java
+++ b/aai-core/src/test/java/org/onap/aai/serialization/queryformats/ConsoleTest.java
@@ -17,64 +17,63 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.serialization.queryformats;
+import static org.junit.Assert.*;
+
import com.google.gson.JsonObject;
+
import org.junit.Test;
import org.onap.aai.serialization.queryformats.exceptions.AAIFormatVertexException;
-import static org.junit.Assert.*;
-
public class ConsoleTest {
-
-
- Console fM1 = new Console();
-
- String param = "abcd";
-
- JsonObject resultVal;
-
- @Test
- public void classConsoleInstantiateCheck() {
- try {
- Console fm1 = new Console();
- assertNotNull("Created class Object is null", fm1);
- }
- catch(Exception e) {
- fail();
- }
+
+ Console fM1 = new Console();
+
+ String param = "abcd";
+
+ JsonObject resultVal;
+
+ @Test
+ public void classConsoleInstantiateCheck() {
+ try {
+ Console fm1 = new Console();
+ assertNotNull("Created class Object is null", fm1);
+ } catch (Exception e) {
+ fail();
+ }
}
-
- //Below method is expecting to throw an exception
-
- @Test(expected=NullPointerException.class)
+
+ // Below method is expecting to throw an exception
+
+ @Test(expected = NullPointerException.class)
public void formatObjectParamNullCheck() throws AAIFormatVertexException {
-
- param=null;
- Console fm3 = new Console();
- resultVal = fm3.formatObject(param).get();
- }
-
- @Test
+
+ param = null;
+ Console fm3 = new Console();
+ resultVal = fm3.formatObject(param).get();
+ }
+
+ @Test
public void formatObjectResultCheck() {
-
- try {
- Console fm2 = new Console();
-
- resultVal = fm2.formatObject(param).get();
- assertNotNull("The result is null", resultVal);
-
- //System.out.println(resultVal);
-
- JsonObject jsonObj = new JsonObject();
- jsonObj.addProperty("result", "abcd");
-
- assertEquals(jsonObj, resultVal);
-
- }
- catch (Exception e) {
- fail();
- }
- }
-
+
+ try {
+ Console fm2 = new Console();
+
+ resultVal = fm2.formatObject(param).get();
+ assertNotNull("The result is null", resultVal);
+
+ // System.out.println(resultVal);
+
+ JsonObject jsonObj = new JsonObject();
+ jsonObj.addProperty("result", "abcd");
+
+ assertEquals(jsonObj, resultVal);
+
+ } catch (Exception e) {
+ fail();
+ }
+ }
+
}
diff --git a/aai-core/src/test/java/org/onap/aai/serialization/queryformats/CountQuerySupportTest.java b/aai-core/src/test/java/org/onap/aai/serialization/queryformats/CountQuerySupportTest.java
index c83b5b39..a2976e0c 100644
--- a/aai-core/src/test/java/org/onap/aai/serialization/queryformats/CountQuerySupportTest.java
+++ b/aai-core/src/test/java/org/onap/aai/serialization/queryformats/CountQuerySupportTest.java
@@ -17,9 +17,18 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.serialization.queryformats;
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.when;
+
import com.google.gson.JsonObject;
+
+import java.util.Arrays;
+import java.util.List;
+
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.process.traversal.strategy.verification.ReadOnlyStrategy;
import org.apache.tinkerpop.gremlin.structure.Graph;
@@ -47,119 +56,111 @@ import org.onap.aai.serialization.queryformats.utils.UrlBuilder;
import org.onap.aai.setup.SchemaVersion;
import org.springframework.beans.factory.annotation.Autowired;
-import java.util.Arrays;
-import java.util.List;
-
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.when;
-
public class CountQuerySupportTest extends AAISetup {
- @Autowired
- private EdgeSerializer edgeSer;
-
- private Graph graph;
- private TransactionalGraphEngine dbEngine;
- private Loader loader;
- private final ModelType factoryType = ModelType.MOXY;
-
- private SchemaVersion version;
- Vertex pserver1;
- Vertex complex1;
- Vertex complex2;
-
- private DBSerializer serializer;
-
- private FormatFactory ff;
- private Formatter formatter;
-
-
-
- @Before
- public void setUp() throws Exception {
-
- version = schemaVersions.getDefaultVersion();
- MockitoAnnotations.initMocks(this);
-
- graph = TinkerGraph.open();
-
- pserver1 = graph.addVertex(T.label, "pserver", T.id, "2", "aai-node-type", "pserver", "hostname",
- "hostname-1");
- complex1 = graph.addVertex(T.label, "complex", T.id, "3", "aai-node-type", "complex",
- "physical-location-id", "physical-location-id-1", "country", "US");
-
- complex2 = graph.addVertex(T.label, "complex", T.id, "4", "aai-node-type", "complex",
- "physical-location-id", "physical-location-id-2", "country", "US");
-
- GraphTraversalSource g = graph.traversal();
- edgeSer.addEdge(g, pserver1, complex1);
-
- createLoaderEngineSetup();
-
- }
-
- @After
- public void tearDown() throws Exception {
- graph.close();
- }
-
- @Test
- public void verifyComplexVertexCountTest1() throws AAIFormatVertexException, AAIException, AAIFormatQueryResultFormatNotSupported {
- List<Object> complexList = Arrays.asList(this.complex1, this.complex2 );
- JsonObject jo = this.formatter.output(complexList);
- assertEquals(2, jo.get("results").getAsJsonArray().get(0).getAsJsonObject().get("complex").getAsInt());
- }
-
- @Test
- public void verifyPserverVertexCountTest1() throws AAIFormatVertexException, AAIException, AAIFormatQueryResultFormatNotSupported {
- List<Object> pserverList = Arrays.asList(this.pserver1 );
- JsonObject jo = this.formatter.output(pserverList);
- assertEquals(1, jo.get("results").getAsJsonArray().get(0).getAsJsonObject().get("pserver").getAsInt());
- }
-
- @Test
- public void verifyComplexVertexCountTest2() throws AAIFormatVertexException, AAIException, AAIFormatQueryResultFormatNotSupported {
- List<Object> list = Arrays.asList(this.complex1, this.pserver1, this.complex2 );
- JsonObject jo = this.formatter.output(list);
- assertEquals(2, jo.get("results").getAsJsonArray().get(0).getAsJsonObject().get("complex").getAsInt());
- }
-
- @Test
- public void verifyPserverVertexCountTest2() throws AAIFormatVertexException, AAIException, AAIFormatQueryResultFormatNotSupported {
- List<Object> list = Arrays.asList(this.complex1, this.pserver1, this.complex2 );
- JsonObject jo = this.formatter.output(list);
- assertEquals(1, jo.get("results").getAsJsonArray().get(0).getAsJsonObject().get("pserver").getAsInt());
- }
-
- @Test
- public void verifyLongTest() throws AAIFormatVertexException, AAIException, AAIFormatQueryResultFormatNotSupported {
- List<Object> complexList = Arrays.asList(Long.valueOf(22L) );
- JsonObject jo = this.formatter.output(complexList);
- assertEquals(22, jo.get("results").getAsJsonArray().get(0).getAsJsonObject().get("count").getAsInt());
- }
-
-
- public void createLoaderEngineSetup() throws AAIException {
-
- if (loader == null) {
- loader = loaderFactory.createLoaderForVersion(factoryType, version);
- //loader = LoaderFactory.createLoaderForVersion(factoryType, version);
- dbEngine = spy(new JanusGraphDBEngine(QueryStyle.TRAVERSAL, DBConnectionType.CACHED, loader));
- serializer = new DBSerializer(version, dbEngine, factoryType, "Junit");
-
- ff = new FormatFactory(loader, serializer, schemaVersions, basePath);
- formatter = ff.get(Format.count);
-
-
- TransactionalGraphEngine.Admin spyAdmin = spy(dbEngine.asAdmin());
-
- when(dbEngine.tx()).thenReturn(graph);
- when(dbEngine.asAdmin()).thenReturn(spyAdmin);
-
- when(spyAdmin.getReadOnlyTraversalSource())
- .thenReturn(graph.traversal(GraphTraversalSource.build().with(ReadOnlyStrategy.instance())));
- when(spyAdmin.getTraversalSource()).thenReturn(graph.traversal());
- }
- }
+ @Autowired
+ private EdgeSerializer edgeSer;
+
+ private Graph graph;
+ private TransactionalGraphEngine dbEngine;
+ private Loader loader;
+ private final ModelType factoryType = ModelType.MOXY;
+
+ private SchemaVersion version;
+ Vertex pserver1;
+ Vertex complex1;
+ Vertex complex2;
+
+ private DBSerializer serializer;
+
+ private FormatFactory ff;
+ private Formatter formatter;
+
+ @Before
+ public void setUp() throws Exception {
+
+ version = schemaVersions.getDefaultVersion();
+ MockitoAnnotations.initMocks(this);
+
+ graph = TinkerGraph.open();
+
+ pserver1 = graph.addVertex(T.label, "pserver", T.id, "2", "aai-node-type", "pserver", "hostname", "hostname-1");
+ complex1 = graph.addVertex(T.label, "complex", T.id, "3", "aai-node-type", "complex", "physical-location-id",
+ "physical-location-id-1", "country", "US");
+
+ complex2 = graph.addVertex(T.label, "complex", T.id, "4", "aai-node-type", "complex", "physical-location-id",
+ "physical-location-id-2", "country", "US");
+
+ GraphTraversalSource g = graph.traversal();
+ edgeSer.addEdge(g, pserver1, complex1);
+
+ createLoaderEngineSetup();
+
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ graph.close();
+ }
+
+ @Test
+ public void verifyComplexVertexCountTest1()
+ throws AAIFormatVertexException, AAIException, AAIFormatQueryResultFormatNotSupported {
+ List<Object> complexList = Arrays.asList(this.complex1, this.complex2);
+ JsonObject jo = this.formatter.output(complexList);
+ assertEquals(2, jo.get("results").getAsJsonArray().get(0).getAsJsonObject().get("complex").getAsInt());
+ }
+
+ @Test
+ public void verifyPserverVertexCountTest1()
+ throws AAIFormatVertexException, AAIException, AAIFormatQueryResultFormatNotSupported {
+ List<Object> pserverList = Arrays.asList(this.pserver1);
+ JsonObject jo = this.formatter.output(pserverList);
+ assertEquals(1, jo.get("results").getAsJsonArray().get(0).getAsJsonObject().get("pserver").getAsInt());
+ }
+
+ @Test
+ public void verifyComplexVertexCountTest2()
+ throws AAIFormatVertexException, AAIException, AAIFormatQueryResultFormatNotSupported {
+ List<Object> list = Arrays.asList(this.complex1, this.pserver1, this.complex2);
+ JsonObject jo = this.formatter.output(list);
+ assertEquals(2, jo.get("results").getAsJsonArray().get(0).getAsJsonObject().get("complex").getAsInt());
+ }
+
+ @Test
+ public void verifyPserverVertexCountTest2()
+ throws AAIFormatVertexException, AAIException, AAIFormatQueryResultFormatNotSupported {
+ List<Object> list = Arrays.asList(this.complex1, this.pserver1, this.complex2);
+ JsonObject jo = this.formatter.output(list);
+ assertEquals(1, jo.get("results").getAsJsonArray().get(0).getAsJsonObject().get("pserver").getAsInt());
+ }
+
+ @Test
+ public void verifyLongTest() throws AAIFormatVertexException, AAIException, AAIFormatQueryResultFormatNotSupported {
+ List<Object> complexList = Arrays.asList(Long.valueOf(22L));
+ JsonObject jo = this.formatter.output(complexList);
+ assertEquals(22, jo.get("results").getAsJsonArray().get(0).getAsJsonObject().get("count").getAsInt());
+ }
+
+ public void createLoaderEngineSetup() throws AAIException {
+
+ if (loader == null) {
+ loader = loaderFactory.createLoaderForVersion(factoryType, version);
+ // loader = LoaderFactory.createLoaderForVersion(factoryType, version);
+ dbEngine = spy(new JanusGraphDBEngine(QueryStyle.TRAVERSAL, DBConnectionType.CACHED, loader));
+ serializer = new DBSerializer(version, dbEngine, factoryType, "Junit");
+
+ ff = new FormatFactory(loader, serializer, schemaVersions, basePath);
+ formatter = ff.get(Format.count);
+
+ TransactionalGraphEngine.Admin spyAdmin = spy(dbEngine.asAdmin());
+
+ when(dbEngine.tx()).thenReturn(graph);
+ when(dbEngine.asAdmin()).thenReturn(spyAdmin);
+
+ when(spyAdmin.getReadOnlyTraversalSource())
+ .thenReturn(graph.traversal(GraphTraversalSource.build().with(ReadOnlyStrategy.instance())));
+ when(spyAdmin.getTraversalSource()).thenReturn(graph.traversal());
+ }
+ }
}
diff --git a/aai-core/src/test/java/org/onap/aai/serialization/queryformats/FormatTest.java b/aai-core/src/test/java/org/onap/aai/serialization/queryformats/FormatTest.java
index 6838481e..965e7157 100644
--- a/aai-core/src/test/java/org/onap/aai/serialization/queryformats/FormatTest.java
+++ b/aai-core/src/test/java/org/onap/aai/serialization/queryformats/FormatTest.java
@@ -17,32 +17,33 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.serialization.queryformats;
+import static org.junit.Assert.*;
+
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.onap.aai.AAISetup;
import org.onap.aai.exceptions.AAIException;
-import static org.junit.Assert.*;
-
public class FormatTest extends AAISetup {
- @Rule
- public ExpectedException expectedEx = ExpectedException.none();
+ @Rule
+ public ExpectedException expectedEx = ExpectedException.none();
- @Test
- public void validFormatTest() throws AAIException {
- assertEquals(Format.count, Format.getFormat("count"));
- }
+ @Test
+ public void validFormatTest() throws AAIException {
+ assertEquals(Format.count, Format.getFormat("count"));
+ }
- @Test
- public void invalidFormatTest() throws AAIException {
- String format = "test";
- expectedEx.expect(AAIException.class);
- expectedEx.expectMessage("Unsupported format query parameter " + format + " in request.");
- Format.getFormat(format);
- }
+ @Test
+ public void invalidFormatTest() throws AAIException {
+ String format = "test";
+ expectedEx.expect(AAIException.class);
+ expectedEx.expectMessage("Unsupported format query parameter " + format + " in request.");
+ Format.getFormat(format);
+ }
-} \ No newline at end of file
+}
diff --git a/aai-core/src/test/java/org/onap/aai/serialization/queryformats/GraphSONTest.java b/aai-core/src/test/java/org/onap/aai/serialization/queryformats/GraphSONTest.java
index 154761ae..847a45ed 100644
--- a/aai-core/src/test/java/org/onap/aai/serialization/queryformats/GraphSONTest.java
+++ b/aai-core/src/test/java/org/onap/aai/serialization/queryformats/GraphSONTest.java
@@ -17,12 +17,22 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.serialization.queryformats;
+import static org.hamcrest.CoreMatchers.containsString;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.core.IsNot.not;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
+
+import java.util.Optional;
+
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.T;
@@ -46,520 +56,423 @@ import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-import java.util.Optional;
-
-import static org.hamcrest.CoreMatchers.containsString;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.core.IsNot.not;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-
@RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration(classes = {
- ConfigConfiguration.class,
- AAICorePrivateEdgeTestConfigTranslator.class,
- EdgeIngestor.class,
- EdgeSerializer.class,
- SpringContextAware.class
-})
+@ContextConfiguration(
+ classes = {ConfigConfiguration.class, AAICorePrivateEdgeTestConfigTranslator.class, EdgeIngestor.class,
+ EdgeSerializer.class, SpringContextAware.class})
@DirtiesContext
public class GraphSONTest {
private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(GraphSONTest.class);
- private Graph graph;
- private Vertex v1;
-
- @Autowired
- protected EdgeSerializer edgeSer;
-
- @Autowired
- protected EdgeIngestor rules;
-
- private JsonObject jsonObj = new JsonObject() ;
- private JsonObject properties = new JsonObject();
- private JsonArray name = new JsonArray() ;
- private JsonObject idVal = new JsonObject() ;
-
- private GraphSON graphSON;
-
- @Before
- public void setUp() {
-
- jsonObj.addProperty("id", 0);
- jsonObj.addProperty("label", "vertex");
-
- idVal.addProperty("id", 1);
- idVal.addProperty("value", "Sam");
-
- name.add(idVal);
- properties.add("name",name);
- jsonObj.add("properties", properties);
-
- graph = TinkerGraph.open();
- v1 = graph.addVertex("name", "Sam");
-
- graphSON = new GraphSON();
- }
-
- @Test
- public void classGraphSONTestWithVertex(){
-
- GraphSON graphSonObj1 = new GraphSON();
- JsonObject obj = graphSonObj1.formatObject(v1).get();
-
- assertEquals(jsonObj, obj);
- }
-
- /**
+ private Graph graph;
+ private Vertex v1;
+
+ @Autowired
+ protected EdgeSerializer edgeSer;
+
+ @Autowired
+ protected EdgeIngestor rules;
+
+ private JsonObject jsonObj = new JsonObject();
+ private JsonObject properties = new JsonObject();
+ private JsonArray name = new JsonArray();
+ private JsonObject idVal = new JsonObject();
+
+ private GraphSON graphSON;
+
+ @Before
+ public void setUp() {
+
+ jsonObj.addProperty("id", 0);
+ jsonObj.addProperty("label", "vertex");
+
+ idVal.addProperty("id", 1);
+ idVal.addProperty("value", "Sam");
+
+ name.add(idVal);
+ properties.add("name", name);
+ jsonObj.add("properties", properties);
+
+ graph = TinkerGraph.open();
+ v1 = graph.addVertex("name", "Sam");
+
+ graphSON = new GraphSON();
+ }
+
+ @Test
+ public void classGraphSONTestWithVertex() {
+
+ GraphSON graphSonObj1 = new GraphSON();
+ JsonObject obj = graphSonObj1.formatObject(v1).get();
+
+ assertEquals(jsonObj, obj);
+ }
+
+ /**
* Case where there is only one private edge
+ *
+ * <pre>
+ * {
+ * "id": 21,
+ * "inE": {
+ * "org.onap.relationships.inventory.isA": [
+ * {
+ * "id": 10,
+ * "properties": {
+ * "aai-uuid": "oafjdsiofjs",
+ * "private": true
+ * }
+ * }
+ * ]
+ * }
+ * "label": "model-ver",
+ * "properties": {
+ * "aai-node-type": [
+ * {
+ * "id": 5,
+ * "value": "model-ver"
+ * }
+ * ]
+ * }
+ * }
+ * </pre>
+ *
+ * @throws AAIException
+ */
+ @Test
+ public void testGraphWithVertexHavingPrivateEdges()
+ throws AAIException, EdgeRuleNotFoundException, AmbiguousRuleChoiceException {
+
+ Vertex genericVnf = graph.addVertex(T.label, "generic-vnf", T.id, "20", "aai-node-type", "generic-vnf",
+ "vnf-id", "vnf-id-1", "vnf-name", "vnf-name-1");
+
+ Vertex modelVer = graph.addVertex(T.label, "model-ver", T.id, "21", "aai-node-type", "model-ver",
+ "model-version-id", "modelVer1", "model-name", "modelName1");
+
+ GraphTraversalSource source = graph.traversal();
+ edgeSer.addPrivateEdge(source, genericVnf, modelVer, null);
+
+ Optional<JsonObject> jsonObjectOptional = graphSON.formatObject(genericVnf);
+ JsonObject obj = jsonObjectOptional.get();
+ LOGGER.info(obj.toString());
+ assertNotNull(obj);
+ String value = obj.toString();
+
+ assertThat(value, not(containsString("private")));
+ assertThat(value, not(containsString("inE")));
+ assertThat(value, not(containsString("outE")));
+ }
+
+ /**
+ * Case where there is one private edge and regular edge
+ * with the same edge label name
+ *
+ * <pre>
+ * {
+ * "id": 21,
+ * "inE": {
+ * "org.onap.relationships.inventory.isA": [
+ * {
+ * "id": 10,
+ * "properties": {
+ * "aai-uuid": "oafjdsiofjs",
+ * "private": true
+ * }
+ * }
+ * {
+ * "id": 11,
+ * "properties": {
+ * "aai-uuid": "oafjdsiofjs",
+ * "private": false
+ * }
+ * }
+ * ]
+ * }
+ * "label": "model-ver",
+ * "properties": {
+ * "aai-node-type": [
+ * {
+ * "id": 5,
+ * "value": "model-ver"
+ * }
+ * ]
+ * }
+ * }
+ * </pre>
+ *
+ * @throws AAIException
+ */
+ @Test
+ public void testGraphWithSameLabelWithPrivateEdgeAndRegularEdge()
+ throws AAIException, EdgeRuleNotFoundException, AmbiguousRuleChoiceException {
+
+ Vertex genericVnf = graph.addVertex(T.label, "generic-vnf", T.id, "20", "aai-node-type", "generic-vnf",
+ "vnf-id", "vnf-id-1", "vnf-name", "vnf-name-1");
+
+ Vertex modelVer = graph.addVertex(T.label, "model-ver", T.id, "21", "aai-node-type", "model-ver",
+ "model-version-id", "modelVer1", "model-name", "modelName1");
+
+ Vertex modelElement = graph.addVertex(T.label, "model-element", T.id, "22", "aai-node-type", "model-element");
+
+ GraphTraversalSource source = graph.traversal();
+ edgeSer.addPrivateEdge(source, genericVnf, modelVer, null);
+ edgeSer.addEdge(source, modelVer, modelElement, null);
+
+ Optional<JsonObject> jsonObjectOptional = graphSON.formatObject(modelVer);
+ JsonObject obj = jsonObjectOptional.get();
+ LOGGER.info(obj.toString());
+ assertNotNull(obj);
+ String value = obj.toString();
+ assertThat(value, not(containsString("\"private\":true")));
+ }
+
+ /**
+ * Case where there is one private edge and regular edge to same label
+ * And another regular edge to a different label
+ *
+ * <pre>
+ * {
+ * "id": 21,
+ * "inE": {
+ * "org.onap.relationships.inventory.isA": [
+ * {
+ * "id": 10,
+ * "properties": {
+ * "aai-uuid": "oafjdsiofjs",
+ * "private": true
+ * }
+ * },
+ * {
+ * "id": 11,
+ * "properties": {
+ * "aai-uuid": "oafjdsiofjs",
+ * "private": false
+ * }
+ * }
+ * ],
+ * "org.onap.relationships.inventory.BelongsTo": [
+ * {
+ * "id": 13,
+ * "properties": {
+ * "aai-uuid": "oafjdsiofjs",
+ * "private": false
+ * }
+ * }
+ * ]
+ * }
+ * "label": "model-ver",
+ * "properties": {
+ * "aai-node-type": [
+ * {
+ * "id": 5,
+ * "value": "model-ver"
+ * }
+ * ]
+ * }
+ * }
+ * </pre>
+ *
+ * @throws AAIException
+ */
+ @Test
+ public void testGraphWithMultipleLabelWithOneLabelWithPrivateEdgeAndRegularEdgeAndAnotherLabelWithRegularEdge()
+ throws AAIException, EdgeRuleNotFoundException, AmbiguousRuleChoiceException {
+
+ Vertex genericVnf = graph.addVertex(T.label, "generic-vnf", T.id, "20", "aai-node-type", "generic-vnf",
+ "vnf-id", "vnf-id-1", "vnf-name", "vnf-name-1");
+
+ Vertex modelVer = graph.addVertex(T.label, "model-ver", T.id, "21", "aai-node-type", "model-ver",
+ "model-version-id", "modelVer1", "model-name", "modelName1");
+
+ Vertex modelElement = graph.addVertex(T.label, "model-element", T.id, "22", "aai-node-type", "model-element");
+
+ Vertex metadatum = graph.addVertex(T.label, "metadatum", T.id, "23", "aai-node-type", "metadatum");
+
+ GraphTraversalSource source = graph.traversal();
+ edgeSer.addPrivateEdge(source, genericVnf, modelVer, null);
+ edgeSer.addEdge(source, modelVer, modelElement, null);
+ edgeSer.addTreeEdge(source, modelVer, metadatum);
+
+ Optional<JsonObject> jsonObjectOptional = graphSON.formatObject(modelVer);
+ JsonObject obj = jsonObjectOptional.get();
+ LOGGER.info(obj.toString());
+ assertNotNull(obj);
+ String value = obj.toString();
+ assertThat(value, not(containsString("\"private\":true")));
+ }
+
+ @Test
+ public void testGraphCreateRegularOutAndInEdges() throws AAIException {
+
+ Vertex complex1 = graph.addVertex(T.label, "complex", T.id, "20", "aai-node-type", "complex");
+
+ Vertex pserver1 = graph.addVertex(T.label, "pserver", T.id, "22", "aai-node-type", "pserver", "hostname",
+ "test-pserver1");
+
+ Vertex pserver2 = graph.addVertex(T.label, "pserver", T.id, "23", "aai-node-type", "pserver", "hostname",
+ "test-pserver2");
+
+ GraphTraversalSource source = graph.traversal();
+ edgeSer.addEdge(source, pserver1, complex1, null);
+ edgeSer.addEdge(source, pserver2, complex1, null);
+
+ Optional<JsonObject> jsonObjectOptional = graphSON.formatObject(complex1);
+ JsonObject obj = jsonObjectOptional.get();
+ LOGGER.info(obj.toString());
+ assertNotNull(obj);
+ assertThat(obj.toString(), not(containsString("\"private\":true")));
+ assertThat(obj.toString(), containsString("inE"));
+ }
+
+ /**
+ * Case where there is one private edge and regular edge to same label
+ * And another regular edge to a different label
+ *
* <pre>
* {
- * "id": 21,
- * "inE": {
- * "org.onap.relationships.inventory.isA": [
- * {
- * "id": 10,
- * "properties": {
- * "aai-uuid": "oafjdsiofjs",
- * "private": true
- * }
- * }
- * ]
- * }
- * "label": "model-ver",
- * "properties": {
- * "aai-node-type": [
- * {
- * "id": 5,
- * "value": "model-ver"
- * }
- * ]
- * }
- * }
+ * "id": 21,
+ * "inE": {
+ * "org.onap.relationships.inventory.isA": [
+ * {
+ * "id": 10,
+ * "properties": {
+ * "aai-uuid": "oafjdsiofjs",
+ * "private": true
+ * }
+ * }
+ * ],
+ * "org.onap.relationships.inventory.BelongsTo": [
+ * {
+ * "id": 13,
+ * "properties": {
+ * "aai-uuid": "oafjdsiofjs",
+ * "private": true
+ * }
+ * }
+ * ]
+ * }
+ * "label": "model-ver",
+ * "properties": {
+ * "aai-node-type": [
+ * {
+ * "id": 5,
+ * "value": "model-ver"
+ * }
+ * ]
+ * }
+ * }
* </pre>
- *
- * @throws AAIException
- */
- @Test
- public void testGraphWithVertexHavingPrivateEdges() throws AAIException, EdgeRuleNotFoundException, AmbiguousRuleChoiceException {
-
- Vertex genericVnf = graph.addVertex(
- T.label, "generic-vnf",
- T.id, "20",
- "aai-node-type", "generic-vnf",
- "vnf-id", "vnf-id-1",
- "vnf-name", "vnf-name-1"
- );
-
- Vertex modelVer = graph.addVertex(
- T.label, "model-ver",
- T.id, "21",
- "aai-node-type", "model-ver",
- "model-version-id", "modelVer1",
- "model-name", "modelName1"
- );
-
- GraphTraversalSource source = graph.traversal();
- edgeSer.addPrivateEdge(source, genericVnf, modelVer, null);
-
- Optional<JsonObject> jsonObjectOptional = graphSON.formatObject(genericVnf);
- JsonObject obj = jsonObjectOptional.get();
- LOGGER.info(obj.toString());
- assertNotNull(obj);
- String value = obj.toString();
-
- assertThat(value, not(containsString("private")));
- assertThat(value, not(containsString("inE")));
- assertThat(value, not(containsString("outE")));
- }
-
- /**
- * Case where there is one private edge and regular edge
- * with the same edge label name
- * <pre>
- * {
- * "id": 21,
- * "inE": {
- * "org.onap.relationships.inventory.isA": [
- * {
- * "id": 10,
- * "properties": {
- * "aai-uuid": "oafjdsiofjs",
- * "private": true
- * }
- * }
- * {
- * "id": 11,
- * "properties": {
- * "aai-uuid": "oafjdsiofjs",
- * "private": false
- * }
- * }
- * ]
- * }
- * "label": "model-ver",
- * "properties": {
- * "aai-node-type": [
- * {
- * "id": 5,
- * "value": "model-ver"
- * }
- * ]
- * }
- * }
- * </pre>
- *
- * @throws AAIException
- */
- @Test
- public void testGraphWithSameLabelWithPrivateEdgeAndRegularEdge() throws AAIException, EdgeRuleNotFoundException, AmbiguousRuleChoiceException {
-
- Vertex genericVnf = graph.addVertex(
- T.label, "generic-vnf",
- T.id, "20",
- "aai-node-type", "generic-vnf",
- "vnf-id", "vnf-id-1",
- "vnf-name", "vnf-name-1"
- );
-
- Vertex modelVer = graph.addVertex(
- T.label, "model-ver",
- T.id, "21",
- "aai-node-type", "model-ver",
- "model-version-id", "modelVer1",
- "model-name", "modelName1"
- );
-
- Vertex modelElement = graph.addVertex(
- T.label, "model-element",
- T.id, "22",
- "aai-node-type", "model-element"
- );
-
-
-
- GraphTraversalSource source = graph.traversal();
- edgeSer.addPrivateEdge(source, genericVnf, modelVer, null);
- edgeSer.addEdge(source, modelVer, modelElement, null);
-
- Optional<JsonObject> jsonObjectOptional = graphSON.formatObject(modelVer);
- JsonObject obj = jsonObjectOptional.get();
- LOGGER.info(obj.toString());
- assertNotNull(obj);
- String value = obj.toString();
- assertThat(value, not(containsString("\"private\":true")));
- }
-
- /**
- * Case where there is one private edge and regular edge to same label
+ *
+ * @throws AAIException
+ */
+ @Test
+ public void testWhenMultipleEdgeLabelsBothOnlyHavePrivateEdges()
+ throws AAIException, EdgeRuleNotFoundException, AmbiguousRuleChoiceException {
+
+ Vertex genericVnf = graph.addVertex(T.label, "generic-vnf", T.id, "20", "aai-node-type", "generic-vnf",
+ "vnf-id", "vnf-id-1", "vnf-name", "vnf-name-1");
+
+ Vertex modelVer = graph.addVertex(T.label, "model-ver", T.id, "21", "aai-node-type", "model-ver",
+ "model-version-id", "modelVer1", "model-name", "modelName1");
+
+ Vertex modelPrivate = graph.addVertex(T.label, "model-private", T.id, "22", "aai-node-type", "model-private");
+
+ GraphTraversalSource source = graph.traversal();
+ edgeSer.addPrivateEdge(source, genericVnf, modelVer, null);
+ edgeSer.addPrivateEdge(source, modelVer, modelPrivate, null);
+
+ Optional<JsonObject> jsonObjectOptional = graphSON.formatObject(modelVer);
+ JsonObject obj = jsonObjectOptional.get();
+ LOGGER.info(obj.toString());
+ assertNotNull(obj);
+ String value = obj.toString();
+ assertThat(value, not(containsString("\"private\":true")));
+ assertThat(value, not(containsString("inventory.BelongsTo")));
+ assertThat(value, not(containsString("inE")));
+ }
+
+ /**
+ * Case where there is one private edge and regular edge to same label
* And another regular edge to a different label
- * <pre>
- * {
- * "id": 21,
- * "inE": {
- * "org.onap.relationships.inventory.isA": [
- * {
- * "id": 10,
- * "properties": {
- * "aai-uuid": "oafjdsiofjs",
- * "private": true
- * }
- * },
- * {
- * "id": 11,
- * "properties": {
- * "aai-uuid": "oafjdsiofjs",
- * "private": false
- * }
- * }
- * ],
- * "org.onap.relationships.inventory.BelongsTo": [
- * {
- * "id": 13,
- * "properties": {
- * "aai-uuid": "oafjdsiofjs",
- * "private": false
- * }
- * }
- * ]
- * }
- * "label": "model-ver",
- * "properties": {
- * "aai-node-type": [
- * {
- * "id": 5,
- * "value": "model-ver"
- * }
- * ]
- * }
- * }
- * </pre>
- *
- * @throws AAIException
- */
- @Test
- public void testGraphWithMultipleLabelWithOneLabelWithPrivateEdgeAndRegularEdgeAndAnotherLabelWithRegularEdge() throws AAIException, EdgeRuleNotFoundException, AmbiguousRuleChoiceException {
-
- Vertex genericVnf = graph.addVertex(
- T.label, "generic-vnf",
- T.id, "20",
- "aai-node-type", "generic-vnf",
- "vnf-id", "vnf-id-1",
- "vnf-name", "vnf-name-1"
- );
-
- Vertex modelVer = graph.addVertex(
- T.label, "model-ver",
- T.id, "21",
- "aai-node-type", "model-ver",
- "model-version-id", "modelVer1",
- "model-name", "modelName1"
- );
-
- Vertex modelElement = graph.addVertex(
- T.label, "model-element",
- T.id, "22",
- "aai-node-type", "model-element"
- );
-
- Vertex metadatum = graph.addVertex(
- T.label, "metadatum",
- T.id, "23",
- "aai-node-type", "metadatum"
- );
-
-
-
- GraphTraversalSource source = graph.traversal();
- edgeSer.addPrivateEdge(source, genericVnf, modelVer, null);
- edgeSer.addEdge(source, modelVer, modelElement, null);
- edgeSer.addTreeEdge(source, modelVer, metadatum);
-
- Optional<JsonObject> jsonObjectOptional = graphSON.formatObject(modelVer);
- JsonObject obj = jsonObjectOptional.get();
- LOGGER.info(obj.toString());
- assertNotNull(obj);
- String value = obj.toString();
- assertThat(value, not(containsString("\"private\":true")));
- }
-
- @Test
- public void testGraphCreateRegularOutAndInEdges() throws AAIException {
-
- Vertex complex1 = graph.addVertex(
- T.label, "complex",
- T.id, "20",
- "aai-node-type", "complex"
- );
-
- Vertex pserver1 = graph.addVertex(
- T.label, "pserver",
- T.id, "22",
- "aai-node-type", "pserver",
- "hostname", "test-pserver1"
- );
-
- Vertex pserver2 = graph.addVertex(
- T.label, "pserver",
- T.id, "23",
- "aai-node-type", "pserver",
- "hostname", "test-pserver2"
- );
-
-
-
- GraphTraversalSource source = graph.traversal();
- edgeSer.addEdge(source, pserver1, complex1, null);
- edgeSer.addEdge(source, pserver2, complex1, null);
-
-
- Optional<JsonObject> jsonObjectOptional = graphSON.formatObject(complex1);
- JsonObject obj = jsonObjectOptional.get();
- LOGGER.info(obj.toString());
- assertNotNull(obj);
- assertThat(obj.toString(), not(containsString("\"private\":true")));
- assertThat(obj.toString(), containsString("inE"));
- }
-
- /**
- * Case where there is one private edge and regular edge to same label
- * And another regular edge to a different label
- * <pre>
- * {
- * "id": 21,
- * "inE": {
- * "org.onap.relationships.inventory.isA": [
- * {
- * "id": 10,
- * "properties": {
- * "aai-uuid": "oafjdsiofjs",
- * "private": true
- * }
- * }
- * ],
- * "org.onap.relationships.inventory.BelongsTo": [
- * {
- * "id": 13,
- * "properties": {
- * "aai-uuid": "oafjdsiofjs",
- * "private": true
- * }
- * }
- * ]
- * }
- * "label": "model-ver",
- * "properties": {
- * "aai-node-type": [
- * {
- * "id": 5,
- * "value": "model-ver"
- * }
- * ]
- * }
- * }
- * </pre>
- *
- * @throws AAIException
- */
- @Test
- public void testWhenMultipleEdgeLabelsBothOnlyHavePrivateEdges() throws AAIException, EdgeRuleNotFoundException, AmbiguousRuleChoiceException {
-
- Vertex genericVnf = graph.addVertex(
- T.label, "generic-vnf",
- T.id, "20",
- "aai-node-type", "generic-vnf",
- "vnf-id", "vnf-id-1",
- "vnf-name", "vnf-name-1"
- );
-
- Vertex modelVer = graph.addVertex(
- T.label, "model-ver",
- T.id, "21",
- "aai-node-type", "model-ver",
- "model-version-id", "modelVer1",
- "model-name", "modelName1"
- );
-
- Vertex modelPrivate = graph.addVertex(
- T.label, "model-private",
- T.id, "22",
- "aai-node-type", "model-private"
- );
-
-
-
- GraphTraversalSource source = graph.traversal();
- edgeSer.addPrivateEdge(source, genericVnf, modelVer, null);
- edgeSer.addPrivateEdge(source, modelVer, modelPrivate, null);
-
- Optional<JsonObject> jsonObjectOptional = graphSON.formatObject(modelVer);
- JsonObject obj = jsonObjectOptional.get();
- LOGGER.info(obj.toString());
- assertNotNull(obj);
- String value = obj.toString();
- assertThat(value, not(containsString("\"private\":true")));
- assertThat(value, not(containsString("inventory.BelongsTo")));
- assertThat(value, not(containsString("inE")));
- }
-
- /**
- * Case where there is one private edge and regular edge to same label
- * And another regular edge to a different label
- * <pre>
- * {
- * "id": 21,
- * "inE": {
- * "org.onap.relationships.inventory.isA": [
- * {
- * "id": 10,
- * "properties": {
- * "aai-uuid": "oafjdsiofjs",
- * "private": true
- * }
- * }
- * ],
- * "org.onap.relationships.inventory.BelongsTo": [
- * {
- * "id": 13,
- * "properties": {
- * "aai-uuid": "oafjdsiofjs",
- * "private": true
- * }
- * },
- * {
- * "id": 13,
- * "properties": {
- * "aai-uuid": "jaosjfaisj",
- * "private": false
- * }
- * }
- * ]
- * }
- * "label": "model-ver",
- * "properties": {
- * "aai-node-type": [
- * {
- * "id": 5,
- * "value": "model-ver"
- * }
- * ]
- * }
- * }
- * </pre>
- *
- * @throws AAIException
- */
- @Test
- public void testWhenMultipleEdgeLabelsBothHavePrivateEdgesButOneHasTreeEdgeAndPrivateEdge() throws AAIException, EdgeRuleNotFoundException, AmbiguousRuleChoiceException {
-
- Vertex genericVnf = graph.addVertex(
- T.label, "generic-vnf",
- T.id, "20",
- "aai-node-type", "generic-vnf",
- "vnf-id", "vnf-id-1",
- "vnf-name", "vnf-name-1"
- );
-
- Vertex modelVer = graph.addVertex(
- T.label, "model-ver",
- T.id, "21",
- "aai-node-type", "model-ver",
- "model-version-id", "modelVer1",
- "model-name", "modelName1"
- );
-
- Vertex modelPrivate = graph.addVertex(
- T.label, "model-private",
- T.id, "22",
- "aai-node-type", "model-private"
- );
-
- Vertex metadatum = graph.addVertex(
- T.label, "metadatum",
- T.id, "23",
- "aai-node-type", "metadatum"
- );
-
- GraphTraversalSource source = graph.traversal();
- edgeSer.addPrivateEdge(source, genericVnf, modelVer, null);
- edgeSer.addPrivateEdge(source, modelVer, modelPrivate, null);
- edgeSer.addTreeEdge(source, modelVer, metadatum);
-
- Optional<JsonObject> jsonObjectOptional = graphSON.formatObject(modelVer);
- JsonObject obj = jsonObjectOptional.get();
- LOGGER.info(obj.toString());
- assertNotNull(obj);
- String value = obj.toString();
- assertThat(value, not(containsString("\"private\":true")));
- assertThat(value, containsString("inventory.BelongsTo"));
- }
-
- @Test
- public void parallelThresholdCehck(){
-
- GraphSON graphSonObj2 = new GraphSON();
- assertEquals(50, graphSonObj2.parallelThreshold());
-
- }
+ *
+ * <pre>
+ * {
+ * "id": 21,
+ * "inE": {
+ * "org.onap.relationships.inventory.isA": [
+ * {
+ * "id": 10,
+ * "properties": {
+ * "aai-uuid": "oafjdsiofjs",
+ * "private": true
+ * }
+ * }
+ * ],
+ * "org.onap.relationships.inventory.BelongsTo": [
+ * {
+ * "id": 13,
+ * "properties": {
+ * "aai-uuid": "oafjdsiofjs",
+ * "private": true
+ * }
+ * },
+ * {
+ * "id": 13,
+ * "properties": {
+ * "aai-uuid": "jaosjfaisj",
+ * "private": false
+ * }
+ * }
+ * ]
+ * }
+ * "label": "model-ver",
+ * "properties": {
+ * "aai-node-type": [
+ * {
+ * "id": 5,
+ * "value": "model-ver"
+ * }
+ * ]
+ * }
+ * }
+ * </pre>
+ *
+ * @throws AAIException
+ */
+ @Test
+ public void testWhenMultipleEdgeLabelsBothHavePrivateEdgesButOneHasTreeEdgeAndPrivateEdge()
+ throws AAIException, EdgeRuleNotFoundException, AmbiguousRuleChoiceException {
+
+ Vertex genericVnf = graph.addVertex(T.label, "generic-vnf", T.id, "20", "aai-node-type", "generic-vnf",
+ "vnf-id", "vnf-id-1", "vnf-name", "vnf-name-1");
+
+ Vertex modelVer = graph.addVertex(T.label, "model-ver", T.id, "21", "aai-node-type", "model-ver",
+ "model-version-id", "modelVer1", "model-name", "modelName1");
+
+ Vertex modelPrivate = graph.addVertex(T.label, "model-private", T.id, "22", "aai-node-type", "model-private");
+
+ Vertex metadatum = graph.addVertex(T.label, "metadatum", T.id, "23", "aai-node-type", "metadatum");
+
+ GraphTraversalSource source = graph.traversal();
+ edgeSer.addPrivateEdge(source, genericVnf, modelVer, null);
+ edgeSer.addPrivateEdge(source, modelVer, modelPrivate, null);
+ edgeSer.addTreeEdge(source, modelVer, metadatum);
+
+ Optional<JsonObject> jsonObjectOptional = graphSON.formatObject(modelVer);
+ JsonObject obj = jsonObjectOptional.get();
+ LOGGER.info(obj.toString());
+ assertNotNull(obj);
+ String value = obj.toString();
+ assertThat(value, not(containsString("\"private\":true")));
+ assertThat(value, containsString("inventory.BelongsTo"));
+ }
+
+ @Test
+ public void parallelThresholdCehck() {
+
+ GraphSON graphSonObj2 = new GraphSON();
+ assertEquals(50, graphSonObj2.parallelThreshold());
+
+ }
}
diff --git a/aai-core/src/test/java/org/onap/aai/serialization/queryformats/MultiFormatTest.java b/aai-core/src/test/java/org/onap/aai/serialization/queryformats/MultiFormatTest.java
index 0df32bd3..9ac79ca8 100644
--- a/aai-core/src/test/java/org/onap/aai/serialization/queryformats/MultiFormatTest.java
+++ b/aai-core/src/test/java/org/onap/aai/serialization/queryformats/MultiFormatTest.java
@@ -17,10 +17,18 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.serialization.queryformats;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.mockito.Mockito.*;
+
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
+
+import java.io.UnsupportedEncodingException;
+
import org.apache.tinkerpop.gremlin.process.traversal.Path;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.process.traversal.step.util.Tree;
@@ -38,136 +46,129 @@ import org.onap.aai.dbmap.DBConnectionType;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.introspection.Loader;
import org.onap.aai.introspection.ModelType;
-import org.onap.aai.setup.SchemaVersion;
import org.onap.aai.serialization.db.EdgeSerializer;
-import org.onap.aai.serialization.engines.QueryStyle;
import org.onap.aai.serialization.engines.JanusGraphDBEngine;
+import org.onap.aai.serialization.engines.QueryStyle;
import org.onap.aai.serialization.engines.TransactionalGraphEngine;
import org.onap.aai.serialization.queryformats.exceptions.AAIFormatQueryResultFormatNotSupported;
import org.onap.aai.serialization.queryformats.exceptions.AAIFormatVertexException;
import org.onap.aai.serialization.queryformats.utils.UrlBuilder;
+import org.onap.aai.setup.SchemaVersion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.DirtiesContext;
-import java.io.UnsupportedEncodingException;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.mockito.Mockito.*;
-
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
public class MultiFormatTest extends AAISetup {
- @Mock
- private UrlBuilder urlBuilder;
-
- private Graph graph;
- private TransactionalGraphEngine dbEngine;
- private Loader loader;
- private IdURL idFormat;
- private final ModelType factoryType = ModelType.MOXY;
- @Autowired
- private EdgeSerializer rules;
- private Tree<?> resultTree;
- private Path resultPath;
- private SchemaVersion version;
- private JsonObject expectedTreeIdFormat = new JsonParser()
- .parse("{\"nodes\":[{\"resource-type\":\"generic-vnf\",\"nodes\":[{\"resource-type\":\"vserver\",\"nodes\":[{\"resource-type\":\"pserver\"}]},{\"resource-type\":\"pserver\",\"nodes\":[{\"resource-type\":\"complex\"}]}]}]}").getAsJsonObject();
- private JsonObject expectedPathIdFormat = new JsonParser()
- .parse("{\"path\":[{\"resource-type\":\"generic-vnf\"},{\"resource-type\":\"vserver\"},{\"resource-type\":\"pserver\"},{\"resource-type\":\"complex\"}]}").getAsJsonObject();
-
-
-
- @Before
- public void setUp() throws Exception {
-
- version = schemaVersions.getAppRootVersion();
- MockitoAnnotations.initMocks(this);
-
- graph = TinkerGraph.open();
-
- 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);
-
- resultTree = graph.traversal().V("0").out().out().tree().next();
- resultPath = graph.traversal().V("0").out().hasId("1").out().hasId("2").out().hasId("3").path().next();
- }
-
- @Test
- public void testTreeResultQueryIdFormat()
- throws AAIFormatVertexException, AAIException, AAIFormatQueryResultFormatNotSupported {
-
- createLoaderEngineSetup();
- idFormat = new IdURL(loader, urlBuilder);
-
- assertNotNull(dbEngine.tx());
- assertNotNull(dbEngine.asAdmin());
-
- JsonObject json = idFormat.formatObject(resultTree).get();
-
- assertEquals(this.expectedTreeIdFormat, json);
-
- }
-
- @Test
- public void testPathResultQueryIdFormat()
- throws AAIFormatVertexException, AAIException, AAIFormatQueryResultFormatNotSupported {
-
- createLoaderEngineSetup();
- idFormat = new IdURL(loader, urlBuilder);
-
- assertNotNull(dbEngine.tx());
- assertNotNull(dbEngine.asAdmin());
-
- JsonObject json = idFormat.formatObject(resultPath).get();
-
- assertEquals(this.expectedPathIdFormat, json);
-
- }
-
-
- @Test(expected = AAIFormatQueryResultFormatNotSupported.class)
- public void testThrowsExceptionIfObjectNotSupported() throws AAIFormatVertexException,
- AAIException, UnsupportedEncodingException, AAIFormatQueryResultFormatNotSupported {
-
- loader = mock(Loader.class);
- idFormat = new IdURL(loader, urlBuilder);
- idFormat.formatObject(new String());
- }
-
- public void createLoaderEngineSetup() {
-
- if (loader == null) {
- loader = loaderFactory.createLoaderForVersion(factoryType,version);
- //loader = LoaderFactory.createLoaderForVersion(factoryType, version);
- dbEngine = spy(new JanusGraphDBEngine(QueryStyle.TRAVERSAL, DBConnectionType.CACHED, loader));
-
- TransactionalGraphEngine.Admin spyAdmin = spy(dbEngine.asAdmin());
-
- when(dbEngine.tx()).thenReturn(graph);
- when(dbEngine.asAdmin()).thenReturn(spyAdmin);
-
- when(spyAdmin.getReadOnlyTraversalSource())
- .thenReturn(graph.traversal(GraphTraversalSource.build().with(ReadOnlyStrategy.instance())));
- when(spyAdmin.getTraversalSource()).thenReturn(graph.traversal());
- }
- }
+ @Mock
+ private UrlBuilder urlBuilder;
+
+ private Graph graph;
+ private TransactionalGraphEngine dbEngine;
+ private Loader loader;
+ private IdURL idFormat;
+ private final ModelType factoryType = ModelType.MOXY;
+ @Autowired
+ private EdgeSerializer rules;
+ private Tree<?> resultTree;
+ private Path resultPath;
+ private SchemaVersion version;
+ private JsonObject expectedTreeIdFormat = new JsonParser().parse(
+ "{\"nodes\":[{\"resource-type\":\"generic-vnf\",\"nodes\":[{\"resource-type\":\"vserver\",\"nodes\":[{\"resource-type\":\"pserver\"}]},{\"resource-type\":\"pserver\",\"nodes\":[{\"resource-type\":\"complex\"}]}]}]}")
+ .getAsJsonObject();
+ private JsonObject expectedPathIdFormat = new JsonParser().parse(
+ "{\"path\":[{\"resource-type\":\"generic-vnf\"},{\"resource-type\":\"vserver\"},{\"resource-type\":\"pserver\"},{\"resource-type\":\"complex\"}]}")
+ .getAsJsonObject();
+
+ @Before
+ public void setUp() throws Exception {
+
+ version = schemaVersions.getAppRootVersion();
+ MockitoAnnotations.initMocks(this);
+
+ graph = TinkerGraph.open();
+
+ 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);
+
+ resultTree = graph.traversal().V("0").out().out().tree().next();
+ resultPath = graph.traversal().V("0").out().hasId("1").out().hasId("2").out().hasId("3").path().next();
+ }
+
+ @Test
+ public void testTreeResultQueryIdFormat()
+ throws AAIFormatVertexException, AAIException, AAIFormatQueryResultFormatNotSupported {
+
+ createLoaderEngineSetup();
+ idFormat = new IdURL(loader, urlBuilder);
+
+ assertNotNull(dbEngine.tx());
+ assertNotNull(dbEngine.asAdmin());
+
+ JsonObject json = idFormat.formatObject(resultTree).get();
+
+ assertEquals(this.expectedTreeIdFormat, json);
+
+ }
+
+ @Test
+ public void testPathResultQueryIdFormat()
+ throws AAIFormatVertexException, AAIException, AAIFormatQueryResultFormatNotSupported {
+
+ createLoaderEngineSetup();
+ idFormat = new IdURL(loader, urlBuilder);
+
+ assertNotNull(dbEngine.tx());
+ assertNotNull(dbEngine.asAdmin());
+
+ JsonObject json = idFormat.formatObject(resultPath).get();
+
+ assertEquals(this.expectedPathIdFormat, json);
+
+ }
+
+ @Test(expected = AAIFormatQueryResultFormatNotSupported.class)
+ public void testThrowsExceptionIfObjectNotSupported() throws AAIFormatVertexException, AAIException,
+ UnsupportedEncodingException, AAIFormatQueryResultFormatNotSupported {
+
+ loader = mock(Loader.class);
+ idFormat = new IdURL(loader, urlBuilder);
+ idFormat.formatObject(new String());
+ }
+
+ public void createLoaderEngineSetup() {
+
+ if (loader == null) {
+ loader = loaderFactory.createLoaderForVersion(factoryType, version);
+ // loader = LoaderFactory.createLoaderForVersion(factoryType, version);
+ dbEngine = spy(new JanusGraphDBEngine(QueryStyle.TRAVERSAL, DBConnectionType.CACHED, loader));
+
+ TransactionalGraphEngine.Admin spyAdmin = spy(dbEngine.asAdmin());
+
+ when(dbEngine.tx()).thenReturn(graph);
+ when(dbEngine.asAdmin()).thenReturn(spyAdmin);
+
+ when(spyAdmin.getReadOnlyTraversalSource())
+ .thenReturn(graph.traversal(GraphTraversalSource.build().with(ReadOnlyStrategy.instance())));
+ when(spyAdmin.getTraversalSource()).thenReturn(graph.traversal());
+ }
+ }
}
diff --git a/aai-core/src/test/java/org/onap/aai/serialization/queryformats/QueryFormatTestHelper.java b/aai-core/src/test/java/org/onap/aai/serialization/queryformats/QueryFormatTestHelper.java
index 609de5ff..f05e36dd 100644
--- a/aai-core/src/test/java/org/onap/aai/serialization/queryformats/QueryFormatTestHelper.java
+++ b/aai-core/src/test/java/org/onap/aai/serialization/queryformats/QueryFormatTestHelper.java
@@ -17,8 +17,16 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.serialization.queryformats;
+import static org.mockito.Matchers.isA;
+import static org.mockito.Mockito.when;
+
+import java.io.IOException;
+import java.lang.reflect.Field;
+import java.lang.reflect.Modifier;
+
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.io.IoCore;
@@ -29,46 +37,38 @@ import org.onap.aai.db.props.AAIProperties;
import org.onap.aai.serialization.queryformats.exceptions.AAIFormatVertexException;
import org.onap.aai.serialization.queryformats.utils.UrlBuilder;
-import java.io.IOException;
-import java.lang.reflect.Field;
-import java.lang.reflect.Modifier;
+public class QueryFormatTestHelper {
-import static org.mockito.Matchers.isA;
-import static org.mockito.Mockito.when;
+ public static final String testResources = "src/test/resources/org.onap.aai/serialization/queryformats/";
+ public static final String graphsonResources =
+ "src/test/resources/org.onap.aai/serialization/queryformats/graphson/";
-public class QueryFormatTestHelper {
+ public static void mockPathed(UrlBuilder mock) throws AAIFormatVertexException {
+ Answer<String> answer = new Answer<String>() {
+ public String answer(InvocationOnMock invocation) throws Throwable {
+ Vertex v = invocation.getArgumentAt(0, Vertex.class);
+
+ return v.<String>property(AAIProperties.AAI_URI).orElse("urimissing");
+ }
+ };
+ when(mock.pathed(isA(Vertex.class))).thenAnswer(answer);
+
+ }
+
+ public static Graph loadGraphson(String fileName) throws IOException {
+ final Graph graph = TinkerGraph.open();
+ graph.io(IoCore.graphson()).readGraph(QueryFormatTestHelper.graphsonResources + fileName);
-
- public static final String testResources = "src/test/resources/org.onap.aai/serialization/queryformats/";
- public static final String graphsonResources = "src/test/resources/org.onap.aai/serialization/queryformats/graphson/";
+ return graph;
+ }
-
- public static void mockPathed(UrlBuilder mock) throws AAIFormatVertexException {
- Answer<String> answer = new Answer<String>() {
- public String answer(InvocationOnMock invocation) throws Throwable {
- Vertex v = invocation.getArgumentAt(0, Vertex.class);
-
- return v.<String>property(AAIProperties.AAI_URI).orElse("urimissing");
- }
- };
- when(mock.pathed(isA(Vertex.class))).thenAnswer(answer);
+ public static void setFinalStatic(Field field, Object newValue) throws Exception {
+ field.setAccessible(true);
+ // remove final modifier from field
+ Field modifiersField = Field.class.getDeclaredField("modifiers");
+ modifiersField.setAccessible(true);
+ modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
+ field.set(null, newValue);
+ }
- }
-
- public static Graph loadGraphson(String fileName) throws IOException {
- final Graph graph = TinkerGraph.open();
- graph.io(IoCore.graphson()).readGraph(QueryFormatTestHelper.graphsonResources + fileName);
-
- return graph;
- }
-
- public static void setFinalStatic(Field field, Object newValue) throws Exception {
- field.setAccessible(true);
- // remove final modifier from field
- Field modifiersField = Field.class.getDeclaredField("modifiers");
- modifiersField.setAccessible(true);
- modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
- field.set(null, newValue);
- }
-
}
diff --git a/aai-core/src/test/java/org/onap/aai/serialization/queryformats/RawFormatTest.java b/aai-core/src/test/java/org/onap/aai/serialization/queryformats/RawFormatTest.java
index c2d5e3cd..2d8c66c3 100644
--- a/aai-core/src/test/java/org/onap/aai/serialization/queryformats/RawFormatTest.java
+++ b/aai-core/src/test/java/org/onap/aai/serialization/queryformats/RawFormatTest.java
@@ -17,8 +17,13 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.serialization.queryformats;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.when;
+
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.process.traversal.strategy.verification.ReadOnlyStrategy;
import org.apache.tinkerpop.gremlin.structure.Graph;
@@ -46,94 +51,98 @@ import org.onap.aai.setup.SchemaVersion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.DirtiesContext;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.when;
-
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
public class RawFormatTest extends AAISetup {
- @Mock
- private UrlBuilder urlBuilder;
-
- private Graph graph;
- private TransactionalGraphEngine dbEngine;
- private Loader loader;
- private RawFormat rawFormat;
- private final ModelType factoryType = ModelType.MOXY;
-
- @Autowired
- private EdgeSerializer rules;
-
- private SchemaVersion version;
- private Vertex pserver;
- private Vertex complex;
-
- private DBSerializer serializer;
-
- @Before
- public void setUp() throws Exception {
-
- version = schemaVersions.getDefaultVersion();
-
- MockitoAnnotations.initMocks(this);
-
- graph = TinkerGraph.open();
-
- 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");
-
- GraphTraversalSource g = graph.traversal();
- rules.addEdge(g, pserver1, complex1);
-
- pserver = pserver1;
- complex = complex1;
-
- System.setProperty("AJSC_HOME", ".");
- System.setProperty("BUNDLECONFIG_DIR", "src/test/resources/bundleconfig-local");
-
- createLoaderEngineSetup();
- }
-
- @Test
- public void verifyPserverRelatedToHasEdgeLabel () throws AAIFormatVertexException, AAIException, AAIFormatQueryResultFormatNotSupported {
- assertTrue(rawFormat.createRelationshipObject(pserver).get(0).getAsJsonObject().get("relationship-label").getAsString().equals("org.onap.relationships.inventory.LocatedIn"));
- }
-
- @Test
- public void verifyPserverRelatedToComplexLabel () throws AAIFormatVertexException, AAIException, AAIFormatQueryResultFormatNotSupported {
- assertTrue(rawFormat.createRelationshipObject(pserver).get(0).getAsJsonObject().get("node-type").getAsString().equals("complex"));
- }
-
- @Test
- public void verifyComplexRelatedToHasEdgeLabel () throws AAIFormatVertexException, AAIException, AAIFormatQueryResultFormatNotSupported {
- assertTrue(rawFormat.createRelationshipObject(complex).get(0).getAsJsonObject().get("relationship-label").getAsString().equals("org.onap.relationships.inventory.LocatedIn"));
- }
-
- @Test
- public void verifyComplexRelatedToPserverLabel () throws AAIFormatVertexException, AAIException, AAIFormatQueryResultFormatNotSupported {
- assertTrue(rawFormat.createRelationshipObject(complex).get(0).getAsJsonObject().get("node-type").getAsString().equals("pserver"));
- }
-
- public void createLoaderEngineSetup() throws AAIException {
-
- if (loader == null) {
- loader = loaderFactory.createLoaderForVersion(factoryType, version);
- //loader = LoaderFactory.createLoaderForVersion(factoryType, version);
- dbEngine = spy(new JanusGraphDBEngine(QueryStyle.TRAVERSAL, DBConnectionType.CACHED, loader));
- serializer = new DBSerializer(version, dbEngine, factoryType, "Junit");
- rawFormat = new RawFormat.Builder(loader, serializer, urlBuilder).build();
-
- TransactionalGraphEngine.Admin spyAdmin = spy(dbEngine.asAdmin());
-
- when(dbEngine.tx()).thenReturn(graph);
- when(dbEngine.asAdmin()).thenReturn(spyAdmin);
-
- when(spyAdmin.getReadOnlyTraversalSource())
- .thenReturn(graph.traversal(GraphTraversalSource.build().with(ReadOnlyStrategy.instance())));
- when(spyAdmin.getTraversalSource()).thenReturn(graph.traversal());
- }
- }
+ @Mock
+ private UrlBuilder urlBuilder;
+
+ private Graph graph;
+ private TransactionalGraphEngine dbEngine;
+ private Loader loader;
+ private RawFormat rawFormat;
+ private final ModelType factoryType = ModelType.MOXY;
+
+ @Autowired
+ private EdgeSerializer rules;
+
+ private SchemaVersion version;
+ private Vertex pserver;
+ private Vertex complex;
+
+ private DBSerializer serializer;
+
+ @Before
+ public void setUp() throws Exception {
+
+ version = schemaVersions.getDefaultVersion();
+
+ MockitoAnnotations.initMocks(this);
+
+ graph = TinkerGraph.open();
+
+ 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");
+
+ GraphTraversalSource g = graph.traversal();
+ rules.addEdge(g, pserver1, complex1);
+
+ pserver = pserver1;
+ complex = complex1;
+
+ System.setProperty("AJSC_HOME", ".");
+ System.setProperty("BUNDLECONFIG_DIR", "src/test/resources/bundleconfig-local");
+
+ createLoaderEngineSetup();
+ }
+
+ @Test
+ public void verifyPserverRelatedToHasEdgeLabel()
+ throws AAIFormatVertexException, AAIException, AAIFormatQueryResultFormatNotSupported {
+ assertTrue(rawFormat.createRelationshipObject(pserver).get(0).getAsJsonObject().get("relationship-label")
+ .getAsString().equals("org.onap.relationships.inventory.LocatedIn"));
+ }
+
+ @Test
+ public void verifyPserverRelatedToComplexLabel()
+ throws AAIFormatVertexException, AAIException, AAIFormatQueryResultFormatNotSupported {
+ assertTrue(rawFormat.createRelationshipObject(pserver).get(0).getAsJsonObject().get("node-type").getAsString()
+ .equals("complex"));
+ }
+
+ @Test
+ public void verifyComplexRelatedToHasEdgeLabel()
+ throws AAIFormatVertexException, AAIException, AAIFormatQueryResultFormatNotSupported {
+ assertTrue(rawFormat.createRelationshipObject(complex).get(0).getAsJsonObject().get("relationship-label")
+ .getAsString().equals("org.onap.relationships.inventory.LocatedIn"));
+ }
+
+ @Test
+ public void verifyComplexRelatedToPserverLabel()
+ throws AAIFormatVertexException, AAIException, AAIFormatQueryResultFormatNotSupported {
+ assertTrue(rawFormat.createRelationshipObject(complex).get(0).getAsJsonObject().get("node-type").getAsString()
+ .equals("pserver"));
+ }
+
+ public void createLoaderEngineSetup() throws AAIException {
+
+ if (loader == null) {
+ loader = loaderFactory.createLoaderForVersion(factoryType, version);
+ // loader = LoaderFactory.createLoaderForVersion(factoryType, version);
+ dbEngine = spy(new JanusGraphDBEngine(QueryStyle.TRAVERSAL, DBConnectionType.CACHED, loader));
+ serializer = new DBSerializer(version, dbEngine, factoryType, "Junit");
+ rawFormat = new RawFormat.Builder(loader, serializer, urlBuilder).build();
+
+ TransactionalGraphEngine.Admin spyAdmin = spy(dbEngine.asAdmin());
+
+ when(dbEngine.tx()).thenReturn(graph);
+ when(dbEngine.asAdmin()).thenReturn(spyAdmin);
+
+ when(spyAdmin.getReadOnlyTraversalSource())
+ .thenReturn(graph.traversal(GraphTraversalSource.build().with(ReadOnlyStrategy.instance())));
+ when(spyAdmin.getTraversalSource()).thenReturn(graph.traversal());
+ }
+ }
}
diff --git a/aai-core/src/test/java/org/onap/aai/serialization/queryformats/ResourceFormatTest.java b/aai-core/src/test/java/org/onap/aai/serialization/queryformats/ResourceFormatTest.java
index d522ef5c..1a301b33 100644
--- a/aai-core/src/test/java/org/onap/aai/serialization/queryformats/ResourceFormatTest.java
+++ b/aai-core/src/test/java/org/onap/aai/serialization/queryformats/ResourceFormatTest.java
@@ -17,9 +17,20 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.serialization.queryformats;
+import static org.junit.Assert.*;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.when;
+
import com.google.gson.JsonObject;
+
+import java.util.Arrays;
+
+import javax.ws.rs.core.MultivaluedHashMap;
+import javax.ws.rs.core.MultivaluedMap;
+
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.process.traversal.strategy.verification.ReadOnlyStrategy;
import org.apache.tinkerpop.gremlin.structure.Graph;
@@ -43,122 +54,106 @@ import org.onap.aai.serialization.queryformats.exceptions.AAIFormatVertexExcepti
import org.onap.aai.serialization.queryformats.utils.UrlBuilder;
import org.springframework.test.annotation.DirtiesContext;
-import javax.ws.rs.core.MultivaluedHashMap;
-import javax.ws.rs.core.MultivaluedMap;
-import java.util.Arrays;
-
-import static org.junit.Assert.*;
-import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.when;
-
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
public class ResourceFormatTest extends AAISetup {
- @Mock
- private UrlBuilder urlBuilder;
+ @Mock
+ private UrlBuilder urlBuilder;
- private Graph graph;
- private TransactionalGraphEngine dbEngine;
- private Loader loader;
- private DBSerializer serializer;
- private Resource resource;
- private Vertex vfModule;
- private Vertex unknown;
- private final ModelType factoryType = ModelType.MOXY;
+ private Graph graph;
+ private TransactionalGraphEngine dbEngine;
+ private Loader loader;
+ private DBSerializer serializer;
+ private Resource resource;
+ private Vertex vfModule;
+ private Vertex unknown;
+ private final ModelType factoryType = ModelType.MOXY;
- @Before
- public void setUp() throws Exception {
+ @Before
+ public void setUp() throws Exception {
- MockitoAnnotations.initMocks(this);
+ MockitoAnnotations.initMocks(this);
- graph = TinkerGraph.open();
+ graph = TinkerGraph.open();
- 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"
- );
+ 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");
- unknown = graph.addVertex(T.label, "unknown", T.id, "1", "aai-node-type", "unknown", "vserver-id",
- "vserver-id-1", "vserver-name", "vserver-name-1");
- }
+ unknown = graph.addVertex(T.label, "unknown", T.id, "1", "aai-node-type", "unknown", "vserver-id",
+ "vserver-id-1", "vserver-name", "vserver-name-1");
+ }
- @Test
- public void testCreatePropertiesObjectReturnsProperProperties() throws AAIFormatVertexException, AAIException {
+ @Test
+ public void testCreatePropertiesObjectReturnsProperProperties() throws AAIFormatVertexException, AAIException {
- createLoaderEngineSetup();
- serializer = new DBSerializer(schemaVersions.getAppRootVersion(), dbEngine, factoryType, "Junit");
- resource = new Resource.Builder(loader, serializer, urlBuilder).build();
+ createLoaderEngineSetup();
+ serializer = new DBSerializer(schemaVersions.getAppRootVersion(), dbEngine, factoryType, "Junit");
+ resource = new Resource.Builder(loader, serializer, urlBuilder).build();
- assertNotNull(dbEngine.tx());
- assertNotNull(dbEngine.asAdmin());
+ assertNotNull(dbEngine.tx());
+ assertNotNull(dbEngine.asAdmin());
- JsonObject json = resource.getJsonFromVertex(vfModule).get();
+ JsonObject json = resource.getJsonFromVertex(vfModule).get();
- assertTrue(json.getAsJsonObject("vf-module").has("model-invariant-id"));
- assertTrue(json.getAsJsonObject("vf-module").has("model-version-id"));
+ assertTrue(json.getAsJsonObject("vf-module").has("model-invariant-id"));
+ assertTrue(json.getAsJsonObject("vf-module").has("model-version-id"));
- assertFalse(json.getAsJsonObject("vf-module").has("model-invariant-id-local"));
- assertFalse(json.getAsJsonObject("vf-module").has("model-version-id-local"));
+ assertFalse(json.getAsJsonObject("vf-module").has("model-invariant-id-local"));
+ assertFalse(json.getAsJsonObject("vf-module").has("model-version-id-local"));
- }
+ }
- @Test
- public void testUnknownVertex() throws AAIFormatVertexException, AAIException {
+ @Test
+ public void testUnknownVertex() throws AAIFormatVertexException, AAIException {
- createLoaderEngineSetup();
- serializer = new DBSerializer(schemaVersions.getAppRootVersion(), dbEngine, factoryType, "Junit");
- resource = new Resource.Builder(loader, serializer, urlBuilder).build();
+ createLoaderEngineSetup();
+ serializer = new DBSerializer(schemaVersions.getAppRootVersion(), dbEngine, factoryType, "Junit");
+ resource = new Resource.Builder(loader, serializer, urlBuilder).build();
- assertNotNull(dbEngine.tx());
- assertNotNull(dbEngine.asAdmin());
+ assertNotNull(dbEngine.tx());
+ assertNotNull(dbEngine.asAdmin());
- assertFalse(resource.getJsonFromVertex(unknown).isPresent());
+ assertFalse(resource.getJsonFromVertex(unknown).isPresent());
- }
+ }
- @Test
- public void testFormattingUnknownVertex() throws AAIFormatVertexException, AAIException {
+ @Test
+ public void testFormattingUnknownVertex() throws AAIFormatVertexException, AAIException {
- createLoaderEngineSetup();
- serializer = new DBSerializer(schemaVersions.getAppRootVersion(), dbEngine, factoryType, "Junit");
+ createLoaderEngineSetup();
+ serializer = new DBSerializer(schemaVersions.getAppRootVersion(), dbEngine, factoryType, "Junit");
- FormatFactory ff = new FormatFactory(loader, serializer,schemaVersions, basePath);
- MultivaluedMap mvm = new MultivaluedHashMap();
- mvm.add("depth","0");
- Formatter formatter = ff.get(Format.resource, mvm);
+ FormatFactory ff = new FormatFactory(loader, serializer, schemaVersions, basePath);
+ MultivaluedMap mvm = new MultivaluedHashMap();
+ mvm.add("depth", "0");
+ Formatter formatter = ff.get(Format.resource, mvm);
- JsonObject json = formatter.output(Arrays.asList(unknown,vfModule));
- System.out.println(json);
+ JsonObject json = formatter.output(Arrays.asList(unknown, vfModule));
+ System.out.println(json);
- }
+ }
- public void createLoaderEngineSetup(){
+ public void createLoaderEngineSetup() {
- if(loader == null){
- loader = loaderFactory.createLoaderForVersion(factoryType, schemaVersions.getAppRootVersion());
- dbEngine = spy(new JanusGraphDBEngine(QueryStyle.TRAVERSAL, DBConnectionType.CACHED, loader));
+ if (loader == null) {
+ loader = loaderFactory.createLoaderForVersion(factoryType, schemaVersions.getAppRootVersion());
+ dbEngine = spy(new JanusGraphDBEngine(QueryStyle.TRAVERSAL, DBConnectionType.CACHED, loader));
- TransactionalGraphEngine.Admin spyAdmin = spy(dbEngine.asAdmin());
+ TransactionalGraphEngine.Admin spyAdmin = spy(dbEngine.asAdmin());
- when(dbEngine.tx()).thenReturn(graph);
- when(dbEngine.asAdmin()).thenReturn(spyAdmin);
+ when(dbEngine.tx()).thenReturn(graph);
+ when(dbEngine.asAdmin()).thenReturn(spyAdmin);
- when(spyAdmin.getReadOnlyTraversalSource()).thenReturn(graph.traversal(GraphTraversalSource.build().with(ReadOnlyStrategy.instance())));
- when(spyAdmin.getTraversalSource()).thenReturn(graph.traversal());
- }
- }
+ when(spyAdmin.getReadOnlyTraversalSource())
+ .thenReturn(graph.traversal(GraphTraversalSource.build().with(ReadOnlyStrategy.instance())));
+ when(spyAdmin.getTraversalSource()).thenReturn(graph.traversal());
+ }
+ }
}
diff --git a/aai-core/src/test/java/org/onap/aai/serialization/queryformats/ResourceWithSoTTest.java b/aai-core/src/test/java/org/onap/aai/serialization/queryformats/ResourceWithSoTTest.java
index ad28e697..75fe6ec6 100644
--- a/aai-core/src/test/java/org/onap/aai/serialization/queryformats/ResourceWithSoTTest.java
+++ b/aai-core/src/test/java/org/onap/aai/serialization/queryformats/ResourceWithSoTTest.java
@@ -17,9 +17,17 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.serialization.queryformats;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.when;
+
import com.google.gson.JsonObject;
+
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.process.traversal.strategy.verification.ReadOnlyStrategy;
import org.apache.tinkerpop.gremlin.structure.Graph;
@@ -42,12 +50,6 @@ import org.onap.aai.serialization.queryformats.exceptions.AAIFormatVertexExcepti
import org.onap.aai.serialization.queryformats.utils.UrlBuilder;
import org.onap.aai.setup.SchemaVersion;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.when;
-
public class ResourceWithSoTTest extends AAISetup {
@Mock
private UrlBuilder urlBuilder;
@@ -57,9 +59,9 @@ public class ResourceWithSoTTest extends AAISetup {
private Vertex patchVertex1;
private Vertex patchVertex2;
- private JsonObject jsonPutObj = new JsonObject() ;
- private JsonObject jsonPatchObj1 = new JsonObject() ;
- private JsonObject jsonPatchObj2 = new JsonObject() ;
+ private JsonObject jsonPutObj = new JsonObject();
+ private JsonObject jsonPatchObj1 = new JsonObject();
+ private JsonObject jsonPatchObj2 = new JsonObject();
private SchemaVersion version;
private ResourceWithSoT resourceWithSoT;
@@ -87,12 +89,8 @@ public class ResourceWithSoTTest extends AAISetup {
jsonPutObj.addProperty("last-mod-source-of-truth", "user_a");
jsonPutObj.addProperty("last-action-performed", "Created");
- putVertex = graph.addVertex(
- "aai-created-ts", timeNowInMs,
- "aai-last-mod-ts", timeNowInMs,
- "source-of-truth", "user_a",
- "last-mod-source-of-truth", "user_a"
- );
+ putVertex = graph.addVertex("aai-created-ts", timeNowInMs, "aai-last-mod-ts", timeNowInMs, "source-of-truth",
+ "user_a", "last-mod-source-of-truth", "user_a");
// PATCH / MODIFY with differing source of truths
jsonPatchObj1.addProperty("aai-created-ts", timeNowInMs);
@@ -101,12 +99,8 @@ public class ResourceWithSoTTest extends AAISetup {
jsonPatchObj1.addProperty("last-mod-source-of-truth", "user_b");
jsonPatchObj1.addProperty("last-action-performed", "Modified");
- patchVertex1 = graph.addVertex(
- "aai-created-ts", timeNowInMs,
- "aai-last-mod-ts", timeNowInMs,
- "source-of-truth", "user_a",
- "last-mod-source-of-truth", "user_b"
- );
+ patchVertex1 = graph.addVertex("aai-created-ts", timeNowInMs, "aai-last-mod-ts", timeNowInMs, "source-of-truth",
+ "user_a", "last-mod-source-of-truth", "user_b");
// PATCH / MODIFY with differing time stamps
jsonPatchObj2.addProperty("aai-created-ts", timeNowInMs);
@@ -115,12 +109,8 @@ public class ResourceWithSoTTest extends AAISetup {
jsonPatchObj2.addProperty("last-mod-source-of-truth", "user_a");
jsonPatchObj2.addProperty("last-action-performed", "Modified");
- patchVertex2 = graph.addVertex(
- "aai-created-ts", timeNowInMs,
- "aai-last-mod-ts", Long.toString(currentTimeMs + 1000),
- "source-of-truth", "user_a",
- "last-mod-source-of-truth", "user_a"
- );
+ patchVertex2 = graph.addVertex("aai-created-ts", timeNowInMs, "aai-last-mod-ts",
+ Long.toString(currentTimeMs + 1000), "source-of-truth", "user_a", "last-mod-source-of-truth", "user_a");
graph = TinkerGraph.open();
createLoaderEngineSetup();
@@ -148,7 +138,8 @@ public class ResourceWithSoTTest extends AAISetup {
JsonObject json1 = resourceWithSoT.getJsonFromVertex(patchVertex1).get();
assertEquals(jsonPatchObj1, json1);
- // Timestamps that have a large span in time difference will (likely) indicate that the transaction was not a create (thus, modify)
+ // Timestamps that have a large span in time difference will (likely) indicate that the transaction was not a
+ // create (thus, modify)
JsonObject json2 = resourceWithSoT.getJsonFromVertex(patchVertex2).get();
assertEquals(jsonPatchObj2, json2);
}
@@ -163,7 +154,7 @@ public class ResourceWithSoTTest extends AAISetup {
if (loader == null) {
loader = loaderFactory.createLoaderForVersion(factoryType, version);
- //loader = LoaderFactory.createLoaderForVersion(factoryType, version);
+ // loader = LoaderFactory.createLoaderForVersion(factoryType, version);
dbEngine = spy(new JanusGraphDBEngine(QueryStyle.TRAVERSAL, DBConnectionType.CACHED, loader));
serializer = new DBSerializer(version, dbEngine, factoryType, "Junit");
resourceWithSoT = new ResourceWithSoT.Builder(loader, serializer, urlBuilder).build();
@@ -174,7 +165,7 @@ public class ResourceWithSoTTest extends AAISetup {
when(dbEngine.asAdmin()).thenReturn(spyAdmin);
when(spyAdmin.getReadOnlyTraversalSource())
- .thenReturn(graph.traversal(GraphTraversalSource.build().with(ReadOnlyStrategy.instance())));
+ .thenReturn(graph.traversal(GraphTraversalSource.build().with(ReadOnlyStrategy.instance())));
when(spyAdmin.getTraversalSource()).thenReturn(graph.traversal());
}
}
diff --git a/aai-core/src/test/java/org/onap/aai/serialization/queryformats/SimpleFormatTest.java b/aai-core/src/test/java/org/onap/aai/serialization/queryformats/SimpleFormatTest.java
index c347bc2d..ab899c01 100644
--- a/aai-core/src/test/java/org/onap/aai/serialization/queryformats/SimpleFormatTest.java
+++ b/aai-core/src/test/java/org/onap/aai/serialization/queryformats/SimpleFormatTest.java
@@ -17,9 +17,24 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.serialization.queryformats;
+import static org.junit.Assert.*;
+import static org.mockito.Matchers.anyBoolean;
+import static org.mockito.Matchers.anyInt;
+import static org.mockito.Matchers.anyObject;
+import static org.mockito.Matchers.anyString;
+import static org.mockito.Mockito.*;
+
import com.google.gson.JsonObject;
+
+import java.io.UnsupportedEncodingException;
+import java.util.Arrays;
+
+import javax.ws.rs.core.MultivaluedHashMap;
+import javax.ws.rs.core.MultivaluedMap;
+
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.process.traversal.strategy.verification.ReadOnlyStrategy;
import org.apache.tinkerpop.gremlin.structure.Graph;
@@ -45,157 +60,138 @@ import org.onap.aai.serialization.queryformats.exceptions.AAIFormatVertexExcepti
import org.onap.aai.serialization.queryformats.utils.UrlBuilder;
import org.springframework.test.annotation.DirtiesContext;
-import javax.ws.rs.core.MultivaluedHashMap;
-import javax.ws.rs.core.MultivaluedMap;
-import java.io.UnsupportedEncodingException;
-import java.util.Arrays;
-
-import static org.junit.Assert.*;
-import static org.mockito.Matchers.anyBoolean;
-import static org.mockito.Matchers.anyInt;
-import static org.mockito.Matchers.anyObject;
-import static org.mockito.Matchers.anyString;
-import static org.mockito.Mockito.*;
-
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
public class SimpleFormatTest extends AAISetup {
- @Mock
- private UrlBuilder urlBuilder;
+ @Mock
+ private UrlBuilder urlBuilder;
- private Graph graph;
- private TransactionalGraphEngine dbEngine;
- private Loader loader;
- private DBSerializer serializer;
- private RawFormat simpleFormat;
- private Vertex vfModule;
- private Vertex unknown;
- private final ModelType factoryType = ModelType.MOXY;
+ private Graph graph;
+ private TransactionalGraphEngine dbEngine;
+ private Loader loader;
+ private DBSerializer serializer;
+ private RawFormat simpleFormat;
+ private Vertex vfModule;
+ private Vertex unknown;
+ private final ModelType factoryType = ModelType.MOXY;
-
- @Before
- public void setUp() throws Exception {
+ @Before
+ public void setUp() throws Exception {
- MockitoAnnotations.initMocks(this);
+ MockitoAnnotations.initMocks(this);
- graph = TinkerGraph.open();
+ graph = TinkerGraph.open();
- 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"
- );
+ 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");
- unknown = graph.addVertex(T.label, "unknown", T.id, "1", "aai-node-type", "unknown", "vserver-id",
- "vserver-id-1", "vserver-name", "vserver-name-1");
- }
+ unknown = graph.addVertex(T.label, "unknown", T.id, "1", "aai-node-type", "unknown", "vserver-id",
+ "vserver-id-1", "vserver-name", "vserver-name-1");
+ }
- @Test
- public void testCreatePropertiesObjectReturnsProperProperties() throws AAIFormatVertexException, AAIException {
+ @Test
+ public void testCreatePropertiesObjectReturnsProperProperties() throws AAIFormatVertexException, AAIException {
- createLoaderEngineSetup();
- serializer = new DBSerializer(schemaVersions.getRelatedLinkVersion(), dbEngine, factoryType, "Junit");
- simpleFormat = new RawFormat.Builder(loader, serializer, urlBuilder).nodesOnly(true).depth(0).modelDriven().build();
+ createLoaderEngineSetup();
+ serializer = new DBSerializer(schemaVersions.getRelatedLinkVersion(), dbEngine, factoryType, "Junit");
+ simpleFormat =
+ new RawFormat.Builder(loader, serializer, urlBuilder).nodesOnly(true).depth(0).modelDriven().build();
- assertNotNull(dbEngine.tx());
- assertNotNull(dbEngine.asAdmin());
+ assertNotNull(dbEngine.tx());
+ assertNotNull(dbEngine.asAdmin());
- JsonObject json = simpleFormat.createPropertiesObject(vfModule).get();
+ JsonObject json = simpleFormat.createPropertiesObject(vfModule).get();
- assertTrue(json.has("model-invariant-id"));
- assertTrue(json.has("model-version-id"));
+ assertTrue(json.has("model-invariant-id"));
+ assertTrue(json.has("model-version-id"));
- assertFalse(json.has("model-invariant-id-local"));
- assertFalse(json.has("model-version-id-local"));
+ assertFalse(json.has("model-invariant-id-local"));
+ assertFalse(json.has("model-version-id-local"));
- }
+ }
- @Test
- public void testUnknownVertex() throws AAIFormatVertexException, AAIException {
+ @Test
+ public void testUnknownVertex() throws AAIFormatVertexException, AAIException {
- createLoaderEngineSetup();
- serializer = new DBSerializer(schemaVersions.getRelatedLinkVersion(), dbEngine, factoryType, "Junit");
- simpleFormat = new RawFormat.Builder(loader, serializer, urlBuilder).nodesOnly(true).depth(0).modelDriven().build();
+ createLoaderEngineSetup();
+ serializer = new DBSerializer(schemaVersions.getRelatedLinkVersion(), dbEngine, factoryType, "Junit");
+ simpleFormat =
+ new RawFormat.Builder(loader, serializer, urlBuilder).nodesOnly(true).depth(0).modelDriven().build();
- assertNotNull(dbEngine.tx());
- assertNotNull(dbEngine.asAdmin());
+ assertNotNull(dbEngine.tx());
+ assertNotNull(dbEngine.asAdmin());
- assertFalse(simpleFormat.getJsonFromVertex(unknown).isPresent());
+ assertFalse(simpleFormat.getJsonFromVertex(unknown).isPresent());
- }
+ }
- @Test
- public void testFormattingUnknownVertex() throws AAIException {
+ @Test
+ public void testFormattingUnknownVertex() throws AAIException {
- createLoaderEngineSetup();
- serializer = new DBSerializer(schemaVersions.getRelatedLinkVersion(), dbEngine, factoryType, "Junit");
+ createLoaderEngineSetup();
+ serializer = new DBSerializer(schemaVersions.getRelatedLinkVersion(), dbEngine, factoryType, "Junit");
- FormatFactory ff = new FormatFactory(loader, serializer, schemaVersions, basePath);
- MultivaluedMap mvm = new MultivaluedHashMap();
- mvm.add("depth","0");
- Formatter formatter = ff.get(Format.simple, mvm);
+ FormatFactory ff = new FormatFactory(loader, serializer, schemaVersions, basePath);
+ MultivaluedMap mvm = new MultivaluedHashMap();
+ mvm.add("depth", "0");
+ Formatter formatter = ff.get(Format.simple, mvm);
- JsonObject json = formatter.output(Arrays.asList(unknown,vfModule));
-
+ JsonObject json = formatter.output(Arrays.asList(unknown, vfModule));
- }
+ }
- @Ignore
- @Test(expected = AAIFormatVertexException.class)
- public void testCreatePropertiesObjectThrowsExceptionIfSerializationFails() throws AAIFormatVertexException, AAIException, UnsupportedEncodingException {
+ @Ignore
+ @Test(expected = AAIFormatVertexException.class)
+ public void testCreatePropertiesObjectThrowsExceptionIfSerializationFails()
+ throws AAIFormatVertexException, AAIException, UnsupportedEncodingException {
- serializer = mock(DBSerializer.class);
- loader = mock(Loader.class);
+ serializer = mock(DBSerializer.class);
+ loader = mock(Loader.class);
- simpleFormat = new RawFormat.Builder(loader, serializer, urlBuilder).nodesOnly(true).depth(0).build();
+ simpleFormat = new RawFormat.Builder(loader, serializer, urlBuilder).nodesOnly(true).depth(0).build();
- when(serializer.dbToObject(anyObject(), anyObject(), anyInt(), anyBoolean(), anyString()))
- .thenThrow(new AAIException("Test Exception"));
+ when(serializer.dbToObject(anyObject(), anyObject(), anyInt(), anyBoolean(), anyString()))
+ .thenThrow(new AAIException("Test Exception"));
- simpleFormat.createPropertiesObject(vfModule);
- }
+ simpleFormat.createPropertiesObject(vfModule);
+ }
- @Ignore
- @Test(expected = AAIFormatVertexException.class)
- public void testCreatePropertiesObjectThrowsExceptionIfUnknownObject() throws AAIFormatVertexException, AAIException, UnsupportedEncodingException {
+ @Ignore
+ @Test(expected = AAIFormatVertexException.class)
+ public void testCreatePropertiesObjectThrowsExceptionIfUnknownObject()
+ throws AAIFormatVertexException, AAIException, UnsupportedEncodingException {
- loader = mock(Loader.class);
- serializer = mock(DBSerializer.class);
+ loader = mock(Loader.class);
+ serializer = mock(DBSerializer.class);
- simpleFormat = new RawFormat.Builder(loader, serializer, urlBuilder).nodesOnly(true).depth(0).build();
+ simpleFormat = new RawFormat.Builder(loader, serializer, urlBuilder).nodesOnly(true).depth(0).build();
- when(loader.introspectorFromName(anyString()))
- .thenThrow(new AAIUnknownObjectException("Test Exception"));
+ when(loader.introspectorFromName(anyString())).thenThrow(new AAIUnknownObjectException("Test Exception"));
- simpleFormat.createPropertiesObject(vfModule);
- }
+ simpleFormat.createPropertiesObject(vfModule);
+ }
- public void createLoaderEngineSetup(){
+ public void createLoaderEngineSetup() {
- if(loader == null){
- loader = loaderFactory.createLoaderForVersion(factoryType, schemaVersions.getRelatedLinkVersion());
- dbEngine = spy(new JanusGraphDBEngine(QueryStyle.TRAVERSAL, DBConnectionType.CACHED, loader));
+ if (loader == null) {
+ loader = loaderFactory.createLoaderForVersion(factoryType, schemaVersions.getRelatedLinkVersion());
+ dbEngine = spy(new JanusGraphDBEngine(QueryStyle.TRAVERSAL, DBConnectionType.CACHED, loader));
- TransactionalGraphEngine.Admin spyAdmin = spy(dbEngine.asAdmin());
+ TransactionalGraphEngine.Admin spyAdmin = spy(dbEngine.asAdmin());
- when(dbEngine.tx()).thenReturn(graph);
- when(dbEngine.asAdmin()).thenReturn(spyAdmin);
+ when(dbEngine.tx()).thenReturn(graph);
+ when(dbEngine.asAdmin()).thenReturn(spyAdmin);
- when(spyAdmin.getReadOnlyTraversalSource()).thenReturn(graph.traversal(GraphTraversalSource.build().with(ReadOnlyStrategy.instance())));
- when(spyAdmin.getTraversalSource()).thenReturn(graph.traversal());
- }
- }
+ when(spyAdmin.getReadOnlyTraversalSource())
+ .thenReturn(graph.traversal(GraphTraversalSource.build().with(ReadOnlyStrategy.instance())));
+ when(spyAdmin.getTraversalSource()).thenReturn(graph.traversal());
+ }
+ }
}
diff --git a/aai-core/src/test/java/org/onap/aai/serialization/queryformats/utils/QueryParamInjectorTest.java b/aai-core/src/test/java/org/onap/aai/serialization/queryformats/utils/QueryParamInjectorTest.java
index 20f7868d..0b689d88 100644
--- a/aai-core/src/test/java/org/onap/aai/serialization/queryformats/utils/QueryParamInjectorTest.java
+++ b/aai-core/src/test/java/org/onap/aai/serialization/queryformats/utils/QueryParamInjectorTest.java
@@ -17,8 +17,14 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.serialization.queryformats.utils;
+import static org.junit.Assert.assertEquals;
+
+import javax.ws.rs.core.MultivaluedHashMap;
+import javax.ws.rs.core.MultivaluedMap;
+
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
@@ -28,31 +34,28 @@ import org.onap.aai.serialization.db.DBSerializer;
import org.onap.aai.serialization.queryformats.Resource;
import org.onap.aai.serialization.queryformats.Resource.Builder;
-import javax.ws.rs.core.MultivaluedHashMap;
-import javax.ws.rs.core.MultivaluedMap;
+public class QueryParamInjectorTest {
-import static org.junit.Assert.assertEquals;
+ @Mock
+ private Loader loader;
+ @Mock
+ private DBSerializer serializer;
+ @Mock
+ private UrlBuilder urlBuilder;
-public class QueryParamInjectorTest {
+ @Test
+ public void test() throws AAIException {
+ MockitoAnnotations.initMocks(this);
+ QueryParamInjector injector = QueryParamInjector.getInstance();
+
+ Builder b = new Builder(loader, serializer, urlBuilder);
+ MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
+ params.putSingle("nodesOnly", "true");
+ params.putSingle("depth", "10");
+ params.putSingle("invalid", "1000");
+ injector.injectParams(b, params);
-
- @Mock private Loader loader;
- @Mock private DBSerializer serializer;
- @Mock private UrlBuilder urlBuilder;
-
- @Test
- public void test() throws AAIException {
- MockitoAnnotations.initMocks(this);
- QueryParamInjector injector = QueryParamInjector.getInstance();
-
- Builder b = new Builder(loader, serializer, urlBuilder);
- MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
- params.putSingle("nodesOnly", "true");
- params.putSingle("depth", "10");
- params.putSingle("invalid", "1000");
- injector.injectParams(b, params);
-
- assertEquals("is nodes only", true, b.isNodesOnly());
- assertEquals("is depth 10", 10, b.getDepth());
- }
+ assertEquals("is nodes only", true, b.isNodesOnly());
+ assertEquals("is depth 10", 10, b.getDepth());
+ }
}
diff --git a/aai-core/src/test/java/org/onap/aai/serialization/queryformats/utils/UrlBuilderTest.java b/aai-core/src/test/java/org/onap/aai/serialization/queryformats/utils/UrlBuilderTest.java
index 397999e2..08d29cd3 100644
--- a/aai-core/src/test/java/org/onap/aai/serialization/queryformats/utils/UrlBuilderTest.java
+++ b/aai-core/src/test/java/org/onap/aai/serialization/queryformats/utils/UrlBuilderTest.java
@@ -17,8 +17,17 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.serialization.queryformats.utils;
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.when;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URI;
+import java.net.URISyntaxException;
+
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.junit.Before;
import org.junit.Test;
@@ -30,70 +39,62 @@ import org.onap.aai.serialization.queryformats.exceptions.AAIFormatVertexExcepti
import org.onap.aai.setup.SchemaVersion;
import org.onap.aai.util.AAIConstants;
-import java.io.UnsupportedEncodingException;
-import java.net.URI;
-import java.net.URISyntaxException;
+public class UrlBuilderTest extends AAISetup {
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Matchers.any;
-import static org.mockito.Mockito.when;
+ @Mock
+ private DBSerializer serializer;
+ @Mock
+ private Vertex v;
-public class UrlBuilderTest extends AAISetup {
+ private static final String uri = "/test/uri";
+ private static final Object vId = new Long(123);
+ private static final String protocolAndHost = "http://localhost/aai/";
+
+ @Before
+ public void before() throws UnsupportedEncodingException, URISyntaxException {
+ MockitoAnnotations.initMocks(this);
+ when(serializer.getURIForVertex(any(Vertex.class))).thenReturn(new URI(uri));
+ when(v.id()).thenReturn(vId);
+ }
+
+ @Test
+ public void v11Pathed() throws AAIFormatVertexException {
+ SchemaVersion version = new SchemaVersion("v11");
+ UrlBuilder builder = new UrlBuilder(version, serializer, protocolAndHost, schemaVersions, basePath);
+ String result = builder.pathed(v);
+
+ assertEquals("has no protocol and host", basePath + "/" + version + uri, result);
+
+ }
+
+ @Test
+ public void v11Id() {
+ SchemaVersion version = new SchemaVersion("v11");
+ UrlBuilder builder = new UrlBuilder(version, serializer, protocolAndHost, schemaVersions, basePath);
+ String result = builder.id(v);
+
+ assertEquals("has no protocol and host", basePath + "/" + version + "/resources/id/" + vId, result);
+
+ }
+
+ @Test
+ public void beforeV11Pathed() throws AAIFormatVertexException {
+ SchemaVersion version = new SchemaVersion("v10");
+ UrlBuilder builder = new UrlBuilder(version, serializer, protocolAndHost, schemaVersions, basePath);
+ String result = builder.pathed(v);
+
+ assertEquals("has protocol and host", protocolAndHost + version + uri, result);
+
+ }
+
+ @Test
+ public void beforeV11Id() {
+ SchemaVersion version = new SchemaVersion("v10");
+ UrlBuilder builder = new UrlBuilder(version, serializer, protocolAndHost, schemaVersions, basePath);
+ String result = builder.id(v);
+
+ assertEquals("has protocol and host", protocolAndHost + version + "/resources/id/" + vId, result);
+
+ }
- @Mock
- private DBSerializer serializer;
- @Mock
- private Vertex v;
-
- private static final String uri = "/test/uri";
- private static final Object vId = new Long(123);
- private static final String protocolAndHost = "http://localhost/aai/";
-
- @Before
- public void before() throws UnsupportedEncodingException, URISyntaxException {
- MockitoAnnotations.initMocks(this);
- when(serializer.getURIForVertex(any(Vertex.class))).thenReturn(new URI(uri));
- when(v.id()).thenReturn(vId);
- }
-
- @Test
- public void v11Pathed() throws AAIFormatVertexException {
- SchemaVersion version = new SchemaVersion("v11");
- UrlBuilder builder = new UrlBuilder(version, serializer, protocolAndHost, schemaVersions, basePath);
- String result = builder.pathed(v);
-
- assertEquals("has no protocol and host", basePath + "/"+ version + uri, result);
-
- }
-
- @Test
- public void v11Id() {
- SchemaVersion version = new SchemaVersion("v11");
- UrlBuilder builder = new UrlBuilder(version, serializer, protocolAndHost, schemaVersions, basePath);
- String result = builder.id(v);
-
- assertEquals("has no protocol and host", basePath + "/"+ version + "/resources/id/" + vId, result);
-
- }
-
- @Test
- public void beforeV11Pathed() throws AAIFormatVertexException {
- SchemaVersion version = new SchemaVersion("v10");
- UrlBuilder builder = new UrlBuilder(version, serializer, protocolAndHost, schemaVersions, basePath);
- String result = builder.pathed(v);
-
- assertEquals("has protocol and host", protocolAndHost + version + uri, result);
-
- }
-
- @Test
- public void beforeV11Id() {
- SchemaVersion version = new SchemaVersion("v10");
- UrlBuilder builder = new UrlBuilder(version, serializer, protocolAndHost, schemaVersions, basePath);
- String result = builder.id(v);
-
- assertEquals("has protocol and host", protocolAndHost + version + "/resources/id/" + vId, result);
-
- }
-
}
diff --git a/aai-core/src/test/java/org/onap/aai/serialization/tinkerpop/TreeBackedVertexTest.java b/aai-core/src/test/java/org/onap/aai/serialization/tinkerpop/TreeBackedVertexTest.java
index 6d17674a..8eed7c64 100644
--- a/aai-core/src/test/java/org/onap/aai/serialization/tinkerpop/TreeBackedVertexTest.java
+++ b/aai-core/src/test/java/org/onap/aai/serialization/tinkerpop/TreeBackedVertexTest.java
@@ -17,8 +17,11 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.serialization.tinkerpop;
+import static org.junit.Assert.assertEquals;
+
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.process.traversal.step.util.Tree;
import org.apache.tinkerpop.gremlin.structure.*;
@@ -29,123 +32,124 @@ import org.junit.Test;
import org.onap.aai.edges.enums.EdgeProperty;
import org.onap.aai.serialization.engines.query.GraphTraversalQueryEngine;
-import static org.junit.Assert.assertEquals;
-
@Ignore
public class TreeBackedVertexTest {
- private Graph graph = TinkerGraph.open();
- private Object startKey = null;
- private Tree<Element> tree = null;
- private Tree<Element> treeDepth1 = null;
- private Tree<Element> treeDepth0NodeOnly = null;
-
- @Before
- public void configure() {
- GraphTraversalSource g = graph.traversal();
-
- startKey = g.addV(T.label, "vserver").as("v1").property("test", "hello")
- .addV(T.label, "vserver").as("v2")
- .addV(T.label, "interface").property("name", "interface 1").as("v10").addInE("hasChild", "v2").property(EdgeProperty.CONTAINS.toString(), true)
- .addV(T.label, "pserver").property("name", "pserver 1").as("v4").addOutE("runsOn", "v1").property(EdgeProperty.CONTAINS.toString(), false)
- .addV(T.label, "interface").property("name", "interface 2").as("v3").addInE("hasChild", "v1").property(EdgeProperty.CONTAINS.toString(), true)
- .addV(T.label, "address").property("name", "address 1").addInE("hasChild", "v3").property(EdgeProperty.CONTAINS.toString(), true)
- .addV(T.label, "address").property("name", "address 2").addInE("hasChild", "v3").property(EdgeProperty.CONTAINS.toString(), true)
- .addV(T.label, "complex").property("name", "complex 1").addInE("locatedIn", "v4").property(EdgeProperty.CONTAINS.toString(), false)
- .addV(T.label, "interface").property("name", "interface 3").addInE("hasChild", "v4").property(EdgeProperty.CONTAINS.toString(), true)
- .addV(T.label, "subnet").property("name", "subnet 1").as("v5").addInE("in", "v3").property(EdgeProperty.CONTAINS.toString(), false)
- .addV(T.label, "address").property("name", "address 3").as("v6").addInE("hasChild", "v5").property(EdgeProperty.CONTAINS.toString(), true)
- .select("v1").next();
-
- tree = new GraphTraversalQueryEngine(g).findSubGraph((Vertex)startKey);
- treeDepth1 = new GraphTraversalQueryEngine(g).findSubGraph((Vertex)startKey, 1, false);
- treeDepth0NodeOnly = new GraphTraversalQueryEngine(g).findSubGraph((Vertex)startKey, 0, true);
- }
-
- @Ignore
- @Test
- public void oneHopViaEdges() {
-
- //BulkSet set = (BulkSet)result;
- TreeBackedVertex v = new TreeBackedVertex((Vertex)tree.getObjectsAtDepth(1).iterator().next(), tree);
-
-
- assertEquals("locate child", v.edges(Direction.OUT).next().inVertex().property("name").orElse(""), "interface 2");
- assertEquals("locate cousin", v.edges(Direction.IN).next().outVertex().property("name").orElse(""), "pserver 1");
-
-
- }
-
- @Ignore
- @Test
- public void oneHopViaVertices() {
-
- //BulkSet set = (BulkSet)result;
- TreeBackedVertex v = new TreeBackedVertex((Vertex)tree.getObjectsAtDepth(1).iterator().next(), tree);
-
-
- assertEquals("locate child", "interface 2", v.vertices(Direction.OUT).next().property("name").orElse(""));
- assertEquals("locate cousin", "pserver 1", v.vertices(Direction.IN).next().property("name").orElse(""));
-
- }
-
- @Ignore
- @Test
- public void twoHopCousinViaVertices() {
-
- //BulkSet set = (BulkSet)result;
- TreeBackedVertex v = new TreeBackedVertex((Vertex)tree.getObjectsAtDepth(1).iterator().next(), tree);
-
-
- assertEquals("locate child", "subnet 1", v.vertices(Direction.OUT).next().vertices(Direction.OUT, "in").next().property("name").orElse(""));
-
- }
-
- @Test
- public void walkVerticesRestrictedDepth() {
-
- //BulkSet set = (BulkSet)result;
- TreeBackedVertex v = new TreeBackedVertex((Vertex)treeDepth1.getObjectsAtDepth(1).iterator().next(), treeDepth1);
-
-
- assertEquals("nothing returned", false, v.vertices(Direction.OUT).next()
- .vertices(Direction.OUT, "hasChild").hasNext());
-
- }
-
- @Test
- public void walkVertices() {
- TreeBackedVertex v = new TreeBackedVertex((Vertex)tree.getObjectsAtDepth(1).iterator().next(), tree);
- assertEquals("locate child", "address 2", v.vertices(Direction.OUT).next()
- .vertices(Direction.OUT, "hasChild").next().property("name").orElse(""));
- }
-
- @Test
- public void walkEdges() {
- TreeBackedVertex v = new TreeBackedVertex((Vertex)tree.getObjectsAtDepth(1).iterator().next(), tree);
-
- assertEquals("locate child", "address 2", v.edges(Direction.OUT).next().inVertex()
- .edges(Direction.OUT, "hasChild").next().inVertex().property("name").orElse(""));
- }
-
- @Test
- public void noEdgesFoudWithLabelVertices() {
- TreeBackedVertex v = new TreeBackedVertex((Vertex)tree.getObjectsAtDepth(1).iterator().next(), tree);
-
- assertEquals("missing hello label", false , v.vertices(Direction.OUT, "hello").hasNext());
- }
-
- @Test
- public void noEdgesFoudWithLabelEdges() {
- TreeBackedVertex v = new TreeBackedVertex((Vertex)tree.getObjectsAtDepth(1).iterator().next(), tree);
-
- assertEquals("missing hello label", false , v.edges(Direction.OUT, "hello").hasNext());
- }
-
- @Test
- public void depthZeroNodeOnly() {
- TreeBackedVertex v = new TreeBackedVertex((Vertex)treeDepth0NodeOnly.getObjectsAtDepth(1).iterator().next(), treeDepth0NodeOnly);
- assertEquals("no edges returned", false, v.edges(Direction.BOTH).hasNext());
- }
-
+ private Graph graph = TinkerGraph.open();
+ private Object startKey = null;
+ private Tree<Element> tree = null;
+ private Tree<Element> treeDepth1 = null;
+ private Tree<Element> treeDepth0NodeOnly = null;
+
+ @Before
+ public void configure() {
+ GraphTraversalSource g = graph.traversal();
+
+ startKey = g.addV(T.label, "vserver").as("v1").property("test", "hello").addV(T.label, "vserver").as("v2")
+ .addV(T.label, "interface").property("name", "interface 1").as("v10").addInE("hasChild", "v2")
+ .property(EdgeProperty.CONTAINS.toString(), true).addV(T.label, "pserver").property("name", "pserver 1")
+ .as("v4").addOutE("runsOn", "v1").property(EdgeProperty.CONTAINS.toString(), false)
+ .addV(T.label, "interface").property("name", "interface 2").as("v3").addInE("hasChild", "v1")
+ .property(EdgeProperty.CONTAINS.toString(), true).addV(T.label, "address").property("name", "address 1")
+ .addInE("hasChild", "v3").property(EdgeProperty.CONTAINS.toString(), true).addV(T.label, "address")
+ .property("name", "address 2").addInE("hasChild", "v3").property(EdgeProperty.CONTAINS.toString(), true)
+ .addV(T.label, "complex").property("name", "complex 1").addInE("locatedIn", "v4")
+ .property(EdgeProperty.CONTAINS.toString(), false).addV(T.label, "interface")
+ .property("name", "interface 3").addInE("hasChild", "v4")
+ .property(EdgeProperty.CONTAINS.toString(), true).addV(T.label, "subnet").property("name", "subnet 1")
+ .as("v5").addInE("in", "v3").property(EdgeProperty.CONTAINS.toString(), false).addV(T.label, "address")
+ .property("name", "address 3").as("v6").addInE("hasChild", "v5")
+ .property(EdgeProperty.CONTAINS.toString(), true).select("v1").next();
+
+ tree = new GraphTraversalQueryEngine(g).findSubGraph((Vertex) startKey);
+ treeDepth1 = new GraphTraversalQueryEngine(g).findSubGraph((Vertex) startKey, 1, false);
+ treeDepth0NodeOnly = new GraphTraversalQueryEngine(g).findSubGraph((Vertex) startKey, 0, true);
+ }
+
+ @Ignore
+ @Test
+ public void oneHopViaEdges() {
+
+ // BulkSet set = (BulkSet)result;
+ TreeBackedVertex v = new TreeBackedVertex((Vertex) tree.getObjectsAtDepth(1).iterator().next(), tree);
+
+ assertEquals("locate child", v.edges(Direction.OUT).next().inVertex().property("name").orElse(""),
+ "interface 2");
+ assertEquals("locate cousin", v.edges(Direction.IN).next().outVertex().property("name").orElse(""),
+ "pserver 1");
+
+ }
+
+ @Ignore
+ @Test
+ public void oneHopViaVertices() {
+
+ // BulkSet set = (BulkSet)result;
+ TreeBackedVertex v = new TreeBackedVertex((Vertex) tree.getObjectsAtDepth(1).iterator().next(), tree);
+
+ assertEquals("locate child", "interface 2", v.vertices(Direction.OUT).next().property("name").orElse(""));
+ assertEquals("locate cousin", "pserver 1", v.vertices(Direction.IN).next().property("name").orElse(""));
+
+ }
+
+ @Ignore
+ @Test
+ public void twoHopCousinViaVertices() {
+
+ // BulkSet set = (BulkSet)result;
+ TreeBackedVertex v = new TreeBackedVertex((Vertex) tree.getObjectsAtDepth(1).iterator().next(), tree);
+
+ assertEquals("locate child", "subnet 1",
+ v.vertices(Direction.OUT).next().vertices(Direction.OUT, "in").next().property("name").orElse(""));
+
+ }
+
+ @Test
+ public void walkVerticesRestrictedDepth() {
+
+ // BulkSet set = (BulkSet)result;
+ TreeBackedVertex v =
+ new TreeBackedVertex((Vertex) treeDepth1.getObjectsAtDepth(1).iterator().next(), treeDepth1);
+
+ assertEquals("nothing returned", false,
+ v.vertices(Direction.OUT).next().vertices(Direction.OUT, "hasChild").hasNext());
+
+ }
+
+ @Test
+ public void walkVertices() {
+ TreeBackedVertex v = new TreeBackedVertex((Vertex) tree.getObjectsAtDepth(1).iterator().next(), tree);
+ assertEquals("locate child", "address 2", v.vertices(Direction.OUT).next().vertices(Direction.OUT, "hasChild")
+ .next().property("name").orElse(""));
+ }
+
+ @Test
+ public void walkEdges() {
+ TreeBackedVertex v = new TreeBackedVertex((Vertex) tree.getObjectsAtDepth(1).iterator().next(), tree);
+
+ assertEquals("locate child", "address 2", v.edges(Direction.OUT).next().inVertex()
+ .edges(Direction.OUT, "hasChild").next().inVertex().property("name").orElse(""));
+ }
+
+ @Test
+ public void noEdgesFoudWithLabelVertices() {
+ TreeBackedVertex v = new TreeBackedVertex((Vertex) tree.getObjectsAtDepth(1).iterator().next(), tree);
+
+ assertEquals("missing hello label", false, v.vertices(Direction.OUT, "hello").hasNext());
+ }
+
+ @Test
+ public void noEdgesFoudWithLabelEdges() {
+ TreeBackedVertex v = new TreeBackedVertex((Vertex) tree.getObjectsAtDepth(1).iterator().next(), tree);
+
+ assertEquals("missing hello label", false, v.edges(Direction.OUT, "hello").hasNext());
+ }
+
+ @Test
+ public void depthZeroNodeOnly() {
+ TreeBackedVertex v = new TreeBackedVertex((Vertex) treeDepth0NodeOnly.getObjectsAtDepth(1).iterator().next(),
+ treeDepth0NodeOnly);
+ assertEquals("no edges returned", false, v.edges(Direction.BOTH).hasNext());
+ }
+
}
diff --git a/aai-core/src/test/java/org/onap/aai/testutils/TestUtilConfigTranslatorforBusiness.java b/aai-core/src/test/java/org/onap/aai/testutils/TestUtilConfigTranslatorforBusiness.java
index 6dab1743..279e0967 100644
--- a/aai-core/src/test/java/org/onap/aai/testutils/TestUtilConfigTranslatorforBusiness.java
+++ b/aai-core/src/test/java/org/onap/aai/testutils/TestUtilConfigTranslatorforBusiness.java
@@ -27,48 +27,48 @@ import java.util.Map;
import java.util.TreeMap;
import org.onap.aai.setup.ConfigTranslator;
+import org.onap.aai.setup.SchemaConfigVersions;
import org.onap.aai.setup.SchemaLocationsBean;
import org.onap.aai.setup.SchemaVersion;
-import org.onap.aai.setup.SchemaConfigVersions;
public class TestUtilConfigTranslatorforBusiness extends ConfigTranslator {
-
- public TestUtilConfigTranslatorforBusiness(SchemaLocationsBean bean, SchemaConfigVersions schemaVersions) {
- super(bean, schemaVersions);
- }
- @Override
- public Map<SchemaVersion, List<String>> getNodeFiles() {
+ public TestUtilConfigTranslatorforBusiness(SchemaLocationsBean bean, SchemaConfigVersions schemaVersions) {
+ super(bean, schemaVersions);
+ }
+
+ @Override
+ public Map<SchemaVersion, List<String>> getNodeFiles() {
+
+ List<String> files11 = new ArrayList<>();
+ files11.add("src/test/resources/oxm/business_oxm_v11.xml");
+
+ List<String> files13 = new ArrayList<>();
+ files13.add("src/test/resources/oxm/business_oxm_v13.xml");
+ files13.add("src/test/resources/oxm/common_oxm_v13.xml");
+ files13.add("src/test/resources/oxm/serviceDesign_oxm_v13.xml");
+ files13.add("src/test/resources/oxm/network_oxm_v13.xml");
+
+ Map<SchemaVersion, List<String>> input = new TreeMap<>();
+ input.put(new SchemaVersion("v11"), files11);
+ input.put(schemaVersions.getDefaultVersion(), files13);
+ return input;
+ }
+
+ @Override
+ public Map<SchemaVersion, List<String>> getEdgeFiles() {
+ List<String> files = new ArrayList<>();
+ files.add("src/test/resources/dbedgerules/DbEdgeBusinessRules_test.json");
+ Map<SchemaVersion, List<String>> input = new TreeMap<>();
+ input.put(schemaVersions.getDefaultVersion(), files);
- List<String> files11 = new ArrayList<>();
- files11.add("src/test/resources/oxm/business_oxm_v11.xml");
-
- List<String> files13 = new ArrayList<>();
- files13.add("src/test/resources/oxm/business_oxm_v13.xml");
- files13.add("src/test/resources/oxm/common_oxm_v13.xml");
- files13.add("src/test/resources/oxm/serviceDesign_oxm_v13.xml");
- files13.add("src/test/resources/oxm/network_oxm_v13.xml");
-
- Map<SchemaVersion, List<String>> input = new TreeMap<>();
- input.put(new SchemaVersion("v11"), files11);
- input.put(schemaVersions.getDefaultVersion(), files13);
- return input;
- }
+ List<String> files2 = new ArrayList<>();
+ files2.add("src/test/resources/dbedgerules/test.json");
- @Override
- public Map<SchemaVersion, List<String>> getEdgeFiles() {
- List<String> files = new ArrayList<>();
- files.add("src/test/resources/dbedgerules/DbEdgeBusinessRules_test.json");
- Map<SchemaVersion, List<String>> input = new TreeMap<>();
- input.put(schemaVersions.getDefaultVersion(), files);
-
- List<String> files2 = new ArrayList<>();
- files2.add("src/test/resources/dbedgerules/test.json");
+ List<String> files3 = new ArrayList<>();
+ files3.add("src/test/resources/dbedgerules/DbEdgeBusinessRules_test.json");
+ input.put(new SchemaVersion("v11"), files3);
- List<String> files3 = new ArrayList<>();
- files3.add("src/test/resources/dbedgerules/DbEdgeBusinessRules_test.json");
- input.put(new SchemaVersion("v11"), files3);
-
- return input;
- }
+ return input;
+ }
}
diff --git a/aai-core/src/test/java/org/onap/aai/testutils/TestUtilConfigTranslatorforDataLink.java b/aai-core/src/test/java/org/onap/aai/testutils/TestUtilConfigTranslatorforDataLink.java
index d82c9d80..e5652fe1 100644
--- a/aai-core/src/test/java/org/onap/aai/testutils/TestUtilConfigTranslatorforDataLink.java
+++ b/aai-core/src/test/java/org/onap/aai/testutils/TestUtilConfigTranslatorforDataLink.java
@@ -20,37 +20,37 @@
package org.onap.aai.testutils;
+import java.util.*;
+
import org.onap.aai.setup.ConfigTranslator;
+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 java.util.*;
public class TestUtilConfigTranslatorforDataLink extends ConfigTranslator {
- public TestUtilConfigTranslatorforDataLink(SchemaLocationsBean bean, SchemaConfigVersions schemaVersions) {
- super(bean, schemaVersions);
- }
-
- @Override
- public Map<SchemaVersion, List<String>> getNodeFiles() {
-
- Map<SchemaVersion, List<String>> input = new TreeMap<>();
- input.put(new SchemaVersion("v1"), Arrays.asList("src/test/resources/oxm/dbalias_oxm_one.xml"));
- input.put(new SchemaVersion("v2"), Arrays.asList("src/test/resources/oxm/dbalias_oxm_two.xml"));
- input.put(new SchemaVersion("v3"), Arrays.asList("src/test/resources/oxm/dbalias_oxm_three.xml"));
- input.put(new SchemaVersion("v4"), Arrays.asList("src/test/resources/oxm/dbalias_oxm_four.xml"));
- return input;
- }
-
- @Override
- public Map<SchemaVersion, List<String>> getEdgeFiles() {
- Map<SchemaVersion, List<String>> input = new TreeMap<>();
- input.put(new SchemaVersion("v1"), Arrays.asList("src/test/resources/dbedgerules/DbEdgerules_one.json"));
- input.put(new SchemaVersion("v2"), Arrays.asList("src/test/resources/dbedgerules/DbEdgerules_two.json"));
- input.put(new SchemaVersion("v3"), Arrays.asList("src/test/resources/dbedgerules/DbEdgerules_three.json"));
- input.put(new SchemaVersion("v4"), Arrays.asList("src/test/resources/dbedgerules/DbEdgerules_four.json"));
- return input;
- }
+ public TestUtilConfigTranslatorforDataLink(SchemaLocationsBean bean, SchemaConfigVersions schemaVersions) {
+ super(bean, schemaVersions);
+ }
+
+ @Override
+ public Map<SchemaVersion, List<String>> getNodeFiles() {
+
+ Map<SchemaVersion, List<String>> input = new TreeMap<>();
+ input.put(new SchemaVersion("v1"), Arrays.asList("src/test/resources/oxm/dbalias_oxm_one.xml"));
+ input.put(new SchemaVersion("v2"), Arrays.asList("src/test/resources/oxm/dbalias_oxm_two.xml"));
+ input.put(new SchemaVersion("v3"), Arrays.asList("src/test/resources/oxm/dbalias_oxm_three.xml"));
+ input.put(new SchemaVersion("v4"), Arrays.asList("src/test/resources/oxm/dbalias_oxm_four.xml"));
+ return input;
+ }
+
+ @Override
+ public Map<SchemaVersion, List<String>> getEdgeFiles() {
+ Map<SchemaVersion, List<String>> input = new TreeMap<>();
+ input.put(new SchemaVersion("v1"), Arrays.asList("src/test/resources/dbedgerules/DbEdgerules_one.json"));
+ input.put(new SchemaVersion("v2"), Arrays.asList("src/test/resources/dbedgerules/DbEdgerules_two.json"));
+ input.put(new SchemaVersion("v3"), Arrays.asList("src/test/resources/dbedgerules/DbEdgerules_three.json"));
+ input.put(new SchemaVersion("v4"), Arrays.asList("src/test/resources/dbedgerules/DbEdgerules_four.json"));
+ return input;
+ }
}
diff --git a/aai-core/src/test/java/org/onap/aai/testutils/TestUtilConfigTranslatorforEdges.java b/aai-core/src/test/java/org/onap/aai/testutils/TestUtilConfigTranslatorforEdges.java
index ca6c6740..d47a775c 100644
--- a/aai-core/src/test/java/org/onap/aai/testutils/TestUtilConfigTranslatorforEdges.java
+++ b/aai-core/src/test/java/org/onap/aai/testutils/TestUtilConfigTranslatorforEdges.java
@@ -27,48 +27,48 @@ import java.util.Map;
import java.util.TreeMap;
import org.onap.aai.setup.ConfigTranslator;
+import org.onap.aai.setup.SchemaConfigVersions;
import org.onap.aai.setup.SchemaLocationsBean;
import org.onap.aai.setup.SchemaVersion;
-import org.onap.aai.setup.SchemaConfigVersions;
public class TestUtilConfigTranslatorforEdges extends ConfigTranslator {
-
- public TestUtilConfigTranslatorforEdges(SchemaLocationsBean bean, SchemaConfigVersions schemaVersions) {
- super(bean, schemaVersions);
- }
- @Override
- public Map<SchemaVersion, List<String>> getNodeFiles() {
- List<String> files11 = new ArrayList<>();
- files11.add("src/test/resources/oxm/business_oxm_v11.xml");
-
- List<String> files13 = new ArrayList<>();
- files13.add("src/test/resources/oxm/business_oxm_v13.xml");
- files13.add("src/test/resources/oxm/common_oxm_v13.xml");
- files13.add("src/test/resources/oxm/serviceDesign_oxm_v13.xml");
- files13.add("src/test/resources/oxm/network_oxm_v13.xml");
-
- Map<SchemaVersion, List<String>> input = new TreeMap<>();
- input.put(new SchemaVersion("v11"), files11);
- input.put(new SchemaVersion("v13"), files13);
- return input;
- }
+ public TestUtilConfigTranslatorforEdges(SchemaLocationsBean bean, SchemaConfigVersions schemaVersions) {
+ super(bean, schemaVersions);
+ }
+
+ @Override
+ public Map<SchemaVersion, List<String>> getNodeFiles() {
+ List<String> files11 = new ArrayList<>();
+ files11.add("src/test/resources/oxm/business_oxm_v11.xml");
+
+ List<String> files13 = new ArrayList<>();
+ files13.add("src/test/resources/oxm/business_oxm_v13.xml");
+ files13.add("src/test/resources/oxm/common_oxm_v13.xml");
+ files13.add("src/test/resources/oxm/serviceDesign_oxm_v13.xml");
+ files13.add("src/test/resources/oxm/network_oxm_v13.xml");
+
+ Map<SchemaVersion, List<String>> input = new TreeMap<>();
+ input.put(new SchemaVersion("v11"), files11);
+ input.put(new SchemaVersion("v13"), files13);
+ return input;
+ }
+
+ @Override
+ public Map<SchemaVersion, List<String>> getEdgeFiles() {
+ List<String> files = new ArrayList<>();
+ files.add("src/test/resources/dbedgerules/test.json");
+ files.add("src/test/resources/dbedgerules/test2.json");
+ Map<SchemaVersion, List<String>> input = new TreeMap<>();
+ input.put(schemaVersions.getDefaultVersion(), files);
+
+ List<String> files2 = new ArrayList<>();
+ files2.add("src/test/resources/dbedgerules/DbEdgeBusinessRules_test.json");
+ input.put(new SchemaVersion("v10"), files2);
+ List<String> files3 = new ArrayList<>();
+ files3.add("src/test/resources/dbedgerules/EdgeDescriptionRules_test.json");
+ input.put(new SchemaVersion("v11"), files3);
- @Override
- public Map<SchemaVersion, List<String>> getEdgeFiles() {
- List<String> files = new ArrayList<>();
- files.add("src/test/resources/dbedgerules/test.json");
- files.add("src/test/resources/dbedgerules/test2.json");
- Map<SchemaVersion, List<String>> input = new TreeMap<>();
- input.put(schemaVersions.getDefaultVersion(), files);
-
- List<String> files2 = new ArrayList<>();
- files2.add("src/test/resources/dbedgerules/DbEdgeBusinessRules_test.json");
- input.put(new SchemaVersion("v10"), files2);
- List<String> files3 = new ArrayList<>();
- files3.add("src/test/resources/dbedgerules/EdgeDescriptionRules_test.json");
- input.put(new SchemaVersion("v11"), files3);
-
- return input;
- }
+ return input;
+ }
}
diff --git a/aai-core/src/test/java/org/onap/aai/util/AAIConfigCommandLinePropGetterTest.java b/aai-core/src/test/java/org/onap/aai/util/AAIConfigCommandLinePropGetterTest.java
index 316cc150..c64c9a93 100644
--- a/aai-core/src/test/java/org/onap/aai/util/AAIConfigCommandLinePropGetterTest.java
+++ b/aai-core/src/test/java/org/onap/aai/util/AAIConfigCommandLinePropGetterTest.java
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.util;
import static org.junit.Assert.assertEquals;
@@ -30,74 +31,73 @@ import org.onap.aai.AAISetup;
public class AAIConfigCommandLinePropGetterTest extends AAISetup {
- private SecurityManager m;
- private TestSecurityManager sm;
+ private SecurityManager m;
+ private TestSecurityManager sm;
+
+ @Before
+ public void setUp() {
+ m = System.getSecurityManager();
+ sm = new TestSecurityManager();
+ System.setSecurityManager(sm);
+ }
+
+ @After
+ public void tearDown() {
+ System.setSecurityManager(m);
+ }
- @Before
- public void setUp()
- {
- m = System.getSecurityManager();
- sm = new TestSecurityManager();
- System.setSecurityManager(sm);
- }
+ @Test
+ public void testMainNoArgs() {
+ try {
+ AAIConfigCommandLinePropGetter.main(new String[] {});
+ } catch (SecurityException se) {
+ // assert main method ends with System.exit(0)
+ assertEquals("0", se.getMessage());
+ }
+ }
- @After
- public void tearDown()
- {
- System.setSecurityManager(m);
- }
+ @Test
+ public void testMainReadProp() {
+ try {
+ AAIConfigCommandLinePropGetter.main(new String[] {"aai.primary.filetransfer.serverlist"});
+ } catch (SecurityException se) {
+ // assert main method ends with System.exit(0)
+ assertEquals("0", se.getMessage());
+ }
+ }
- @Test
- public void testMainNoArgs() {
- try {
- AAIConfigCommandLinePropGetter.main(new String[] {});
- } catch (SecurityException se) {
- // assert main method ends with System.exit(0)
- assertEquals("0", se.getMessage());
- }
- }
-
- @Test
- public void testMainReadProp() {
- try {
- AAIConfigCommandLinePropGetter.main(new String[] {"aai.primary.filetransfer.serverlist"});
- } catch (SecurityException se) {
- // assert main method ends with System.exit(0)
- assertEquals("0", se.getMessage());
- }
- }
-
- @Test
- public void testMainOneArg() {
- try {
- AAIConfigCommandLinePropGetter.main(new String[] {"one"});
- } catch (SecurityException se) {
- // assert main method ends with System.exit(0)
- assertEquals("0", se.getMessage());
- }
- }
-
- @Test
- public void testMainMoreThanOneArg() {
- try {
- AAIConfigCommandLinePropGetter.main(new String[] {"one", "two"});
- } catch (SecurityException se) {
- // assert main method ends with System.exit(0)
- assertEquals("0", se.getMessage());
- }
- }
+ @Test
+ public void testMainOneArg() {
+ try {
+ AAIConfigCommandLinePropGetter.main(new String[] {"one"});
+ } catch (SecurityException se) {
+ // assert main method ends with System.exit(0)
+ assertEquals("0", se.getMessage());
+ }
+ }
+
+ @Test
+ public void testMainMoreThanOneArg() {
+ try {
+ AAIConfigCommandLinePropGetter.main(new String[] {"one", "two"});
+ } catch (SecurityException se) {
+ // assert main method ends with System.exit(0)
+ assertEquals("0", se.getMessage());
+ }
+ }
}
+
class TestSecurityManager extends SecurityManager {
- @Override
- public void checkPermission(Permission permission) {
- if ("exitVM".equals(permission.getName()))
- {
- throw new SecurityException("System.exit attempted and blocked.");
- }
- }
- @Override
- public void checkExit(int status) {
- throw new SecurityException(Integer.toString(status));
- }
+ @Override
+ public void checkPermission(Permission permission) {
+ if ("exitVM".equals(permission.getName())) {
+ throw new SecurityException("System.exit attempted and blocked.");
+ }
+ }
+
+ @Override
+ public void checkExit(int status) {
+ throw new SecurityException(Integer.toString(status));
+ }
}
diff --git a/aai-core/src/test/java/org/onap/aai/util/AAIConfigTest.java b/aai-core/src/test/java/org/onap/aai/util/AAIConfigTest.java
index 51acdb74..69a8b89c 100644
--- a/aai-core/src/test/java/org/onap/aai/util/AAIConfigTest.java
+++ b/aai-core/src/test/java/org/onap/aai/util/AAIConfigTest.java
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.util;
import static org.junit.Assert.assertEquals;
@@ -39,92 +40,92 @@ import org.onap.aai.exceptions.AAIException;
public class AAIConfigTest extends AAISetup {
- @BeforeClass
- public static void setUp() throws AAIException {
- AAIConfig.init();
- }
-
- @Test
- public void testGetConfigFile() {
- String res = AAIConfig.getConfigFile();
- assertNotNull(res);
- assertTrue(res.endsWith("aaiconfig.properties"));
- }
-
- @Test
- public void testGetStringString() {
- String res = AAIConfig.get("aai.notificationEvent.default.sourceName", "somerandomvalue");
- assertNotNull(res);
- assertEquals("aai", res);
- }
-
- @Test
- public void testGetStringStringReturnDefaultvalue() {
- String res = AAIConfig.get("key", "result");
- assertNotNull(res);
- assertEquals("result", res);
- }
-
- @Test(expected = AAIException.class)
- public void testGetStringInvalidKey() throws AAIException {
- AAIConfig.get("key");
- }
-
- @Test(expected = AAIException.class)
- public void testGetStringEmptyResponse() throws AAIException {
- AAIConfig.get("aai.response.null");
- }
-
- @Test
- public void testGetStringReloadConfig() throws AAIException {
- String res = AAIConfig.get("aai.config.nodename");
- assertNotNull(res);
- assertEquals(AAIConfig.getNodeName(), res);
- }
-
- @Test
- public void testGetStringPassword() throws AAIException {
- String res = AAIConfig.get("aai.example.passwd");
- assertNotNull(res);
- assertEquals("changeit", res);
- }
-
- @Test(expected=NumberFormatException.class)
- public void testGetIntInvalidInput() throws AAIException {
- AAIConfig.getInt("aai.example.string");
- }
-
- @Test
- public void testGetInt() throws AAIException {
- int res = AAIConfig.getInt("aai.example.int");
- assertNotNull(res);
- assertEquals(7748, res);
- }
-
- @Test
- public void testGetNodeName() throws UnknownHostException {
- InetAddress ip = InetAddress.getLocalHost();
- String res = AAIConfig.getNodeName();
- assertNotNull(res);
- assertEquals(ip.getHostName(), res);
- }
-
- @Test
- public void testIsEmpty() {
- boolean res = AAIConfig.isEmpty("hllo world");
- assertFalse(res);
- }
-
- @Test
- public void testIsEmptyEmpty() {
- boolean res = AAIConfig.isEmpty("");
- assertTrue(res);
- }
-
- @Test
- public void testIsEmptyNull() {
- boolean res = AAIConfig.isEmpty(null);
- assertTrue(res);
- }
+ @BeforeClass
+ public static void setUp() throws AAIException {
+ AAIConfig.init();
+ }
+
+ @Test
+ public void testGetConfigFile() {
+ String res = AAIConfig.getConfigFile();
+ assertNotNull(res);
+ assertTrue(res.endsWith("aaiconfig.properties"));
+ }
+
+ @Test
+ public void testGetStringString() {
+ String res = AAIConfig.get("aai.notificationEvent.default.sourceName", "somerandomvalue");
+ assertNotNull(res);
+ assertEquals("aai", res);
+ }
+
+ @Test
+ public void testGetStringStringReturnDefaultvalue() {
+ String res = AAIConfig.get("key", "result");
+ assertNotNull(res);
+ assertEquals("result", res);
+ }
+
+ @Test(expected = AAIException.class)
+ public void testGetStringInvalidKey() throws AAIException {
+ AAIConfig.get("key");
+ }
+
+ @Test(expected = AAIException.class)
+ public void testGetStringEmptyResponse() throws AAIException {
+ AAIConfig.get("aai.response.null");
+ }
+
+ @Test
+ public void testGetStringReloadConfig() throws AAIException {
+ String res = AAIConfig.get("aai.config.nodename");
+ assertNotNull(res);
+ assertEquals(AAIConfig.getNodeName(), res);
+ }
+
+ @Test
+ public void testGetStringPassword() throws AAIException {
+ String res = AAIConfig.get("aai.example.passwd");
+ assertNotNull(res);
+ assertEquals("changeit", res);
+ }
+
+ @Test(expected = NumberFormatException.class)
+ public void testGetIntInvalidInput() throws AAIException {
+ AAIConfig.getInt("aai.example.string");
+ }
+
+ @Test
+ public void testGetInt() throws AAIException {
+ int res = AAIConfig.getInt("aai.example.int");
+ assertNotNull(res);
+ assertEquals(7748, res);
+ }
+
+ @Test
+ public void testGetNodeName() throws UnknownHostException {
+ InetAddress ip = InetAddress.getLocalHost();
+ String res = AAIConfig.getNodeName();
+ assertNotNull(res);
+ assertEquals(ip.getHostName(), res);
+ }
+
+ @Test
+ public void testIsEmpty() {
+ boolean res = AAIConfig.isEmpty("hllo world");
+ assertFalse(res);
+ }
+
+ @Test
+ public void testIsEmptyEmpty() {
+ boolean res = AAIConfig.isEmpty("");
+ assertTrue(res);
+ }
+
+ @Test
+ public void testIsEmptyNull() {
+ boolean res = AAIConfig.isEmpty(null);
+ assertTrue(res);
+ }
}
diff --git a/aai-core/src/test/java/org/onap/aai/util/AAIUtilsTest.java b/aai-core/src/test/java/org/onap/aai/util/AAIUtilsTest.java
index b7f71d2b..e7132b58 100644
--- a/aai-core/src/test/java/org/onap/aai/util/AAIUtilsTest.java
+++ b/aai-core/src/test/java/org/onap/aai/util/AAIUtilsTest.java
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.util;
import static org.junit.Assert.assertEquals;
@@ -38,51 +39,52 @@ import org.junit.Test;
public class AAIUtilsTest {
- @Test
- public void testNullCheckWithNull() {
- List<String> newList = null;
- Iterable<String> res = AAIUtils.nullCheck(newList);
- assertNotNull("nullCheck() should return empty list", res);
- assertEquals(Collections.<String>emptyList(), res);
- }
+ @Test
+ public void testNullCheckWithNull() {
+ List<String> newList = null;
+ Iterable<String> res = AAIUtils.nullCheck(newList);
+ assertNotNull("nullCheck() should return empty list", res);
+ assertEquals(Collections.<String>emptyList(), res);
+ }
- @Test
- public void testNullCheckWithList() {
- List<String> newList = new ArrayList<String>();
- newList.add("testString");
+ @Test
+ public void testNullCheckWithList() {
+ List<String> newList = new ArrayList<String>();
+ newList.add("testString");
- Iterable<String> res = AAIUtils.nullCheck(newList);
+ Iterable<String> res = AAIUtils.nullCheck(newList);
- assertNotNull("nullCheck() should return back list", res);
- assertEquals(newList, res);
- }
+ assertNotNull("nullCheck() should return back list", res);
+ assertEquals(newList, res);
+ }
- @Test
- public void testGenDate() {
+ @Test
+ public void testGenDate() {
- Date d1 = new Date(0);
+ Date d1 = new Date(0);
- DateFormat formatter = new SimpleDateFormat("YYMMdd-HH:mm:ss:SSS");
- formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
- formatter.setLenient(false);
+ DateFormat formatter = new SimpleDateFormat("YYMMdd-HH:mm:ss:SSS");
+ formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
+ formatter.setLenient(false);
- Date d2 = null;
+ Date d2 = null;
- try {
- d2 = formatter.parse(AAIUtils.genDate());
- } catch (ParseException e) {
- fail("Date parsing exception");
- e.printStackTrace();
- }
+ try {
+ d2 = formatter.parse(AAIUtils.genDate());
+ } catch (ParseException e) {
+ fail("Date parsing exception");
+ e.printStackTrace();
+ }
- try {
- TimeUnit.SECONDS.sleep(1);
- } catch (InterruptedException e1) {}
+ try {
+ TimeUnit.SECONDS.sleep(1);
+ } catch (InterruptedException e1) {
+ }
- Date d3 = new Date();
+ Date d3 = new Date();
- assertTrue("Generated date is not after a past date", d2.after(d1));
- assertTrue("Generated date is not before a future date", d2.before(d3));
- }
+ assertTrue("Generated date is not after a past date", d2.after(d1));
+ assertTrue("Generated date is not before a future date", d2.before(d3));
+ }
}
diff --git a/aai-core/src/test/java/org/onap/aai/util/FileWatcherTest.java b/aai-core/src/test/java/org/onap/aai/util/FileWatcherTest.java
index bc815918..f4838304 100644
--- a/aai-core/src/test/java/org/onap/aai/util/FileWatcherTest.java
+++ b/aai-core/src/test/java/org/onap/aai/util/FileWatcherTest.java
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.util;
import static org.junit.Assert.*;
@@ -27,50 +28,50 @@ import org.junit.Test;
import org.mockito.Mockito;
public class FileWatcherTest {
-
- class FileWatcherExtension extends FileWatcher {
- public FileWatcherExtension(File file) {
- super(file);
- }
+ class FileWatcherExtension extends FileWatcher {
+
+ public FileWatcherExtension(File file) {
+ super(file);
+ }
+
+ @Override
+ protected void onChange(File file) {
+ System.out.println("do nothing");
+ }
+ }
+
+ @Test
+ public void testFileWatcher() {
+ File file = new File("helloworld");
+ file.setLastModified(new Long(123));
+ FileWatcher fileWatcher = new FileWatcherExtension(file);
+ assertNotNull(fileWatcher);
+ file.deleteOnExit();
+ }
+
+ @Test(expected = NullPointerException.class)
+ public void testFileWatcher_nullConstructor() {
+ FileWatcher fileWatcher = new FileWatcherExtension(null);
+ assertNull(fileWatcher);
+ }
+
+ @Test
+ public void testRun() {
+ // verify that code is reachable outside of conditional check in run()
+ File file = new File("helloworld");
+ file.setLastModified(new Long(100));
+ FileWatcher fileWatcher = new FileWatcherExtension(file);
+ fileWatcher.run();
+ file.deleteOnExit();
+ }
- @Override
- protected void onChange(File file) {
- System.out.println("do nothing");
- }
- }
+ @Test
+ public void testOnChange() throws Exception {
+ FileWatcher fileWatcher = Mockito.mock(FileWatcher.class, Mockito.CALLS_REAL_METHODS);
- @Test
- public void testFileWatcher() {
- File file = new File("helloworld");
- file.setLastModified(new Long(123));
- FileWatcher fileWatcher = new FileWatcherExtension(file);
- assertNotNull(fileWatcher);
- file.deleteOnExit();
- }
-
- @Test(expected=NullPointerException.class)
- public void testFileWatcher_nullConstructor() {
- FileWatcher fileWatcher = new FileWatcherExtension(null);
- assertNull(fileWatcher);
- }
-
- @Test
- public void testRun() {
- // verify that code is reachable outside of conditional check in run()
- File file = new File("helloworld");
- file.setLastModified(new Long(100));
- FileWatcher fileWatcher = new FileWatcherExtension(file);
- fileWatcher.run();
- file.deleteOnExit();
- }
+ fileWatcher.onChange(Mockito.any(File.class));
- @Test
- public void testOnChange() throws Exception {
- FileWatcher fileWatcher = Mockito.mock(FileWatcher.class, Mockito.CALLS_REAL_METHODS);
-
- fileWatcher.onChange(Mockito.any(File.class));
-
- Mockito.verify(fileWatcher).onChange(Mockito.any(File.class));
- }
+ Mockito.verify(fileWatcher).onChange(Mockito.any(File.class));
+ }
}
diff --git a/aai-core/src/test/java/org/onap/aai/util/FormatDateTest.java b/aai-core/src/test/java/org/onap/aai/util/FormatDateTest.java
index 6295990b..182916bc 100644
--- a/aai-core/src/test/java/org/onap/aai/util/FormatDateTest.java
+++ b/aai-core/src/test/java/org/onap/aai/util/FormatDateTest.java
@@ -17,8 +17,8 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-package org.onap.aai.util;
+package org.onap.aai.util;
import java.time.zone.ZoneRulesException;
@@ -29,46 +29,39 @@ import org.junit.Test;
@Ignore
public class FormatDateTest {
+ @Test(expected = IllegalArgumentException.class)
+ public void testExceptionThrownWhenInvalidPatternIsPassed() {
+ FormatDate formatDate = new FormatDate("XX/TT/GGGG");
+ formatDate.getDateTime();
+ }
+
+ @Test
+ public void correctPattern() {
+ FormatDate formatDate = new FormatDate("dd/mm/yyyy");
+ Assert.assertNotNull(formatDate.getDateTime());
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void invalidPattern() {
+ FormatDate formatDate = new FormatDate("XX/TT/GGGG", "GMT");
+ formatDate.getDateTime();
+ }
+
+ @Test(expected = ZoneRulesException.class)
+ public void invalidZone() {
+ FormatDate formatDate = new FormatDate("dd/mm/yyyy", "IST");
+ formatDate.getDateTime();
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void testExceptionThrownWhenInvalidPatternAndZoneIsPassed() {
+ FormatDate formatDate = new FormatDate("XX/TT/GGGG", "IST");
+ formatDate.getDateTime();
+ }
- @Test(expected=IllegalArgumentException.class)
- public void testExceptionThrownWhenInvalidPatternIsPassed()
- {
- FormatDate formatDate = new FormatDate("XX/TT/GGGG");
- formatDate.getDateTime();
- }
-
- @Test
- public void correctPattern()
- {
- FormatDate formatDate = new FormatDate("dd/mm/yyyy");
- Assert.assertNotNull(formatDate.getDateTime());
- }
-
- @Test(expected=IllegalArgumentException.class)
- public void invalidPattern()
- {
- FormatDate formatDate = new FormatDate("XX/TT/GGGG","GMT");
- formatDate.getDateTime();
- }
-
- @Test(expected=ZoneRulesException.class)
- public void invalidZone()
- {
- FormatDate formatDate = new FormatDate("dd/mm/yyyy","IST");
- formatDate.getDateTime();
- }
-
- @Test(expected=IllegalArgumentException.class)
- public void testExceptionThrownWhenInvalidPatternAndZoneIsPassed()
- {
- FormatDate formatDate = new FormatDate("XX/TT/GGGG","IST");
- formatDate.getDateTime();
- }
-
- @Test
- public void correctPatternAndZone()
- {
- FormatDate formatDate = new FormatDate("dd/mm/yyyy","GMT");
- Assert.assertNotNull(formatDate.getDateTime());
- }
+ @Test
+ public void correctPatternAndZone() {
+ FormatDate formatDate = new FormatDate("dd/mm/yyyy", "GMT");
+ Assert.assertNotNull(formatDate.getDateTime());
+ }
}
diff --git a/aai-core/src/test/java/org/onap/aai/util/JettyObfuscationConversionCommandLineUtilTest.java b/aai-core/src/test/java/org/onap/aai/util/JettyObfuscationConversionCommandLineUtilTest.java
index 071b630b..b060a676 100644
--- a/aai-core/src/test/java/org/onap/aai/util/JettyObfuscationConversionCommandLineUtilTest.java
+++ b/aai-core/src/test/java/org/onap/aai/util/JettyObfuscationConversionCommandLineUtilTest.java
@@ -19,6 +19,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.util;
import static org.junit.Assert.assertTrue;
@@ -39,12 +40,12 @@ public class JettyObfuscationConversionCommandLineUtilTest {
*/
@Test
public void test() {
- //setup, this will catch main's print statements for evaluation
+ // setup, this will catch main's print statements for evaluation
PrintStream oldOutputStream = System.out;
System.setOut(new PrintStream(testOut));
- /* ------ TEST OBFUSCATION ----*/
- JettyObfuscationConversionCommandLineUtil.main(new String[]{"-e", "hello world"});
+ /* ------ TEST OBFUSCATION ---- */
+ JettyObfuscationConversionCommandLineUtil.main(new String[] {"-e", "hello world"});
/*
* testOut was also catching any logging statements which interfered with result checking.
* This regex business was the workaround - it tries to find the expected value in
@@ -56,21 +57,20 @@ public class JettyObfuscationConversionCommandLineUtilTest {
Matcher obfMatch = obfExpectPat.matcher(obfResult);
assertTrue(obfMatch.find());
- testOut.reset(); //clear out previous result
+ testOut.reset(); // clear out previous result
/* ------ TEST DEOBFUSCATION ----- */
- JettyObfuscationConversionCommandLineUtil.main(new String[]{"-d", obfExpected});
+ JettyObfuscationConversionCommandLineUtil.main(new String[] {"-d", obfExpected});
String deobfResult = testOut.toString();
String deobfExpected = "hello world";
Pattern deobfExpectPat = Pattern.compile(deobfExpected);
Matcher deobfMatch = deobfExpectPat.matcher(deobfResult);
assertTrue(deobfMatch.find());
- //clean up, resets to stdout
+ // clean up, resets to stdout
System.setOut(oldOutputStream);
}
-
/**
* Test.
*/
@@ -78,8 +78,8 @@ public class JettyObfuscationConversionCommandLineUtilTest {
public void testUsage() {
System.setOut(new PrintStream(testOut));
- /* ------ TEST OBFUSCATION ----*/
- JettyObfuscationConversionCommandLineUtil.main(new String[]{"-f", "hello world"});
+ /* ------ TEST OBFUSCATION ---- */
+ JettyObfuscationConversionCommandLineUtil.main(new String[] {"-f", "hello world"});
/*
* testOut was also catching any logging statements which interfered with result checking.
* This regex business was the workaround - it tries to find the expected value in
@@ -87,9 +87,8 @@ public class JettyObfuscationConversionCommandLineUtilTest {
*/
String obfResult = testOut.toString();
assertTrue(obfResult.startsWith("failed to parse input"));
-
- testOut.reset(); //clear out previous result
+ testOut.reset(); // clear out previous result
}
diff --git a/aai-core/src/test/java/org/onap/aai/util/KeyValueListTest.java b/aai-core/src/test/java/org/onap/aai/util/KeyValueListTest.java
index 88665065..38901781 100644
--- a/aai-core/src/test/java/org/onap/aai/util/KeyValueListTest.java
+++ b/aai-core/src/test/java/org/onap/aai/util/KeyValueListTest.java
@@ -17,11 +17,13 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.util;
+import static org.junit.Assert.*;
+
import org.junit.Before;
import org.junit.Test;
-import static org.junit.Assert.*;
public class KeyValueListTest {
KeyValueList kv;
diff --git a/aai-core/src/test/java/org/onap/aai/util/MapperUtilTest.java b/aai-core/src/test/java/org/onap/aai/util/MapperUtilTest.java
index 2d68f833..33da9c04 100644
--- a/aai-core/src/test/java/org/onap/aai/util/MapperUtilTest.java
+++ b/aai-core/src/test/java/org/onap/aai/util/MapperUtilTest.java
@@ -19,25 +19,24 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-package org.onap.aai.util;
-
+
+package org.onap.aai.util;
+
+import static org.junit.Assert.assertEquals;
+
import org.json.JSONObject;
import org.junit.Before;
import org.junit.Test;
-import static org.junit.Assert.assertEquals;
-
public class MapperUtilTest {
-
-
private JSONObject expectedJson;
private JSONObject sampleJson;
@Before
- public void setup(){
- expectedJson = new JSONObject();
- sampleJson = new JSONObject();
+ public void setup() {
+ expectedJson = new JSONObject();
+ sampleJson = new JSONObject();
}
@Test
@@ -46,8 +45,8 @@ public class MapperUtilTest {
expectedJson.put("shape", "box");
SampleClass sample = new SampleClass("black", "box");
assertEquals(expectedJson.toString(), MapperUtil.writeAsJSONString(sample));
- }
-
+ }
+
@Test
public void readAsObjectOfTest() throws Exception {
sampleJson.put("color", "black");
@@ -56,19 +55,21 @@ public class MapperUtilTest {
SampleClass actualObject = MapperUtil.readAsObjectOf(SampleClass.class, sampleJson.toString());
assertEquals(expectedObject.getColor(), actualObject.getColor());
assertEquals(expectedObject.getShape(), actualObject.getShape());
- }
+ }
}
-class SampleClass {
- private String color;
- private String shape;
+
+class SampleClass {
+ private String color;
+ private String shape;
public SampleClass() {
-
+
}
- public SampleClass(String c, String s){
- color = c;
- shape = s;
+
+ public SampleClass(String c, String s) {
+ color = c;
+ shape = s;
}
public String getColor() {
diff --git a/aai-core/src/test/java/org/onap/aai/util/PojoUtilsTest.java b/aai-core/src/test/java/org/onap/aai/util/PojoUtilsTest.java
index 35065fd5..e9069885 100644
--- a/aai-core/src/test/java/org/onap/aai/util/PojoUtilsTest.java
+++ b/aai-core/src/test/java/org/onap/aai/util/PojoUtilsTest.java
@@ -17,12 +17,17 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.util;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
+import com.google.common.collect.ImmutableListMultimap;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Multimap;
+
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.Month;
@@ -42,287 +47,284 @@ import org.junit.Test;
import org.mockito.Mockito;
import org.onap.aai.domain.notificationEvent.NotificationEvent;
-import com.google.common.collect.ImmutableListMultimap;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Multimap;
-
public class PojoUtilsTest {
- private PojoUtils pojoUtils;
-
- @Before
- public void init() {
- pojoUtils = new PojoUtils();
- }
-
- @Test
- public void testGetKeyValueList() throws Exception {
- Entity entity = getEntityObject();
- Person person = getPojoObject();
-
- List<KeyValueList> keyValueLists = pojoUtils.getKeyValueList(entity, person);
-
- for (KeyValueList keyValueList : keyValueLists) {
-
- if(keyValueList.getKey().equals("key")) {
- assertEquals("value", keyValueList.getValue());
- } else if (keyValueList.getKey().equals("name")) {
- assertEquals("Andrew", keyValueList.getValue());
- } else if(keyValueList.getKey().equals("nickname")) {
- assertEquals("Andy", keyValueList.getValue());
- } else if(keyValueList.getKey().equals("age")) {
- assertEquals("30", keyValueList.getValue());
- } else if(keyValueList.getKey().equals("weightlb")) {
- assertEquals("185", keyValueList.getValue());
- } else if(keyValueList.getKey().equals("heightcm")) {
- assertEquals("190", keyValueList.getValue());
- } else if(keyValueList.getKey().equals("pet")) {
- assertEquals("", keyValueList.getValue());
- }
- }
- }
-
- @Test
- public void testGetJsonFromObjectClassMockTest() throws Exception {
- PojoUtils pojoUtils = Mockito.mock(PojoUtils.class);
- String obj = "helloWorld";
- Mockito.when(pojoUtils.getJsonFromObject(Mockito.anyString())).thenCallRealMethod();
-
- pojoUtils.getJsonFromObject(obj);
-
- Mockito.verify(pojoUtils, Mockito.times(1)).getJsonFromObject(Mockito.anyString(), Mockito.eq(false), Mockito.eq(true));
- }
-
- @Test
- public void testGetJsonFromObjectClass() throws Exception {
- LocalDateTime date = LocalDateTime.of(2017, Month.SEPTEMBER, 18, 10, 55, 0, 300);
-
- String res = pojoUtils.getJsonFromObject(date);
-
- assertNotNull(res);
- assertTrue(res.contains("\"dayOfMonth\" : 18"));
- assertTrue(res.contains("\"dayOfWeek\" : \"MONDAY\""));
- assertTrue(res.contains("\"dayOfYear\" : 261"));
- assertTrue(res.contains("\"hour\" : 10"));
- assertTrue(res.contains("\"minute\" : 55"));
- assertTrue(res.contains("\"month\" : \"SEPTEMBER\""));
- assertTrue(res.contains("\"monthValue\" : 9"));
- assertTrue(res.contains("\"nano\" : 300"));
- assertTrue(res.contains("\"second\" : 0"));
- assertTrue(res.contains("\"year\" : 2017"));
- }
-
- @Test
- public void testGetJsonFromObjectClassNull() throws Exception {
- String res = pojoUtils.getJsonFromObject(null);
-
- assertNotNull(res);
- assertEquals("null", res);
- }
-
- @Test
- public void testGetJsonFromObjectNull() throws Exception {
- String res = pojoUtils.getJsonFromObject(null, false, true);
-
- assertNotNull(res);
- assertEquals("null", res);
- }
-
- @Test
- public void testGetJsonFromObject() throws Exception {
- LocalDateTime date = LocalDateTime.of(2017, Month.SEPTEMBER, 18, 10, 55, 0, 300);
-
- String res = pojoUtils.getJsonFromObject(date, false, false);
- assertNotNull(res);
-
- res = pojoUtils.getJsonFromObject(date, true, false);
- assertNotNull(res);
-
- res = pojoUtils.getJsonFromObject(date, true, true);
- assertNotNull(res);
- }
-
- @Test
- public void testGetJsonFromDynamicObject() throws Exception {
- DynamicEntity dynamicEntity = Mockito.mock(DynamicEntity.class);
- JAXBContext jaxbContext = Mockito.mock(JAXBContext.class);
- JAXBMarshaller marshaller = Mockito.mock(JAXBMarshaller.class);
-
- Mockito.when(jaxbContext.createMarshaller()).thenReturn(marshaller);
-
- String output = pojoUtils.getJsonFromDynamicObject(dynamicEntity, jaxbContext, true);
- assertEquals("", output);
- }
-
- @Test(expected = NullPointerException.class)
- public void testGetXmlFromObjectNull() throws Exception {
- pojoUtils.getXmlFromObject(null);
- }
-
- @Test
- public void testGetXmlFromObject() throws JAXBException, IOException {
- NotificationEvent notificationEvent = new NotificationEvent();
- notificationEvent.setCambriaPartition("partition");
-
- String res = pojoUtils.getXmlFromObject(notificationEvent);
-
- assertNotNull(res);
- assertTrue(res.contains("<NotificationEvent>"));
- assertTrue(res.contains("<cambria.partition>partition</cambria.partition>"));
- assertTrue(res.contains("</NotificationEvent>"));
- }
-
- @Test
- public void testGetLookupKeyEmptyKey() {
- String baseKey = "";
- Collection<String> keyProps = new ArrayList<String>();
- keyProps.add("key");
-
- HashMap<String, Object> lookup = new HashMap<String, Object>();
- lookup.put("key", "val");
- String expectedLookupKey = "key=val";
-
- String res = pojoUtils.getLookupKey(baseKey, lookup, keyProps);
- assertEquals(expectedLookupKey, res);
- }
-
- @Test
- public void testGetLookupKey() {
- String baseKey = "baseKey";
- Collection<String> keyProps = new ArrayList<String>();
- keyProps.add("key");
-
- HashMap<String, Object> lookup = new HashMap<String, Object>();
- lookup.put("key", "val");
- String expectedLookupKey = "baseKey&key=val";
-
- String res = pojoUtils.getLookupKey(baseKey, lookup, keyProps);
-
- assertEquals(expectedLookupKey, res);
- }
-
- @Test
- public void testGetLookupKeys() {
- HashMap<String, Object> lookup = new HashMap<>();
- lookup.put("multimapkey", "val");
- LinkedHashMap<String, HashMap<String, Object>> lookupHashes = new LinkedHashMap<>();
- lookupHashes.put("objectType", lookup);
-
- Multimap<String, String> multimap = ImmutableListMultimap.of("objectType", "multimapkey");
- String res = pojoUtils.getLookupKeys(lookupHashes, multimap);
-
- String lookupKey = "val";
- assertNotNull(res);
- assertEquals(lookupKey, res);
- }
-
- @Test
- public void testGetExampleObject() throws Exception {
- Person p = getPojoObject();
- pojoUtils.getExampleObject(p, true);
- assertNotNull(p);
- assertTrue(p.getName().contains("example-name-val-"));
- assertTrue(p.getNickname().contains("example-nickname-val-"));
- assertTrue(p.getPet().contains("example-pet-val-"));
- assertNotNull(p.getAge());
- assertNotNull(p.getHeightcm());
- assertNotNull(p.getWeightlb());
- assertTrue(p.isMarried());
- }
-
- private Entity getEntityObject() {
- Entity entity = new Entity();
- KeyValueList list = new KeyValueList();
- list.setKey("key");
- list.setValue("value");
-
- entity.setAction("action");
- entity.setKeyValueList(Lists.newArrayList(list));
- entity.setEquipmentRole("equipmentRole");
- entity.setSelfLink("selfLink");
-
- return entity;
- }
-
- private Person getPojoObject() {
- Person p = new Person("Andrew");
- p.setAge(30);
- p.setHeightcm((short) 190);
- p.setWeightlb(185);
- p.setNickname("Andy");
- p.setPet(null);
- return p;
- }
-
- class Person {
-
- private int age;
- private long weightlb;
- private short heightcm;
- private String nickname;
- private String name;
- private String pet;
- private boolean isMarried;
-
- public Person(String name) {
- this.name = name;
- }
-
- public int getAge() {
- return age;
- }
-
- public void setAge(int age) {
- this.age = age;
- }
-
- public long getWeightlb() {
- return weightlb;
- }
-
- public void setWeightlb(long weightlb) {
- this.weightlb = weightlb;
- }
-
- public short getHeightcm() {
- return heightcm;
- }
-
- public void setHeightcm(short heightcm) {
- this.heightcm = heightcm;
- }
-
- public String getNickname() {
- return nickname;
- }
-
- public void setNickname(String nickname) {
- this.nickname = nickname;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public String getPet() {
- return pet;
- }
-
- public void setPet(String pet) {
- this.pet = pet;
- }
-
- public boolean isMarried() {
- return isMarried;
- }
-
- public void setMarried(boolean isMarried) {
- this.isMarried = isMarried;
- }
-
- }
+ private PojoUtils pojoUtils;
+
+ @Before
+ public void init() {
+ pojoUtils = new PojoUtils();
+ }
+
+ @Test
+ public void testGetKeyValueList() throws Exception {
+ Entity entity = getEntityObject();
+ Person person = getPojoObject();
+
+ List<KeyValueList> keyValueLists = pojoUtils.getKeyValueList(entity, person);
+
+ for (KeyValueList keyValueList : keyValueLists) {
+
+ if (keyValueList.getKey().equals("key")) {
+ assertEquals("value", keyValueList.getValue());
+ } else if (keyValueList.getKey().equals("name")) {
+ assertEquals("Andrew", keyValueList.getValue());
+ } else if (keyValueList.getKey().equals("nickname")) {
+ assertEquals("Andy", keyValueList.getValue());
+ } else if (keyValueList.getKey().equals("age")) {
+ assertEquals("30", keyValueList.getValue());
+ } else if (keyValueList.getKey().equals("weightlb")) {
+ assertEquals("185", keyValueList.getValue());
+ } else if (keyValueList.getKey().equals("heightcm")) {
+ assertEquals("190", keyValueList.getValue());
+ } else if (keyValueList.getKey().equals("pet")) {
+ assertEquals("", keyValueList.getValue());
+ }
+ }
+ }
+
+ @Test
+ public void testGetJsonFromObjectClassMockTest() throws Exception {
+ PojoUtils pojoUtils = Mockito.mock(PojoUtils.class);
+ String obj = "helloWorld";
+ Mockito.when(pojoUtils.getJsonFromObject(Mockito.anyString())).thenCallRealMethod();
+
+ pojoUtils.getJsonFromObject(obj);
+
+ Mockito.verify(pojoUtils, Mockito.times(1)).getJsonFromObject(Mockito.anyString(), Mockito.eq(false),
+ Mockito.eq(true));
+ }
+
+ @Test
+ public void testGetJsonFromObjectClass() throws Exception {
+ LocalDateTime date = LocalDateTime.of(2017, Month.SEPTEMBER, 18, 10, 55, 0, 300);
+
+ String res = pojoUtils.getJsonFromObject(date);
+
+ assertNotNull(res);
+ assertTrue(res.contains("\"dayOfMonth\" : 18"));
+ assertTrue(res.contains("\"dayOfWeek\" : \"MONDAY\""));
+ assertTrue(res.contains("\"dayOfYear\" : 261"));
+ assertTrue(res.contains("\"hour\" : 10"));
+ assertTrue(res.contains("\"minute\" : 55"));
+ assertTrue(res.contains("\"month\" : \"SEPTEMBER\""));
+ assertTrue(res.contains("\"monthValue\" : 9"));
+ assertTrue(res.contains("\"nano\" : 300"));
+ assertTrue(res.contains("\"second\" : 0"));
+ assertTrue(res.contains("\"year\" : 2017"));
+ }
+
+ @Test
+ public void testGetJsonFromObjectClassNull() throws Exception {
+ String res = pojoUtils.getJsonFromObject(null);
+
+ assertNotNull(res);
+ assertEquals("null", res);
+ }
+
+ @Test
+ public void testGetJsonFromObjectNull() throws Exception {
+ String res = pojoUtils.getJsonFromObject(null, false, true);
+
+ assertNotNull(res);
+ assertEquals("null", res);
+ }
+
+ @Test
+ public void testGetJsonFromObject() throws Exception {
+ LocalDateTime date = LocalDateTime.of(2017, Month.SEPTEMBER, 18, 10, 55, 0, 300);
+
+ String res = pojoUtils.getJsonFromObject(date, false, false);
+ assertNotNull(res);
+
+ res = pojoUtils.getJsonFromObject(date, true, false);
+ assertNotNull(res);
+
+ res = pojoUtils.getJsonFromObject(date, true, true);
+ assertNotNull(res);
+ }
+
+ @Test
+ public void testGetJsonFromDynamicObject() throws Exception {
+ DynamicEntity dynamicEntity = Mockito.mock(DynamicEntity.class);
+ JAXBContext jaxbContext = Mockito.mock(JAXBContext.class);
+ JAXBMarshaller marshaller = Mockito.mock(JAXBMarshaller.class);
+
+ Mockito.when(jaxbContext.createMarshaller()).thenReturn(marshaller);
+
+ String output = pojoUtils.getJsonFromDynamicObject(dynamicEntity, jaxbContext, true);
+ assertEquals("", output);
+ }
+
+ @Test(expected = NullPointerException.class)
+ public void testGetXmlFromObjectNull() throws Exception {
+ pojoUtils.getXmlFromObject(null);
+ }
+
+ @Test
+ public void testGetXmlFromObject() throws JAXBException, IOException {
+ NotificationEvent notificationEvent = new NotificationEvent();
+ notificationEvent.setCambriaPartition("partition");
+
+ String res = pojoUtils.getXmlFromObject(notificationEvent);
+
+ assertNotNull(res);
+ assertTrue(res.contains("<NotificationEvent>"));
+ assertTrue(res.contains("<cambria.partition>partition</cambria.partition>"));
+ assertTrue(res.contains("</NotificationEvent>"));
+ }
+
+ @Test
+ public void testGetLookupKeyEmptyKey() {
+ String baseKey = "";
+ Collection<String> keyProps = new ArrayList<String>();
+ keyProps.add("key");
+
+ HashMap<String, Object> lookup = new HashMap<String, Object>();
+ lookup.put("key", "val");
+ String expectedLookupKey = "key=val";
+
+ String res = pojoUtils.getLookupKey(baseKey, lookup, keyProps);
+ assertEquals(expectedLookupKey, res);
+ }
+
+ @Test
+ public void testGetLookupKey() {
+ String baseKey = "baseKey";
+ Collection<String> keyProps = new ArrayList<String>();
+ keyProps.add("key");
+
+ HashMap<String, Object> lookup = new HashMap<String, Object>();
+ lookup.put("key", "val");
+ String expectedLookupKey = "baseKey&key=val";
+
+ String res = pojoUtils.getLookupKey(baseKey, lookup, keyProps);
+
+ assertEquals(expectedLookupKey, res);
+ }
+
+ @Test
+ public void testGetLookupKeys() {
+ HashMap<String, Object> lookup = new HashMap<>();
+ lookup.put("multimapkey", "val");
+ LinkedHashMap<String, HashMap<String, Object>> lookupHashes = new LinkedHashMap<>();
+ lookupHashes.put("objectType", lookup);
+
+ Multimap<String, String> multimap = ImmutableListMultimap.of("objectType", "multimapkey");
+ String res = pojoUtils.getLookupKeys(lookupHashes, multimap);
+
+ String lookupKey = "val";
+ assertNotNull(res);
+ assertEquals(lookupKey, res);
+ }
+
+ @Test
+ public void testGetExampleObject() throws Exception {
+ Person p = getPojoObject();
+ pojoUtils.getExampleObject(p, true);
+ assertNotNull(p);
+ assertTrue(p.getName().contains("example-name-val-"));
+ assertTrue(p.getNickname().contains("example-nickname-val-"));
+ assertTrue(p.getPet().contains("example-pet-val-"));
+ assertNotNull(p.getAge());
+ assertNotNull(p.getHeightcm());
+ assertNotNull(p.getWeightlb());
+ assertTrue(p.isMarried());
+ }
+
+ private Entity getEntityObject() {
+ Entity entity = new Entity();
+ KeyValueList list = new KeyValueList();
+ list.setKey("key");
+ list.setValue("value");
+
+ entity.setAction("action");
+ entity.setKeyValueList(Lists.newArrayList(list));
+ entity.setEquipmentRole("equipmentRole");
+ entity.setSelfLink("selfLink");
+
+ return entity;
+ }
+
+ private Person getPojoObject() {
+ Person p = new Person("Andrew");
+ p.setAge(30);
+ p.setHeightcm((short) 190);
+ p.setWeightlb(185);
+ p.setNickname("Andy");
+ p.setPet(null);
+ return p;
+ }
+
+ class Person {
+
+ private int age;
+ private long weightlb;
+ private short heightcm;
+ private String nickname;
+ private String name;
+ private String pet;
+ private boolean isMarried;
+
+ public Person(String name) {
+ this.name = name;
+ }
+
+ public int getAge() {
+ return age;
+ }
+
+ public void setAge(int age) {
+ this.age = age;
+ }
+
+ public long getWeightlb() {
+ return weightlb;
+ }
+
+ public void setWeightlb(long weightlb) {
+ this.weightlb = weightlb;
+ }
+
+ public short getHeightcm() {
+ return heightcm;
+ }
+
+ public void setHeightcm(short heightcm) {
+ this.heightcm = heightcm;
+ }
+
+ public String getNickname() {
+ return nickname;
+ }
+
+ public void setNickname(String nickname) {
+ this.nickname = nickname;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getPet() {
+ return pet;
+ }
+
+ public void setPet(String pet) {
+ this.pet = pet;
+ }
+
+ public boolean isMarried() {
+ return isMarried;
+ }
+
+ public void setMarried(boolean isMarried) {
+ this.isMarried = isMarried;
+ }
+
+ }
}
diff --git a/aai-core/src/test/java/org/onap/aai/util/RestURLEncoderTest.java b/aai-core/src/test/java/org/onap/aai/util/RestURLEncoderTest.java
index 757a7bb3..a41914d0 100644
--- a/aai-core/src/test/java/org/onap/aai/util/RestURLEncoderTest.java
+++ b/aai-core/src/test/java/org/onap/aai/util/RestURLEncoderTest.java
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.util;
import static org.junit.Assert.assertEquals;
@@ -27,35 +28,35 @@ import org.junit.Test;
public class RestURLEncoderTest {
- @Test
- public void testEncodeURL() throws Exception {
+ @Test
+ public void testEncodeURL() throws Exception {
- String url = "nodeKeyTest&more-string strings";
- String encodedUrl = "nodeKeyTest%26more-string%20strings";
+ String url = "nodeKeyTest&more-string strings";
+ String encodedUrl = "nodeKeyTest%26more-string%20strings";
- String res = RestURLEncoder.encodeURL(url);
- assertEquals(encodedUrl, res);
- }
+ String res = RestURLEncoder.encodeURL(url);
+ assertEquals(encodedUrl, res);
+ }
- @Test
- public void testEncodeURL_plusSign() throws Exception {
+ @Test
+ public void testEncodeURL_plusSign() throws Exception {
- String url = "nodeKeyTest+more+string";
- String encodedUrl = "nodeKeyTest%2Bmore%2Bstring";
+ String url = "nodeKeyTest+more+string";
+ String encodedUrl = "nodeKeyTest%2Bmore%2Bstring";
- String res = RestURLEncoder.encodeURL(url);
- assertEquals(encodedUrl, res);
- }
+ String res = RestURLEncoder.encodeURL(url);
+ assertEquals(encodedUrl, res);
+ }
- @Test
- public void testEncodeURL_noException() throws Exception {
- // no exception expected, none thrown: passes.
- try {
- String encodeResult = RestURLEncoder.encodeURL("");
+ @Test
+ public void testEncodeURL_noException() throws Exception {
+ // no exception expected, none thrown: passes.
+ try {
+ String encodeResult = RestURLEncoder.encodeURL("");
- assertNotNull("Result is not null", encodeResult);
- } catch (Exception e) {
- fail();
- }
- }
+ assertNotNull("Result is not null", encodeResult);
+ } catch (Exception e) {
+ fail();
+ }
+ }
}
diff --git a/aai-core/src/test/java/org/onap/aai/util/StoreNotificationEventTest.java b/aai-core/src/test/java/org/onap/aai/util/StoreNotificationEventTest.java
index 22df113b..08cbba20 100644
--- a/aai-core/src/test/java/org/onap/aai/util/StoreNotificationEventTest.java
+++ b/aai-core/src/test/java/org/onap/aai/util/StoreNotificationEventTest.java
@@ -17,10 +17,20 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.aai.util;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
+
+import java.io.IOException;
+
+import javax.json.Json;
+import javax.json.JsonObject;
+
import org.eclipse.persistence.dynamic.DynamicEntity;
import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext;
import org.junit.Before;
@@ -36,182 +46,182 @@ import org.onap.aai.introspection.Introspector;
import org.onap.aai.introspection.Loader;
import org.onap.aai.introspection.ModelType;
-import javax.json.Json;
-import javax.json.JsonObject;
-import java.io.IOException;
+public class StoreNotificationEventTest extends AAISetup {
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+ private static AAIDmaapEventJMSProducer producer;
+ private static StoreNotificationEvent sne;
-public class StoreNotificationEventTest extends AAISetup {
+ @BeforeClass
+ public static void setUp() {
+ producer = Mockito.mock(AAIDmaapEventJMSProducer.class);
+ // sne = new StoreNotificationEvent(producer, "transiationId", "sourceOfTruth");
+ }
+
+ @Before
+ public void setUpBefore() {
+ producer = Mockito.mock(AAIDmaapEventJMSProducer.class);
+ sne = new StoreNotificationEvent(producer, "transiationId", "sourceOfTruth");
+
+ }
+
+ @Test(expected = AAIException.class)
+ public void testStoreEventNullObj() throws AAIException {
+ sne.storeEvent(new EventHeader(), null);
+ }
+
+ @Test(expected = AAIException.class)
+ public void testStoreEventInvalidObjForPojoUtils() throws AAIException {
+ sne.storeEvent(new EventHeader(), new Object());
+ }
+
+ @Test
+ public void testStoreEventEmptyEventHeader()
+ throws AAIException, JsonGenerationException, JsonMappingException, IOException {
+ JsonObject object = Json.createObjectBuilder().add("hello", "world").build();
+ String res = sne.storeEvent(new EventHeader(), object);
+
+ assertNotNull(res);
+ assertTrue(res.contains("\"cambria.partition\" : \"" + AAIConstants.UEB_PUB_PARTITION_AAI + "\""));
+ assertTrue(res.contains("\"event-header\""));
+ assertTrue(res.contains("\"id\""));
+ assertTrue(res.contains("\"timestamp\""));
+ assertTrue(res
+ .contains("\"source-name\" : \"" + AAIConfig.get("aai.notificationEvent.default.sourceName") + "\""));
+ assertTrue(res.contains("\"domain\" : \"" + AAIConfig.get("aai.notificationEvent.default.domain") + "\""));
+ assertTrue(res.contains(
+ "\"sequence-number\" : \"" + AAIConfig.get("aai.notificationEvent.default.sequenceNumber") + "\""));
+ assertTrue(res.contains("\"severity\" : \"" + AAIConfig.get("aai.notificationEvent.default.severity") + "\""));
+ assertTrue(
+ res.contains("\"event-type\" : \"" + AAIConfig.get("aai.notificationEvent.default.eventType") + "\""));
+ assertTrue(res.contains("\"version\" : \"" + AAIConfig.get("aai.notificationEvent.default.version") + "\""));
+ assertTrue(res.contains("\"action\" : \"UNK\""));
+ assertTrue(res.contains("\"entity-link\" : \"UNK\""));
+ assertTrue(res.contains("\"entity\""));
+ assertTrue(res.contains("\"hello\""));
+ assertTrue(res.contains("\"chars\" : \"world\""));
+ assertTrue(res.contains("\"string\" : \"world\""));
+ assertTrue(res.contains("\"valueType\" : \"STRING\""));
+ }
+
+ @Test
+ public void testStoreEvent() throws AAIException, JsonGenerationException, JsonMappingException, IOException {
+ JsonObject object = Json.createObjectBuilder().add("hello", "world").build();
+ EventHeader eh = new EventHeader();
+ eh.setId("123");
+ eh.setTimestamp("current-time");
+ eh.setEntityLink("entity-link");
+ eh.setAction("action!");
+ eh.setEventType("surprise");
+ eh.setDomain("PROD");
+ eh.setSourceName("source");
+ eh.setSequenceNumber("23");
+ eh.setSeverity("ALERT");
+ eh.setVersion("v12");
+
+ String res = sne.storeEvent(eh, object);
+
+ assertNotNull(res);
+ assertTrue(res.contains("\"cambria.partition\" : \"" + AAIConstants.UEB_PUB_PARTITION_AAI + "\""));
+ assertTrue(res.contains("\"event-header\""));
+ assertTrue(res.contains("\"id\" : \"123\""));
+ assertTrue(res.contains("\"timestamp\" : \"current-time\""));
+ assertTrue(res.contains("\"source-name\" : \"source\""));
+ assertTrue(res.contains("\"domain\" : \"PROD\""));
+ assertTrue(res.contains("\"sequence-number\" : \"23\""));
+ assertTrue(res.contains("\"severity\" : \"ALERT\""));
+ assertTrue(res.contains("\"event-type\" : \"surprise\""));
+ assertTrue(res.contains("\"version\" : \"v12\""));
+ assertTrue(res.contains("\"action\" : \"action!\""));
+ assertTrue(res.contains("\"entity-link\" : \"entity-link\""));
+ assertTrue(res.contains("\"entity\""));
+ assertTrue(res.contains("\"hello\""));
+ assertTrue(res.contains("\"chars\" : \"world\""));
+ assertTrue(res.contains("\"string\" : \"world\""));
+ assertTrue(res.contains("\"valueType\" : \"STRING\""));
+ }
+
+ @Test(expected = AAIException.class)
+ public void testStoreDynamicEventNullObj() throws AAIException {
+ DynamicEntity eventHeader = Mockito.mock(DynamicEntity.class);
+ DynamicJAXBContext notificationJaxbContext =
+ nodeIngestor.getContextForVersion(schemaVersions.getEdgeLabelVersion());
+ sne.storeDynamicEvent(notificationJaxbContext, "v12", eventHeader, null);
+ }
+
+ @Test(expected = Exception.class)
+ public void testStoreDynamicEventAAIException() throws Exception {
+
+ DynamicJAXBContext notificationJaxbContext =
+ nodeIngestor.getContextForVersion(schemaVersions.getEdgeLabelVersion());
+ DynamicEntity obj = Mockito.mock(DynamicEntity.class);
+ DynamicEntity eventHeader = Mockito.mock(DynamicEntity.class);
+ sne.storeDynamicEvent(notificationJaxbContext, "v12", eventHeader, obj);
+ }
+
+ @Test(expected = AAIException.class)
+ public void testStoreEventIntrospectorNullObj() throws Exception {
+ Loader loader = Mockito.mock(Loader.class);
+ sne.storeEvent(loader, null, null);
+ }
+
+ @Ignore("Stopped working since the model driven story")
+ @Test
+ public void testStoreEvent1Introspector() throws Exception {
+ Loader loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getEdgeLabelVersion());
+ Introspector eventHeader = loader.introspectorFromName("notification-event-header");
+ eventHeader.setValue("id", "123");
+ eventHeader.setValue("timestamp", "current-time");
+ eventHeader.setValue("entity-link", "entity-link");
+ eventHeader.setValue("action", "action!");
+ eventHeader.setValue("event-type", "surprise");
+ eventHeader.setValue("domain", "PROD");
+ eventHeader.setValue("source-name", "source");
+ eventHeader.setValue("sequence-number", "23");
+ eventHeader.setValue("severity", "ALERT");
+ eventHeader.setValue("version", "v12");
+ Introspector obj = loader.introspectorFromName("notification-event");
+ String res = sne.storeEvent(loader, eventHeader, obj);
+
+ assertNotNull(res);
+ assertTrue(res.contains("\"cambria.partition\":\"" + AAIConstants.UEB_PUB_PARTITION_AAI + "\""));
+ assertTrue(res.contains("\"event-header\""));
+ assertTrue(res.contains("\"id\":\"123\""));
+ assertTrue(res.contains("\"timestamp\":\"current-time\""));
+ assertTrue(res.contains("\"source-name\":\"source\""));
+ assertTrue(res.contains("\"domain\":\"PROD\""));
+ assertTrue(res.contains("\"sequence-number\":\"23\""));
+ assertTrue(res.contains("\"severity\":\"ALERT\""));
+ assertTrue(res.contains("\"event-type\":\"surprise\""));
+ assertTrue(res.contains("\"version\":\"v12\""));
+ assertTrue(res.contains("\"action\":\"action!\""));
+ assertTrue(res.contains("\"entity-link\":\"entity-link\""));
+ assertTrue(res.contains("\"notification-event\""));
+ }
+
+ @Ignore("Stopped working since the model driven story")
+ @Test
+ public void testStoreEventIntrospectorEmptyEventHeader() throws Exception {
+ Loader loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getEdgeLabelVersion());
+ Introspector eventHeader = loader.introspectorFromName("notification-event-header");
+ Introspector obj = loader.introspectorFromName("notification-event");
+
+ String res = sne.storeEvent(loader, eventHeader, obj);
- private static AAIDmaapEventJMSProducer producer;
- private static StoreNotificationEvent sne;
-
-
- @BeforeClass
- public static void setUp() {
- producer = Mockito.mock(AAIDmaapEventJMSProducer.class);
- // sne = new StoreNotificationEvent(producer, "transiationId", "sourceOfTruth");
- }
-
- @Before
- public void setUpBefore() {
- producer = Mockito.mock(AAIDmaapEventJMSProducer.class);
- sne = new StoreNotificationEvent(producer, "transiationId", "sourceOfTruth");
-
- }
-
- @Test(expected = AAIException.class)
- public void testStoreEventNullObj() throws AAIException {
- sne.storeEvent(new EventHeader(), null);
- }
-
- @Test(expected = AAIException.class)
- public void testStoreEventInvalidObjForPojoUtils() throws AAIException {
- sne.storeEvent(new EventHeader(), new Object());
- }
-
- @Test
- public void testStoreEventEmptyEventHeader() throws AAIException, JsonGenerationException, JsonMappingException, IOException {
- JsonObject object = Json.createObjectBuilder().add("hello", "world").build();
- String res = sne.storeEvent(new EventHeader(), object);
-
- assertNotNull(res);
- assertTrue(res.contains("\"cambria.partition\" : \"" + AAIConstants.UEB_PUB_PARTITION_AAI + "\""));
- assertTrue(res.contains("\"event-header\""));
- assertTrue(res.contains("\"id\""));
- assertTrue(res.contains("\"timestamp\""));
- assertTrue(res.contains("\"source-name\" : \"" + AAIConfig.get("aai.notificationEvent.default.sourceName") + "\""));
- assertTrue(res.contains("\"domain\" : \"" + AAIConfig.get("aai.notificationEvent.default.domain") + "\""));
- assertTrue(res.contains("\"sequence-number\" : \"" + AAIConfig.get("aai.notificationEvent.default.sequenceNumber") + "\""));
- assertTrue(res.contains("\"severity\" : \"" + AAIConfig.get("aai.notificationEvent.default.severity") + "\""));
- assertTrue(res.contains("\"event-type\" : \"" + AAIConfig.get("aai.notificationEvent.default.eventType") + "\""));
- assertTrue(res.contains("\"version\" : \"" + AAIConfig.get("aai.notificationEvent.default.version") + "\""));
- assertTrue(res.contains("\"action\" : \"UNK\""));
- assertTrue(res.contains("\"entity-link\" : \"UNK\""));
- assertTrue(res.contains("\"entity\""));
- assertTrue(res.contains("\"hello\""));
- assertTrue(res.contains("\"chars\" : \"world\""));
- assertTrue(res.contains("\"string\" : \"world\""));
- assertTrue(res.contains("\"valueType\" : \"STRING\""));
- }
-
- @Test
- public void testStoreEvent() throws AAIException, JsonGenerationException, JsonMappingException, IOException {
- JsonObject object = Json.createObjectBuilder().add("hello", "world").build();
- EventHeader eh = new EventHeader();
- eh.setId("123");
- eh.setTimestamp("current-time");
- eh.setEntityLink("entity-link");
- eh.setAction("action!");
- eh.setEventType("surprise");
- eh.setDomain("PROD");
- eh.setSourceName("source");
- eh.setSequenceNumber("23");
- eh.setSeverity("ALERT");
- eh.setVersion("v12");
-
- String res = sne.storeEvent(eh, object);
-
- assertNotNull(res);
- assertTrue(res.contains("\"cambria.partition\" : \"" + AAIConstants.UEB_PUB_PARTITION_AAI + "\""));
- assertTrue(res.contains("\"event-header\""));
- assertTrue(res.contains("\"id\" : \"123\""));
- assertTrue(res.contains("\"timestamp\" : \"current-time\""));
- assertTrue(res.contains("\"source-name\" : \"source\""));
- assertTrue(res.contains("\"domain\" : \"PROD\""));
- assertTrue(res.contains("\"sequence-number\" : \"23\""));
- assertTrue(res.contains("\"severity\" : \"ALERT\""));
- assertTrue(res.contains("\"event-type\" : \"surprise\""));
- assertTrue(res.contains("\"version\" : \"v12\""));
- assertTrue(res.contains("\"action\" : \"action!\""));
- assertTrue(res.contains("\"entity-link\" : \"entity-link\""));
- assertTrue(res.contains("\"entity\""));
- assertTrue(res.contains("\"hello\""));
- assertTrue(res.contains("\"chars\" : \"world\""));
- assertTrue(res.contains("\"string\" : \"world\""));
- assertTrue(res.contains("\"valueType\" : \"STRING\""));
- }
-
- @Test(expected=AAIException.class)
- public void testStoreDynamicEventNullObj() throws AAIException {
- DynamicEntity eventHeader = Mockito.mock(DynamicEntity.class);
- DynamicJAXBContext notificationJaxbContext = nodeIngestor.getContextForVersion(schemaVersions.getEdgeLabelVersion());
- sne.storeDynamicEvent(notificationJaxbContext, "v12", eventHeader, null);
- }
-
- @Test(expected = Exception.class)
- public void testStoreDynamicEventAAIException() throws Exception {
-
- DynamicJAXBContext notificationJaxbContext = nodeIngestor.getContextForVersion(schemaVersions.getEdgeLabelVersion());
- DynamicEntity obj = Mockito.mock(DynamicEntity.class);
- DynamicEntity eventHeader = Mockito.mock(DynamicEntity.class);
- sne.storeDynamicEvent(notificationJaxbContext, "v12", eventHeader, obj);
- }
-
- @Test(expected = AAIException.class)
- public void testStoreEventIntrospectorNullObj() throws Exception {
- Loader loader = Mockito.mock(Loader.class);
- sne.storeEvent(loader, null, null);
- }
-
- @Ignore("Stopped working since the model driven story")
- @Test
- public void testStoreEvent1Introspector() throws Exception {
- Loader loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getEdgeLabelVersion());
- Introspector eventHeader = loader.introspectorFromName("notification-event-header");
- eventHeader.setValue("id", "123");
- eventHeader.setValue("timestamp", "current-time");
- eventHeader.setValue("entity-link", "entity-link");
- eventHeader.setValue("action", "action!");
- eventHeader.setValue("event-type", "surprise");
- eventHeader.setValue("domain", "PROD");
- eventHeader.setValue("source-name", "source");
- eventHeader.setValue("sequence-number", "23");
- eventHeader.setValue("severity", "ALERT");
- eventHeader.setValue("version", "v12");
- Introspector obj = loader.introspectorFromName("notification-event");
- String res = sne.storeEvent(loader, eventHeader, obj);
-
- assertNotNull(res);
- assertTrue(res.contains("\"cambria.partition\":\"" + AAIConstants.UEB_PUB_PARTITION_AAI + "\""));
- assertTrue(res.contains("\"event-header\""));
- assertTrue(res.contains("\"id\":\"123\""));
- assertTrue(res.contains("\"timestamp\":\"current-time\""));
- assertTrue(res.contains("\"source-name\":\"source\""));
- assertTrue(res.contains("\"domain\":\"PROD\""));
- assertTrue(res.contains("\"sequence-number\":\"23\""));
- assertTrue(res.contains("\"severity\":\"ALERT\""));
- assertTrue(res.contains("\"event-type\":\"surprise\""));
- assertTrue(res.contains("\"version\":\"v12\""));
- assertTrue(res.contains("\"action\":\"action!\""));
- assertTrue(res.contains("\"entity-link\":\"entity-link\""));
- assertTrue(res.contains("\"notification-event\""));
- }
-
- @Ignore("Stopped working since the model driven story")
- @Test
- public void testStoreEventIntrospectorEmptyEventHeader() throws Exception {
- Loader loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getEdgeLabelVersion());
- Introspector eventHeader = loader.introspectorFromName("notification-event-header");
- Introspector obj = loader.introspectorFromName("notification-event");
-
- String res = sne.storeEvent(loader, eventHeader, obj);
-
- assertNotNull(res);
- assertTrue(res.contains("\"cambria.partition\":\"" + AAIConstants.UEB_PUB_PARTITION_AAI + "\""));
- assertTrue(res.contains("\"event-header\""));
- assertTrue(res.contains("\"id\""));
- assertTrue(res.contains("\"timestamp\""));
- assertTrue(res.contains("\"source-name\":\"" + AAIConfig.get("aai.notificationEvent.default.sourceName") + "\""));
- assertTrue(res.contains("\"domain\":\"" + AAIConfig.get("aai.notificationEvent.default.domain") + "\""));
- assertTrue(res.contains("\"sequence-number\":\"" + AAIConfig.get("aai.notificationEvent.default.sequenceNumber") + "\""));
- assertTrue(res.contains("\"severity\":\"" + AAIConfig.get("aai.notificationEvent.default.severity") + "\""));
- assertTrue(res.contains("\"event-type\":\"" + AAIConfig.get("aai.notificationEvent.default.eventType") + "\""));
- assertTrue(res.contains("\"version\":\"" + AAIConfig.get("aai.notificationEvent.default.version") + "\""));
- assertTrue(res.contains("\"action\":\"UNK\""));
- assertTrue(res.contains("\"entity-link\":\"UNK\""));
- assertTrue(res.contains("\"notification-event\""));
- }
+ assertNotNull(res);
+ assertTrue(res.contains("\"cambria.partition\":\"" + AAIConstants.UEB_PUB_PARTITION_AAI + "\""));
+ assertTrue(res.contains("\"event-header\""));
+ assertTrue(res.contains("\"id\""));
+ assertTrue(res.contains("\"timestamp\""));
+ assertTrue(
+ res.contains("\"source-name\":\"" + AAIConfig.get("aai.notificationEvent.default.sourceName") + "\""));
+ assertTrue(res.contains("\"domain\":\"" + AAIConfig.get("aai.notificationEvent.default.domain") + "\""));
+ assertTrue(res.contains(
+ "\"sequence-number\":\"" + AAIConfig.get("aai.notificationEvent.default.sequenceNumber") + "\""));
+ assertTrue(res.contains("\"severity\":\"" + AAIConfig.get("aai.notificationEvent.default.severity") + "\""));
+ assertTrue(res.contains("\"event-type\":\"" + AAIConfig.get("aai.notificationEvent.default.eventType") + "\""));
+ assertTrue(res.contains("\"version\":\"" + AAIConfig.get("aai.notificationEvent.default.version") + "\""));
+ assertTrue(res.contains("\"action\":\"UNK\""));
+ assertTrue(res.contains("\"entity-link\":\"UNK\""));
+ assertTrue(res.contains("\"notification-event\""));
+ }
}