summaryrefslogtreecommitdiffstats
path: root/aai-core/src/main/java
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 /aai-core/src/main/java
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>
Diffstat (limited to 'aai-core/src/main/java')
-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
229 files changed, 19972 insertions, 19540 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;
+
+ }
}