From 1767960099ea2983eef5218b8ce44b167ae0774c Mon Sep 17 00:00:00 2001 From: Venkata Harish K Kajur Date: Thu, 28 Sep 2017 12:43:08 -0400 Subject: Change openecomp to onap and update license Issue-ID: AAI-61 AAI-82 Change-Id: Iae98d4bf4c693c0a3203158bff98c3c5e739f453 Signed-off-by: Venkata Harish K Kajur --- aai-core/LICENSE.TXT | 42 +- aai-core/pom.xml | 8 +- .../java/org/onap/aai/audit/ListEndpoints.java | 303 +++ .../AAIUnrecognizedFunctionException.java | 43 + .../main/java/org/onap/aai/db/DbMethHelper.java | 159 ++ .../java/org/onap/aai/db/props/AAIProperties.java | 40 + .../main/java/org/onap/aai/db/schema/AuditDoc.java | 90 + .../main/java/org/onap/aai/db/schema/AuditOXM.java | 250 +++ .../java/org/onap/aai/db/schema/AuditTitan.java | 124 ++ .../main/java/org/onap/aai/db/schema/Auditor.java | 55 + .../org/onap/aai/db/schema/AuditorFactory.java | 48 + .../java/org/onap/aai/db/schema/CompareByName.java | 37 + .../main/java/org/onap/aai/db/schema/DBIndex.java | 106 + .../java/org/onap/aai/db/schema/DBProperty.java | 86 + .../java/org/onap/aai/db/schema/EdgeProperty.java | 70 + .../org/onap/aai/db/schema/ManageTitanSchema.java | 330 +++ .../main/java/org/onap/aai/db/schema/Named.java | 32 + .../java/org/onap/aai/db/schema/ScriptDriver.java | 94 + .../main/java/org/onap/aai/dbgen/DataGrooming.java | 2320 ++++++++++++++++++++ .../main/java/org/onap/aai/dbgen/GenTester.java | 144 ++ .../java/org/onap/aai/dbgen/PropertyLimitDesc.java | 28 + .../java/org/onap/aai/dbgen/SchemaGenerator.java | 194 ++ .../src/main/java/org/onap/aai/dbmap/AAIGraph.java | 197 ++ .../java/org/onap/aai/dbmap/DBConnectionType.java | 27 + .../onap/aai/dmaap/AAIDmaapEventJMSConsumer.java | 144 ++ .../onap/aai/dmaap/AAIDmaapEventJMSProducer.java | 50 + .../notificationEvent/NotificationEvent.java | 565 +++++ .../domain/notificationEvent/ObjectFactory.java | 78 + .../domain/responseMessage/AAIResponseMessage.java | 126 ++ .../responseMessage/AAIResponseMessageData.java | 79 + .../responseMessage/AAIResponseMessageDatum.java | 82 + .../responseMessage/AAIResponseMessages.java | 119 + .../aai/domain/responseMessage/package-info.java | 33 + .../onap/aai/domain/restPolicyException/Fault.java | 383 ++++ .../domain/restPolicyException/ObjectFactory.java | 96 + .../restPolicyException/PolicyException.java | 135 ++ .../domain/restPolicyException/RESTResponse.java | 87 + .../domain/restPolicyException/RequestError.java | 88 + .../org/onap/aai/domain/restResponseInfo/Info.java | 386 ++++ .../aai/domain/restResponseInfo/ObjectFactory.java | 96 + .../aai/domain/restServiceException/Fault.java | 383 ++++ .../domain/restServiceException/ObjectFactory.java | 96 + .../domain/restServiceException/RESTResponse.java | 87 + .../domain/restServiceException/RequestError.java | 87 + .../restServiceException/ServiceException.java | 135 ++ .../aai/domain/translog/TransactionLogEntries.java | 132 ++ .../aai/domain/translog/TransactionLogEntry.java | 439 ++++ .../java/org/onap/aai/exceptions/AAIException.java | 147 ++ .../onap/aai/exceptions/AAIExceptionWithInfo.java | 135 ++ .../org/onap/aai/extensions/AAIExtensionMap.java | 826 +++++++ .../onap/aai/extensions/ExtensionController.java | 146 ++ .../onap/aai/ingestModel/CreateWidgetModels.java | 145 ++ .../org/onap/aai/introspection/Introspector.java | 618 ++++++ .../aai/introspection/IntrospectorFactory.java | 66 + .../onap/aai/introspection/IntrospectorWalker.java | 194 ++ .../org/onap/aai/introspection/JSONStrategy.java | 360 +++ .../java/org/onap/aai/introspection/Loader.java | 113 + .../org/onap/aai/introspection/LoaderFactory.java | 45 + .../aai/introspection/MarshallerProperties.java | 140 ++ .../org/onap/aai/introspection/ModelInjestor.java | 174 ++ .../java/org/onap/aai/introspection/ModelType.java | 26 + .../org/onap/aai/introspection/MoxyLoader.java | 196 ++ .../org/onap/aai/introspection/MoxyStrategy.java | 386 ++++ .../org/onap/aai/introspection/PojoInjestor.java | 68 + .../org/onap/aai/introspection/PojoLoader.java | 138 ++ .../org/onap/aai/introspection/PojoStrategy.java | 377 ++++ .../onap/aai/introspection/PropertyPredicate.java | 28 + .../onap/aai/introspection/PropertyPredicates.java | 78 + .../java/org/onap/aai/introspection/Version.java | 37 + .../org/onap/aai/introspection/Visibility.java | 30 + .../java/org/onap/aai/introspection/Wanderer.java | 84 + .../exceptions/AAIUnknownObjectException.java | 43 + .../exceptions/AAIUnmarshallingException.java | 43 + .../aai/introspection/generator/CreateExample.java | 167 ++ .../aai/introspection/sideeffect/DataCopy.java | 90 + .../introspection/sideeffect/DataLinkReader.java | 98 + .../introspection/sideeffect/DataLinkWriter.java | 110 + .../aai/introspection/sideeffect/SideEffect.java | 129 ++ .../introspection/sideeffect/SideEffectRunner.java | 100 + .../sideeffect/SideEffectRunnerHelper.java | 86 + .../AAIMissingRequiredPropertyException.java | 46 + .../exceptions/AAIMultiplePropertiesException.java | 45 + .../onap/aai/introspection/tools/CreateUUID.java | 50 + .../aai/introspection/tools/DefaultFields.java | 49 + .../aai/introspection/tools/InjectKeysFromURI.java | 70 + .../introspection/tools/IntrospectorValidator.java | 319 +++ .../org/onap/aai/introspection/tools/Issue.java | 145 ++ .../aai/introspection/tools/IssueResolver.java | 34 + .../onap/aai/introspection/tools/IssueType.java | 26 + .../tools/RemoveNonVisibleProperty.java | 37 + .../org/onap/aai/introspection/tools/Severity.java | 28 + .../src/main/java/org/onap/aai/logging/CNName.java | 94 + .../onap/aai/logging/CustomLogPatternLayout.java | 29 + .../aai/logging/CustomLogPatternLayoutEncoder.java | 41 + .../java/org/onap/aai/logging/DME2RestFlag.java | 56 + .../org/onap/aai/logging/EcompElapsedTime.java | 68 + .../java/org/onap/aai/logging/EcompEncoder.java | 39 + .../org/onap/aai/logging/EcompPatternLayout.java | 32 + .../java/org/onap/aai/logging/EcompStartTime.java | 40 + .../org/onap/aai/logging/EelfClassOfCaller.java | 44 + .../java/org/onap/aai/logging/ErrorLogHelper.java | 606 +++++ .../java/org/onap/aai/logging/ErrorObject.java | 332 +++ .../aai/logging/ErrorObjectFormatException.java | 31 + .../aai/logging/ErrorObjectNotFoundException.java | 52 + .../java/org/onap/aai/logging/LogFormatTools.java | 46 + .../java/org/onap/aai/logging/LoggingContext.java | 375 ++++ .../logging/LoggingContextNotExistsException.java | 27 + .../main/java/org/onap/aai/logging/StopWatch.java | 42 + .../aai/logging/StopWatchNotStartedException.java | 43 + .../exceptions/AAIIdentityMapParseException.java | 42 + .../exceptions/AmbiguousMapAAIException.java | 42 + .../DoesNotStartWithValidNamespaceException.java | 43 + .../onap/aai/parsers/query/LegacyQueryParser.java | 228 ++ .../aai/parsers/query/ObjectNameQueryParser.java | 37 + .../org/onap/aai/parsers/query/QueryParser.java | 147 ++ .../aai/parsers/query/QueryParserStrategy.java | 92 + .../aai/parsers/query/RelationshipQueryParser.java | 66 + .../onap/aai/parsers/query/TraversalStrategy.java | 83 + .../query/UniqueRelationshipQueryParser.java | 58 + .../org/onap/aai/parsers/query/UniqueStrategy.java | 82 + .../aai/parsers/query/UniqueURIQueryParser.java | 165 ++ .../parsers/relationship/RelationshipToURI.java | 282 +++ .../java/org/onap/aai/parsers/uri/Parsable.java | 73 + .../java/org/onap/aai/parsers/uri/URIParser.java | 279 +++ .../java/org/onap/aai/parsers/uri/URIToDBKey.java | 123 ++ .../aai/parsers/uri/URIToExtensionInformation.java | 165 ++ .../java/org/onap/aai/parsers/uri/URIToObject.java | 221 ++ .../aai/parsers/uri/URIToRelationshipObject.java | 170 ++ .../java/org/onap/aai/parsers/uri/URIValidate.java | 64 + .../aai/query/builder/GraphTraversalBuilder.java | 656 ++++++ .../aai/query/builder/GremlinQueryBuilder.java | 568 +++++ .../onap/aai/query/builder/GremlinTraversal.java | 137 ++ .../org/onap/aai/query/builder/GremlinUnique.java | 138 ++ .../org/onap/aai/query/builder/QueryBuilder.java | 319 +++ .../org/onap/aai/query/builder/TraversalQuery.java | 151 ++ .../main/java/org/onap/aai/rest/RestTokens.java | 37 + .../main/java/org/onap/aai/rest/db/DBRequest.java | 252 +++ .../main/java/org/onap/aai/rest/db/HttpEntry.java | 567 +++++ .../org/onap/aai/rest/ueb/NotificationEvent.java | 100 + .../org/onap/aai/rest/ueb/UEBNotification.java | 177 ++ .../restcore/CustomJacksonJaxBJsonProvider.java | 72 + .../java/org/onap/aai/restcore/HttpMethod.java | 34 + .../JettyObfuscationConversionCommandLineUtil.java | 98 + .../main/java/org/onap/aai/restcore/MediaType.java | 67 + .../main/java/org/onap/aai/restcore/RESTAPI.java | 278 +++ .../search/GremlinGroovyShellSingleton.java | 91 + .../onap/aai/restcore/util/GenerateEdgeRules.java | 155 ++ .../java/org/onap/aai/restcore/util/URITools.java | 114 + .../onap/aai/serialization/db/AAIDirection.java | 35 + .../onap/aai/serialization/db/DBSerializer.java | 1444 ++++++++++++ .../onap/aai/serialization/db/DeleteSemantic.java | 41 + .../onap/aai/serialization/db/EdgeProperties.java | 44 + .../onap/aai/serialization/db/EdgeProperty.java | 45 + .../onap/aai/serialization/db/EdgePropertyMap.java | 60 + .../org/onap/aai/serialization/db/EdgeRule.java | 211 ++ .../org/onap/aai/serialization/db/EdgeRules.java | 589 +++++ .../org/onap/aai/serialization/db/EdgeType.java | 27 + .../org/onap/aai/serialization/db/GetAllPool.java | 47 + .../onap/aai/serialization/db/GraphSingleton.java | 70 + .../aai/serialization/db/LegacyDBSerializer.java | 35 + .../aai/serialization/db/MultiplicityRule.java | 29 + .../aai/serialization/db/TitanGraphSingleton.java | 39 + .../db/exceptions/EdgeMultiplicityException.java | 41 + .../db/exceptions/NoEdgeRuleFoundException.java | 41 + .../onap/aai/serialization/engines/QueryStyle.java | 26 + .../aai/serialization/engines/TitanDBEngine.java | 102 + .../engines/TransactionalGraphEngine.java | 246 +++ .../engines/query/GraphTraversalQueryEngine.java | 198 ++ .../engines/query/GremlinPipelineQueryEngine.java | 206 ++ .../engines/query/GremlinQueryEngine.java | 196 ++ .../serialization/engines/query/QueryEngine.java | 94 + .../aai/serialization/queryformats/Console.java | 43 + .../aai/serialization/queryformats/Format.java | 31 + .../serialization/queryformats/FormatFactory.java | 97 + .../serialization/queryformats/FormatMapper.java | 32 + .../aai/serialization/queryformats/Formatter.java | 80 + .../aai/serialization/queryformats/GraphSON.java | 63 + .../onap/aai/serialization/queryformats/IdURL.java | 71 + .../aai/serialization/queryformats/PathedURL.java | 70 + .../aai/serialization/queryformats/RawFormat.java | 190 ++ .../aai/serialization/queryformats/Resource.java | 163 ++ .../serialization/queryformats/SimpleFormat.java | 76 + .../serialization/queryformats/SubGraphStyle.java | 28 + .../exceptions/AAIFormatVertexException.java | 41 + .../exceptions/QueryParamInjectionException.java | 41 + .../serialization/queryformats/params/Depth.java | 29 + .../serialization/queryformats/params/Inject.java | 35 + .../queryformats/params/NodesOnly.java | 29 + .../serialization/queryformats/params/Setter.java | 37 + .../queryformats/utils/QueryParamInjector.java | 85 + .../queryformats/utils/UrlBuilder.java | 92 + .../serialization/tinkerpop/TreeBackedEdge.java | 81 + .../serialization/tinkerpop/TreeBackedVertex.java | 163 ++ .../java/org/onap/aai/tasks/ScheduledTasks.java | 91 + .../org/onap/aai/util/AAIApiServerURLBase.java | 81 + .../main/java/org/onap/aai/util/AAIApiVersion.java | 75 + .../main/java/org/onap/aai/util/AAICSVWriter.java | 168 ++ .../src/main/java/org/onap/aai/util/AAIConfig.java | 267 +++ .../aai/util/AAIConfigCommandLinePropGetter.java | 67 + .../main/java/org/onap/aai/util/AAIConstants.java | 152 ++ .../java/org/onap/aai/util/AAIMechIdConfig.java | 130 ++ .../java/org/onap/aai/util/AAIRSyncUtility.java | 198 ++ .../src/main/java/org/onap/aai/util/Entity.java | 197 ++ .../main/java/org/onap/aai/util/EntityList.java | 113 + .../main/java/org/onap/aai/util/FileWatcher.java | 60 + .../main/java/org/onap/aai/util/FormatDate.java | 47 + .../main/java/org/onap/aai/util/GenerateXsd.java | 1698 ++++++++++++++ .../java/org/onap/aai/util/HbaseSaltPrefixer.java | 61 + .../java/org/onap/aai/util/HttpsAuthClient.java | 136 ++ .../main/java/org/onap/aai/util/KeyValueList.java | 139 ++ .../main/java/org/onap/aai/util/MapperUtil.java | 116 + .../src/main/java/org/onap/aai/util/PojoUtils.java | 83 + .../src/main/java/org/onap/aai/util/Request.java | 161 ++ .../main/java/org/onap/aai/util/RestObject.java | 47 + .../java/org/onap/aai/util/RestURLEncoder.java | 42 + .../org/onap/aai/util/StoreNotificationEvent.java | 337 +++ .../org/onap/aai/util/UniquePropertyCheck.java | 268 +++ .../main/java/org/onap/aai/util/swagger/Api.java | 311 +++ .../java/org/onap/aai/util/swagger/Definition.java | 200 ++ .../org/onap/aai/util/swagger/GenerateSwagger.java | 433 ++++ .../onap/aai/workarounds/LegacyURITransformer.java | 94 + .../org/onap/aai/workarounds/NamingExceptions.java | 80 + .../aai/workarounds/RemoveDME2QueryParams.java | 66 + .../org/openecomp/aai/audit/ListEndpoints.java | 302 --- .../AAIUnrecognizedFunctionException.java | 42 - .../java/org/openecomp/aai/db/DbMethHelper.java | 158 -- .../org/openecomp/aai/db/props/AAIProperties.java | 39 - .../java/org/openecomp/aai/db/schema/AuditDoc.java | 89 - .../java/org/openecomp/aai/db/schema/AuditOXM.java | 249 --- .../org/openecomp/aai/db/schema/AuditTitan.java | 123 -- .../java/org/openecomp/aai/db/schema/Auditor.java | 54 - .../openecomp/aai/db/schema/AuditorFactory.java | 47 - .../org/openecomp/aai/db/schema/CompareByName.java | 36 - .../java/org/openecomp/aai/db/schema/DBIndex.java | 105 - .../org/openecomp/aai/db/schema/DBProperty.java | 85 - .../org/openecomp/aai/db/schema/EdgeProperty.java | 69 - .../openecomp/aai/db/schema/ManageTitanSchema.java | 329 --- .../java/org/openecomp/aai/db/schema/Named.java | 31 - .../org/openecomp/aai/db/schema/ScriptDriver.java | 93 - .../java/org/openecomp/aai/dbgen/DataGrooming.java | 2319 ------------------- .../java/org/openecomp/aai/dbgen/GenTester.java | 143 -- .../org/openecomp/aai/dbgen/PropertyLimitDesc.java | 27 - .../org/openecomp/aai/dbgen/SchemaGenerator.java | 193 -- .../java/org/openecomp/aai/dbmap/AAIGraph.java | 196 -- .../org/openecomp/aai/dbmap/DBConnectionType.java | 26 - .../aai/dmaap/AAIDmaapEventJMSConsumer.java | 143 -- .../aai/dmaap/AAIDmaapEventJMSProducer.java | 49 - .../notificationEvent/NotificationEvent.java | 564 ----- .../domain/notificationEvent/ObjectFactory.java | 77 - .../domain/responseMessage/AAIResponseMessage.java | 125 -- .../responseMessage/AAIResponseMessageData.java | 78 - .../responseMessage/AAIResponseMessageDatum.java | 81 - .../responseMessage/AAIResponseMessages.java | 118 - .../aai/domain/responseMessage/package-info.java | 32 - .../aai/domain/restPolicyException/Fault.java | 382 ---- .../domain/restPolicyException/ObjectFactory.java | 95 - .../restPolicyException/PolicyException.java | 134 -- .../domain/restPolicyException/RESTResponse.java | 86 - .../domain/restPolicyException/RequestError.java | 87 - .../aai/domain/restResponseInfo/Info.java | 385 ---- .../aai/domain/restResponseInfo/ObjectFactory.java | 95 - .../aai/domain/restServiceException/Fault.java | 382 ---- .../domain/restServiceException/ObjectFactory.java | 95 - .../domain/restServiceException/RESTResponse.java | 86 - .../domain/restServiceException/RequestError.java | 86 - .../restServiceException/ServiceException.java | 134 -- .../aai/domain/translog/TransactionLogEntries.java | 131 -- .../aai/domain/translog/TransactionLogEntry.java | 438 ---- .../org/openecomp/aai/exceptions/AAIException.java | 146 -- .../aai/exceptions/AAIExceptionWithInfo.java | 134 -- .../openecomp/aai/extensions/AAIExtensionMap.java | 825 ------- .../aai/extensions/ExtensionController.java | 145 -- .../aai/ingestModel/CreateWidgetModels.java | 144 -- .../openecomp/aai/introspection/Introspector.java | 617 ------ .../aai/introspection/IntrospectorFactory.java | 65 - .../aai/introspection/IntrospectorWalker.java | 193 -- .../openecomp/aai/introspection/JSONStrategy.java | 359 --- .../org/openecomp/aai/introspection/Loader.java | 112 - .../openecomp/aai/introspection/LoaderFactory.java | 44 - .../aai/introspection/MarshallerProperties.java | 139 -- .../openecomp/aai/introspection/ModelInjestor.java | 173 -- .../org/openecomp/aai/introspection/ModelType.java | 25 - .../openecomp/aai/introspection/MoxyLoader.java | 195 -- .../openecomp/aai/introspection/MoxyStrategy.java | 385 ---- .../openecomp/aai/introspection/PojoInjestor.java | 67 - .../openecomp/aai/introspection/PojoLoader.java | 137 -- .../openecomp/aai/introspection/PojoStrategy.java | 376 ---- .../aai/introspection/PropertyPredicate.java | 27 - .../aai/introspection/PropertyPredicates.java | 77 - .../org/openecomp/aai/introspection/Version.java | 36 - .../openecomp/aai/introspection/Visibility.java | 29 - .../org/openecomp/aai/introspection/Wanderer.java | 83 - .../exceptions/AAIUnknownObjectException.java | 42 - .../exceptions/AAIUnmarshallingException.java | 42 - .../aai/introspection/generator/CreateExample.java | 166 -- .../aai/introspection/sideeffect/DataCopy.java | 89 - .../introspection/sideeffect/DataLinkReader.java | 97 - .../introspection/sideeffect/DataLinkWriter.java | 109 - .../aai/introspection/sideeffect/SideEffect.java | 128 -- .../introspection/sideeffect/SideEffectRunner.java | 99 - .../sideeffect/SideEffectRunnerHelper.java | 85 - .../AAIMissingRequiredPropertyException.java | 45 - .../exceptions/AAIMultiplePropertiesException.java | 44 - .../aai/introspection/tools/CreateUUID.java | 49 - .../aai/introspection/tools/DefaultFields.java | 48 - .../aai/introspection/tools/InjectKeysFromURI.java | 69 - .../introspection/tools/IntrospectorValidator.java | 318 --- .../openecomp/aai/introspection/tools/Issue.java | 144 -- .../aai/introspection/tools/IssueResolver.java | 33 - .../aai/introspection/tools/IssueType.java | 25 - .../tools/RemoveNonVisibleProperty.java | 36 - .../aai/introspection/tools/Severity.java | 27 - .../java/org/openecomp/aai/logging/CNName.java | 93 - .../aai/logging/CustomLogPatternLayout.java | 28 - .../aai/logging/CustomLogPatternLayoutEncoder.java | 40 - .../org/openecomp/aai/logging/DME2RestFlag.java | 55 - .../openecomp/aai/logging/EcompElapsedTime.java | 67 - .../org/openecomp/aai/logging/EcompEncoder.java | 38 - .../openecomp/aai/logging/EcompPatternLayout.java | 31 - .../org/openecomp/aai/logging/EcompStartTime.java | 39 - .../openecomp/aai/logging/EelfClassOfCaller.java | 43 - .../org/openecomp/aai/logging/ErrorLogHelper.java | 605 ----- .../org/openecomp/aai/logging/ErrorObject.java | 331 --- .../aai/logging/ErrorObjectFormatException.java | 30 - .../aai/logging/ErrorObjectNotFoundException.java | 51 - .../org/openecomp/aai/logging/LogFormatTools.java | 45 - .../org/openecomp/aai/logging/LoggingContext.java | 374 ---- .../logging/LoggingContextNotExistsException.java | 26 - .../java/org/openecomp/aai/logging/StopWatch.java | 41 - .../aai/logging/StopWatchNotStartedException.java | 42 - .../exceptions/AAIIdentityMapParseException.java | 41 - .../exceptions/AmbiguousMapAAIException.java | 41 - .../DoesNotStartWithValidNamespaceException.java | 42 - .../aai/parsers/query/LegacyQueryParser.java | 227 -- .../aai/parsers/query/ObjectNameQueryParser.java | 36 - .../openecomp/aai/parsers/query/QueryParser.java | 146 -- .../aai/parsers/query/QueryParserStrategy.java | 91 - .../aai/parsers/query/RelationshipQueryParser.java | 65 - .../aai/parsers/query/TraversalStrategy.java | 82 - .../query/UniqueRelationshipQueryParser.java | 57 - .../aai/parsers/query/UniqueStrategy.java | 81 - .../aai/parsers/query/UniqueURIQueryParser.java | 164 -- .../parsers/relationship/RelationshipToURI.java | 281 --- .../org/openecomp/aai/parsers/uri/Parsable.java | 72 - .../org/openecomp/aai/parsers/uri/URIParser.java | 278 --- .../org/openecomp/aai/parsers/uri/URIToDBKey.java | 122 - .../aai/parsers/uri/URIToExtensionInformation.java | 164 -- .../org/openecomp/aai/parsers/uri/URIToObject.java | 220 -- .../aai/parsers/uri/URIToRelationshipObject.java | 169 -- .../org/openecomp/aai/parsers/uri/URIValidate.java | 63 - .../aai/query/builder/GraphTraversalBuilder.java | 655 ------ .../aai/query/builder/GremlinQueryBuilder.java | 567 ----- .../aai/query/builder/GremlinTraversal.java | 136 -- .../openecomp/aai/query/builder/GremlinUnique.java | 137 -- .../openecomp/aai/query/builder/QueryBuilder.java | 318 --- .../aai/query/builder/TraversalQuery.java | 150 -- .../java/org/openecomp/aai/rest/RestTokens.java | 36 - .../java/org/openecomp/aai/rest/db/DBRequest.java | 251 --- .../java/org/openecomp/aai/rest/db/HttpEntry.java | 566 ----- .../openecomp/aai/rest/ueb/NotificationEvent.java | 99 - .../openecomp/aai/rest/ueb/UEBNotification.java | 176 -- .../restcore/CustomJacksonJaxBJsonProvider.java | 71 - .../org/openecomp/aai/restcore/HttpMethod.java | 33 - .../JettyObfuscationConversionCommandLineUtil.java | 97 - .../java/org/openecomp/aai/restcore/MediaType.java | 66 - .../java/org/openecomp/aai/restcore/RESTAPI.java | 277 --- .../search/GremlinGroovyShellSingleton.java | 90 - .../aai/restcore/util/GenerateEdgeRules.java | 154 -- .../org/openecomp/aai/restcore/util/URITools.java | 113 - .../aai/serialization/db/AAIDirection.java | 34 - .../aai/serialization/db/DBSerializer.java | 1443 ------------ .../aai/serialization/db/DeleteSemantic.java | 40 - .../aai/serialization/db/EdgeProperties.java | 43 - .../aai/serialization/db/EdgeProperty.java | 44 - .../aai/serialization/db/EdgePropertyMap.java | 59 - .../openecomp/aai/serialization/db/EdgeRule.java | 210 -- .../openecomp/aai/serialization/db/EdgeRules.java | 588 ----- .../openecomp/aai/serialization/db/EdgeType.java | 26 - .../openecomp/aai/serialization/db/GetAllPool.java | 46 - .../aai/serialization/db/GraphSingleton.java | 69 - .../aai/serialization/db/LegacyDBSerializer.java | 34 - .../aai/serialization/db/MultiplicityRule.java | 28 - .../aai/serialization/db/TitanGraphSingleton.java | 38 - .../db/exceptions/EdgeMultiplicityException.java | 40 - .../db/exceptions/NoEdgeRuleFoundException.java | 40 - .../aai/serialization/engines/QueryStyle.java | 25 - .../aai/serialization/engines/TitanDBEngine.java | 101 - .../engines/TransactionalGraphEngine.java | 245 --- .../engines/query/GraphTraversalQueryEngine.java | 197 -- .../engines/query/GremlinPipelineQueryEngine.java | 185 -- .../engines/query/GremlinQueryEngine.java | 175 -- .../serialization/engines/query/QueryEngine.java | 93 - .../aai/serialization/queryformats/Console.java | 42 - .../aai/serialization/queryformats/Format.java | 30 - .../serialization/queryformats/FormatFactory.java | 96 - .../serialization/queryformats/FormatMapper.java | 31 - .../aai/serialization/queryformats/Formatter.java | 79 - .../aai/serialization/queryformats/GraphSON.java | 62 - .../aai/serialization/queryformats/IdURL.java | 70 - .../aai/serialization/queryformats/PathedURL.java | 69 - .../aai/serialization/queryformats/RawFormat.java | 189 -- .../aai/serialization/queryformats/Resource.java | 162 -- .../serialization/queryformats/SimpleFormat.java | 75 - .../serialization/queryformats/SubGraphStyle.java | 27 - .../exceptions/AAIFormatVertexException.java | 40 - .../exceptions/QueryParamInjectionException.java | 40 - .../serialization/queryformats/params/Depth.java | 28 - .../serialization/queryformats/params/Inject.java | 34 - .../queryformats/params/NodesOnly.java | 28 - .../serialization/queryformats/params/Setter.java | 36 - .../queryformats/utils/QueryParamInjector.java | 84 - .../queryformats/utils/UrlBuilder.java | 91 - .../serialization/tinkerpop/TreeBackedEdge.java | 80 - .../serialization/tinkerpop/TreeBackedVertex.java | 162 -- .../org/openecomp/aai/tasks/ScheduledTasks.java | 90 - .../openecomp/aai/util/AAIApiServerURLBase.java | 80 - .../java/org/openecomp/aai/util/AAIApiVersion.java | 74 - .../java/org/openecomp/aai/util/AAICSVWriter.java | 167 -- .../java/org/openecomp/aai/util/AAIConfig.java | 266 --- .../aai/util/AAIConfigCommandLinePropGetter.java | 66 - .../java/org/openecomp/aai/util/AAIConstants.java | 151 -- .../org/openecomp/aai/util/AAIMechIdConfig.java | 129 -- .../org/openecomp/aai/util/AAIRSyncUtility.java | 197 -- .../main/java/org/openecomp/aai/util/Entity.java | 196 -- .../java/org/openecomp/aai/util/EntityList.java | 112 - .../java/org/openecomp/aai/util/FileWatcher.java | 59 - .../java/org/openecomp/aai/util/FormatDate.java | 46 - .../java/org/openecomp/aai/util/GenerateXsd.java | 1697 -------------- .../org/openecomp/aai/util/HbaseSaltPrefixer.java | 60 - .../org/openecomp/aai/util/HttpsAuthClient.java | 135 -- .../java/org/openecomp/aai/util/KeyValueList.java | 138 -- .../java/org/openecomp/aai/util/MapperUtil.java | 115 - .../java/org/openecomp/aai/util/PojoUtils.java | 82 - .../main/java/org/openecomp/aai/util/Request.java | 160 -- .../java/org/openecomp/aai/util/RestObject.java | 46 - .../org/openecomp/aai/util/RestURLEncoder.java | 41 - .../openecomp/aai/util/StoreNotificationEvent.java | 336 --- .../openecomp/aai/util/UniquePropertyCheck.java | 267 --- .../java/org/openecomp/aai/util/swagger/Api.java | 310 --- .../org/openecomp/aai/util/swagger/Definition.java | 199 -- .../aai/util/swagger/GenerateSwagger.java | 432 ---- .../aai/workarounds/LegacyURITransformer.java | 93 - .../aai/workarounds/NamingExceptions.java | 79 - .../aai/workarounds/RemoveDME2QueryParams.java | 65 - aai-core/src/main/resources/EdgeRules.ftl | 39 +- aai-core/src/main/resources/swagger.html.ftl | 39 +- aai-core/src/test/java/org/onap/aai/AAISetup.java | 36 + .../org/onap/aai/exceptions/AAIExceptionTest.java | 114 + .../aai/exceptions/AAIExceptionWithInfoTest.java | 148 ++ .../aai/introspection/IntrospectorTestSpec.java | 59 + .../org/onap/aai/introspection/MoxyEngineTest.java | 46 + .../onap/aai/introspection/PojoInjestorTest.java | 60 + .../org/onap/aai/introspection/PojoLoaderTest.java | 53 + .../onap/aai/introspection/PojoStrategyTest.java | 44 + .../aai/introspection/PropertyPredicatesTest.java | 75 + .../aai/introspection/ReflectionEngineTest.java | 47 + .../aai/introspection/sideeffect/DataCopyTest.java | 268 +++ .../aai/introspection/sideeffect/DataLinkTest.java | 259 +++ .../validation/IntrospectorValidationTest.java | 96 + .../test/java/org/onap/aai/logging/CNNameTest.java | 138 ++ .../aai/logging/CustomLogPatternLayoutTest.java | 52 + .../org/onap/aai/logging/DME2RestFlagTest.java | 83 + .../onap/aai/logging/EelfClassOfCallerTest.java | 71 + .../java/org/onap/aai/logging/ErrorObjectTest.java | 163 ++ .../org/onap/aai/logging/LoggingContextTest.java | 108 + .../onap/aai/parsers/query/GraphTraversalTest.java | 815 +++++++ .../onap/aai/parsers/query/LegacyQueryTest.java | 158 ++ .../query/RelationshipGremlinQueryTest.java | 663 ++++++ .../aai/parsers/query/RelationshipQueryTest.java | 272 +++ .../parsers/query/UniqueRelationshipQueryTest.java | 297 +++ .../onap/aai/parsers/query/UniqueURIQueryTest.java | 195 ++ .../relationship/RelationshipToURITest.java | 225 ++ .../org/onap/aai/parsers/uri/URIParserTest.java | 102 + .../org/onap/aai/parsers/uri/URIToDBKeyTest.java | 186 ++ .../parsers/uri/URIToExtensionInformationTest.java | 95 + .../org/onap/aai/parsers/uri/URIToObjectTest.java | 249 +++ .../parsers/uri/URIToRelationshipObjectTest.java | 151 ++ .../org/onap/aai/query/builder/SimplePathTest.java | 124 ++ .../onap/aai/query/builder/TraversalQueryTest.java | 102 + .../java/org/onap/aai/query/builder/UntilTest.java | 113 + .../org/onap/aai/serialization/db/DbAliasTest.java | 133 ++ .../aai/serialization/db/DbSerializerTest.java | 441 ++++ .../aai/serialization/db/EdgePropertyMapTest.java | 44 + .../onap/aai/serialization/db/EdgeRulesTest.java | 238 ++ .../queryformats/QueryFormatTestHelper.java | 76 + .../queryformats/SimpleFormatTest.java | 164 ++ .../queryformats/utils/QueryParamInjectorTest.java | 60 + .../queryformats/utils/UrlBuilderTest.java | 101 + .../tinkerpop/TreeBackedVertexTest.java | 153 ++ .../java/org/onap/aai/util/GenerateXsdTest.java | 55 + .../aai/workarounds/RemoveDME2QueryParamsTest.java | 92 + .../src/test/java/org/openecomp/aai/AAISetup.java | 34 - .../openecomp/aai/exceptions/AAIExceptionTest.java | 113 - .../aai/exceptions/AAIExceptionWithInfoTest.java | 147 -- .../aai/introspection/IntrospectorTestSpec.java | 58 - .../aai/introspection/MoxyEngineTest.java | 45 - .../aai/introspection/PojoInjestorTest.java | 59 - .../aai/introspection/PojoLoaderTest.java | 52 - .../aai/introspection/PojoStrategyTest.java | 43 - .../aai/introspection/PropertyPredicatesTest.java | 74 - .../aai/introspection/ReflectionEngineTest.java | 46 - .../aai/introspection/sideeffect/DataCopyTest.java | 267 --- .../aai/introspection/sideeffect/DataLinkTest.java | 258 --- .../validation/IntrospectorValidationTest.java | 95 - .../java/org/openecomp/aai/logging/CNNameTest.java | 137 -- .../aai/logging/CustomLogPatternLayoutTest.java | 51 - .../openecomp/aai/logging/DME2RestFlagTest.java | 82 - .../aai/logging/EelfClassOfCallerTest.java | 70 - .../org/openecomp/aai/logging/ErrorObjectTest.java | 162 -- .../openecomp/aai/logging/LoggingContextTest.java | 107 - .../aai/parsers/query/GraphTraversalTest.java | 814 ------- .../aai/parsers/query/LegacyQueryTest.java | 157 -- .../query/RelationshipGremlinQueryTest.java | 662 ------ .../aai/parsers/query/RelationshipQueryTest.java | 271 --- .../parsers/query/UniqueRelationshipQueryTest.java | 296 --- .../aai/parsers/query/UniqueURIQueryTest.java | 194 -- .../relationship/RelationshipToURITest.java | 224 -- .../openecomp/aai/parsers/uri/URIParserTest.java | 101 - .../openecomp/aai/parsers/uri/URIToDBKeyTest.java | 185 -- .../parsers/uri/URIToExtensionInformationTest.java | 94 - .../openecomp/aai/parsers/uri/URIToObjectTest.java | 248 --- .../parsers/uri/URIToRelationshipObjectTest.java | 150 -- .../aai/query/builder/SimplePathTest.java | 123 -- .../aai/query/builder/TraversalQueryTest.java | 101 - .../org/openecomp/aai/query/builder/UntilTest.java | 112 - .../aai/serialization/db/DbAliasTest.java | 132 -- .../aai/serialization/db/DbSerializerTest.java | 440 ---- .../aai/serialization/db/EdgePropertyMapTest.java | 43 - .../aai/serialization/db/EdgeRulesTest.java | 237 -- .../queryformats/QueryFormatTestHelper.java | 75 - .../queryformats/SimpleFormatTest.java | 163 -- .../queryformats/utils/QueryParamInjectorTest.java | 59 - .../queryformats/utils/UrlBuilderTest.java | 100 - .../tinkerpop/TreeBackedVertexTest.java | 152 -- .../org/openecomp/aai/util/GenerateXsdTest.java | 54 - .../aai/workarounds/RemoveDME2QueryParamsTest.java | 91 - .../etc/appprops/aaiconfig.properties | 16 +- .../etc/appprops/titan-cached.properties | 22 + .../etc/appprops/titan-realtime.properties | 22 + .../bundleconfig-local/etc/oxm/aai_oxm_v10.xml | 37 +- .../bundleconfig-local/etc/oxm/aai_oxm_v11.xml | 37 +- .../bundleconfig-local/etc/oxm/aai_oxm_v2.xml | 37 +- .../bundleconfig-local/etc/oxm/aai_oxm_v8.xml | 37 +- .../bundleconfig-local/etc/oxm/aai_oxm_v9.xml | 41 +- aai-core/src/test/resources/logback.xml | 45 +- .../openecomp/aai/introspection/aai_oxm_v10.xml | 629 +++--- .../org/openecomp/aai/introspection/aai_oxm_v8.xml | 371 ++-- .../org/openecomp/aai/introspection/aai_oxm_v9.xml | 69 +- 548 files changed, 42796 insertions(+), 42408 deletions(-) create mode 100644 aai-core/src/main/java/org/onap/aai/audit/ListEndpoints.java create mode 100644 aai-core/src/main/java/org/onap/aai/auth/exceptions/AAIUnrecognizedFunctionException.java create mode 100644 aai-core/src/main/java/org/onap/aai/db/DbMethHelper.java create mode 100644 aai-core/src/main/java/org/onap/aai/db/props/AAIProperties.java create mode 100644 aai-core/src/main/java/org/onap/aai/db/schema/AuditDoc.java create mode 100644 aai-core/src/main/java/org/onap/aai/db/schema/AuditOXM.java create mode 100644 aai-core/src/main/java/org/onap/aai/db/schema/AuditTitan.java create mode 100644 aai-core/src/main/java/org/onap/aai/db/schema/Auditor.java create mode 100644 aai-core/src/main/java/org/onap/aai/db/schema/AuditorFactory.java create mode 100644 aai-core/src/main/java/org/onap/aai/db/schema/CompareByName.java create mode 100644 aai-core/src/main/java/org/onap/aai/db/schema/DBIndex.java create mode 100644 aai-core/src/main/java/org/onap/aai/db/schema/DBProperty.java create mode 100644 aai-core/src/main/java/org/onap/aai/db/schema/EdgeProperty.java create mode 100644 aai-core/src/main/java/org/onap/aai/db/schema/ManageTitanSchema.java create mode 100644 aai-core/src/main/java/org/onap/aai/db/schema/Named.java create mode 100644 aai-core/src/main/java/org/onap/aai/db/schema/ScriptDriver.java create mode 100644 aai-core/src/main/java/org/onap/aai/dbgen/DataGrooming.java create mode 100644 aai-core/src/main/java/org/onap/aai/dbgen/GenTester.java create mode 100644 aai-core/src/main/java/org/onap/aai/dbgen/PropertyLimitDesc.java create mode 100644 aai-core/src/main/java/org/onap/aai/dbgen/SchemaGenerator.java create mode 100644 aai-core/src/main/java/org/onap/aai/dbmap/AAIGraph.java create mode 100644 aai-core/src/main/java/org/onap/aai/dbmap/DBConnectionType.java create mode 100644 aai-core/src/main/java/org/onap/aai/dmaap/AAIDmaapEventJMSConsumer.java create mode 100644 aai-core/src/main/java/org/onap/aai/dmaap/AAIDmaapEventJMSProducer.java create mode 100644 aai-core/src/main/java/org/onap/aai/domain/notificationEvent/NotificationEvent.java create mode 100644 aai-core/src/main/java/org/onap/aai/domain/notificationEvent/ObjectFactory.java create mode 100644 aai-core/src/main/java/org/onap/aai/domain/responseMessage/AAIResponseMessage.java create mode 100644 aai-core/src/main/java/org/onap/aai/domain/responseMessage/AAIResponseMessageData.java create mode 100644 aai-core/src/main/java/org/onap/aai/domain/responseMessage/AAIResponseMessageDatum.java create mode 100644 aai-core/src/main/java/org/onap/aai/domain/responseMessage/AAIResponseMessages.java create mode 100644 aai-core/src/main/java/org/onap/aai/domain/responseMessage/package-info.java create mode 100644 aai-core/src/main/java/org/onap/aai/domain/restPolicyException/Fault.java create mode 100644 aai-core/src/main/java/org/onap/aai/domain/restPolicyException/ObjectFactory.java create mode 100644 aai-core/src/main/java/org/onap/aai/domain/restPolicyException/PolicyException.java create mode 100644 aai-core/src/main/java/org/onap/aai/domain/restPolicyException/RESTResponse.java create mode 100644 aai-core/src/main/java/org/onap/aai/domain/restPolicyException/RequestError.java create mode 100644 aai-core/src/main/java/org/onap/aai/domain/restResponseInfo/Info.java create mode 100644 aai-core/src/main/java/org/onap/aai/domain/restResponseInfo/ObjectFactory.java create mode 100644 aai-core/src/main/java/org/onap/aai/domain/restServiceException/Fault.java create mode 100644 aai-core/src/main/java/org/onap/aai/domain/restServiceException/ObjectFactory.java create mode 100644 aai-core/src/main/java/org/onap/aai/domain/restServiceException/RESTResponse.java create mode 100644 aai-core/src/main/java/org/onap/aai/domain/restServiceException/RequestError.java create mode 100644 aai-core/src/main/java/org/onap/aai/domain/restServiceException/ServiceException.java create mode 100644 aai-core/src/main/java/org/onap/aai/domain/translog/TransactionLogEntries.java create mode 100644 aai-core/src/main/java/org/onap/aai/domain/translog/TransactionLogEntry.java create mode 100644 aai-core/src/main/java/org/onap/aai/exceptions/AAIException.java create mode 100644 aai-core/src/main/java/org/onap/aai/exceptions/AAIExceptionWithInfo.java create mode 100644 aai-core/src/main/java/org/onap/aai/extensions/AAIExtensionMap.java create mode 100644 aai-core/src/main/java/org/onap/aai/extensions/ExtensionController.java create mode 100644 aai-core/src/main/java/org/onap/aai/ingestModel/CreateWidgetModels.java create mode 100644 aai-core/src/main/java/org/onap/aai/introspection/Introspector.java create mode 100644 aai-core/src/main/java/org/onap/aai/introspection/IntrospectorFactory.java create mode 100644 aai-core/src/main/java/org/onap/aai/introspection/IntrospectorWalker.java create mode 100644 aai-core/src/main/java/org/onap/aai/introspection/JSONStrategy.java create mode 100644 aai-core/src/main/java/org/onap/aai/introspection/Loader.java create mode 100644 aai-core/src/main/java/org/onap/aai/introspection/LoaderFactory.java create mode 100644 aai-core/src/main/java/org/onap/aai/introspection/MarshallerProperties.java create mode 100644 aai-core/src/main/java/org/onap/aai/introspection/ModelInjestor.java create mode 100644 aai-core/src/main/java/org/onap/aai/introspection/ModelType.java create mode 100644 aai-core/src/main/java/org/onap/aai/introspection/MoxyLoader.java create mode 100644 aai-core/src/main/java/org/onap/aai/introspection/MoxyStrategy.java create mode 100644 aai-core/src/main/java/org/onap/aai/introspection/PojoInjestor.java create mode 100644 aai-core/src/main/java/org/onap/aai/introspection/PojoLoader.java create mode 100644 aai-core/src/main/java/org/onap/aai/introspection/PojoStrategy.java create mode 100644 aai-core/src/main/java/org/onap/aai/introspection/PropertyPredicate.java create mode 100644 aai-core/src/main/java/org/onap/aai/introspection/PropertyPredicates.java create mode 100644 aai-core/src/main/java/org/onap/aai/introspection/Version.java create mode 100644 aai-core/src/main/java/org/onap/aai/introspection/Visibility.java create mode 100644 aai-core/src/main/java/org/onap/aai/introspection/Wanderer.java create mode 100644 aai-core/src/main/java/org/onap/aai/introspection/exceptions/AAIUnknownObjectException.java create mode 100644 aai-core/src/main/java/org/onap/aai/introspection/exceptions/AAIUnmarshallingException.java create mode 100644 aai-core/src/main/java/org/onap/aai/introspection/generator/CreateExample.java create mode 100644 aai-core/src/main/java/org/onap/aai/introspection/sideeffect/DataCopy.java create mode 100644 aai-core/src/main/java/org/onap/aai/introspection/sideeffect/DataLinkReader.java create mode 100644 aai-core/src/main/java/org/onap/aai/introspection/sideeffect/DataLinkWriter.java create mode 100644 aai-core/src/main/java/org/onap/aai/introspection/sideeffect/SideEffect.java create mode 100644 aai-core/src/main/java/org/onap/aai/introspection/sideeffect/SideEffectRunner.java create mode 100644 aai-core/src/main/java/org/onap/aai/introspection/sideeffect/SideEffectRunnerHelper.java create mode 100644 aai-core/src/main/java/org/onap/aai/introspection/sideeffect/exceptions/AAIMissingRequiredPropertyException.java create mode 100644 aai-core/src/main/java/org/onap/aai/introspection/sideeffect/exceptions/AAIMultiplePropertiesException.java create mode 100644 aai-core/src/main/java/org/onap/aai/introspection/tools/CreateUUID.java create mode 100644 aai-core/src/main/java/org/onap/aai/introspection/tools/DefaultFields.java create mode 100644 aai-core/src/main/java/org/onap/aai/introspection/tools/InjectKeysFromURI.java create mode 100644 aai-core/src/main/java/org/onap/aai/introspection/tools/IntrospectorValidator.java create mode 100644 aai-core/src/main/java/org/onap/aai/introspection/tools/Issue.java create mode 100644 aai-core/src/main/java/org/onap/aai/introspection/tools/IssueResolver.java create mode 100644 aai-core/src/main/java/org/onap/aai/introspection/tools/IssueType.java create mode 100644 aai-core/src/main/java/org/onap/aai/introspection/tools/RemoveNonVisibleProperty.java create mode 100644 aai-core/src/main/java/org/onap/aai/introspection/tools/Severity.java create mode 100644 aai-core/src/main/java/org/onap/aai/logging/CNName.java create mode 100644 aai-core/src/main/java/org/onap/aai/logging/CustomLogPatternLayout.java create mode 100644 aai-core/src/main/java/org/onap/aai/logging/CustomLogPatternLayoutEncoder.java create mode 100644 aai-core/src/main/java/org/onap/aai/logging/DME2RestFlag.java create mode 100644 aai-core/src/main/java/org/onap/aai/logging/EcompElapsedTime.java create mode 100644 aai-core/src/main/java/org/onap/aai/logging/EcompEncoder.java create mode 100644 aai-core/src/main/java/org/onap/aai/logging/EcompPatternLayout.java create mode 100644 aai-core/src/main/java/org/onap/aai/logging/EcompStartTime.java create mode 100644 aai-core/src/main/java/org/onap/aai/logging/EelfClassOfCaller.java create mode 100644 aai-core/src/main/java/org/onap/aai/logging/ErrorLogHelper.java create mode 100644 aai-core/src/main/java/org/onap/aai/logging/ErrorObject.java create mode 100644 aai-core/src/main/java/org/onap/aai/logging/ErrorObjectFormatException.java create mode 100644 aai-core/src/main/java/org/onap/aai/logging/ErrorObjectNotFoundException.java create mode 100644 aai-core/src/main/java/org/onap/aai/logging/LogFormatTools.java create mode 100644 aai-core/src/main/java/org/onap/aai/logging/LoggingContext.java create mode 100644 aai-core/src/main/java/org/onap/aai/logging/LoggingContextNotExistsException.java create mode 100644 aai-core/src/main/java/org/onap/aai/logging/StopWatch.java create mode 100644 aai-core/src/main/java/org/onap/aai/logging/StopWatchNotStartedException.java create mode 100644 aai-core/src/main/java/org/onap/aai/parsers/exceptions/AAIIdentityMapParseException.java create mode 100644 aai-core/src/main/java/org/onap/aai/parsers/exceptions/AmbiguousMapAAIException.java create mode 100644 aai-core/src/main/java/org/onap/aai/parsers/exceptions/DoesNotStartWithValidNamespaceException.java create mode 100644 aai-core/src/main/java/org/onap/aai/parsers/query/LegacyQueryParser.java create mode 100644 aai-core/src/main/java/org/onap/aai/parsers/query/ObjectNameQueryParser.java create mode 100644 aai-core/src/main/java/org/onap/aai/parsers/query/QueryParser.java create mode 100644 aai-core/src/main/java/org/onap/aai/parsers/query/QueryParserStrategy.java create mode 100644 aai-core/src/main/java/org/onap/aai/parsers/query/RelationshipQueryParser.java create mode 100644 aai-core/src/main/java/org/onap/aai/parsers/query/TraversalStrategy.java create mode 100644 aai-core/src/main/java/org/onap/aai/parsers/query/UniqueRelationshipQueryParser.java create mode 100644 aai-core/src/main/java/org/onap/aai/parsers/query/UniqueStrategy.java create mode 100644 aai-core/src/main/java/org/onap/aai/parsers/query/UniqueURIQueryParser.java create mode 100644 aai-core/src/main/java/org/onap/aai/parsers/relationship/RelationshipToURI.java create mode 100644 aai-core/src/main/java/org/onap/aai/parsers/uri/Parsable.java create mode 100644 aai-core/src/main/java/org/onap/aai/parsers/uri/URIParser.java create mode 100644 aai-core/src/main/java/org/onap/aai/parsers/uri/URIToDBKey.java create mode 100644 aai-core/src/main/java/org/onap/aai/parsers/uri/URIToExtensionInformation.java create mode 100644 aai-core/src/main/java/org/onap/aai/parsers/uri/URIToObject.java create mode 100644 aai-core/src/main/java/org/onap/aai/parsers/uri/URIToRelationshipObject.java create mode 100644 aai-core/src/main/java/org/onap/aai/parsers/uri/URIValidate.java create mode 100644 aai-core/src/main/java/org/onap/aai/query/builder/GraphTraversalBuilder.java create mode 100644 aai-core/src/main/java/org/onap/aai/query/builder/GremlinQueryBuilder.java create mode 100644 aai-core/src/main/java/org/onap/aai/query/builder/GremlinTraversal.java create mode 100644 aai-core/src/main/java/org/onap/aai/query/builder/GremlinUnique.java create mode 100644 aai-core/src/main/java/org/onap/aai/query/builder/QueryBuilder.java create mode 100644 aai-core/src/main/java/org/onap/aai/query/builder/TraversalQuery.java create mode 100644 aai-core/src/main/java/org/onap/aai/rest/RestTokens.java create mode 100644 aai-core/src/main/java/org/onap/aai/rest/db/DBRequest.java create mode 100644 aai-core/src/main/java/org/onap/aai/rest/db/HttpEntry.java create mode 100644 aai-core/src/main/java/org/onap/aai/rest/ueb/NotificationEvent.java create mode 100644 aai-core/src/main/java/org/onap/aai/rest/ueb/UEBNotification.java create mode 100644 aai-core/src/main/java/org/onap/aai/restcore/CustomJacksonJaxBJsonProvider.java create mode 100644 aai-core/src/main/java/org/onap/aai/restcore/HttpMethod.java create mode 100644 aai-core/src/main/java/org/onap/aai/restcore/JettyObfuscationConversionCommandLineUtil.java create mode 100644 aai-core/src/main/java/org/onap/aai/restcore/MediaType.java create mode 100644 aai-core/src/main/java/org/onap/aai/restcore/RESTAPI.java create mode 100644 aai-core/src/main/java/org/onap/aai/restcore/search/GremlinGroovyShellSingleton.java create mode 100644 aai-core/src/main/java/org/onap/aai/restcore/util/GenerateEdgeRules.java create mode 100644 aai-core/src/main/java/org/onap/aai/restcore/util/URITools.java create mode 100644 aai-core/src/main/java/org/onap/aai/serialization/db/AAIDirection.java create mode 100644 aai-core/src/main/java/org/onap/aai/serialization/db/DBSerializer.java create mode 100644 aai-core/src/main/java/org/onap/aai/serialization/db/DeleteSemantic.java create mode 100644 aai-core/src/main/java/org/onap/aai/serialization/db/EdgeProperties.java create mode 100644 aai-core/src/main/java/org/onap/aai/serialization/db/EdgeProperty.java create mode 100644 aai-core/src/main/java/org/onap/aai/serialization/db/EdgePropertyMap.java create mode 100644 aai-core/src/main/java/org/onap/aai/serialization/db/EdgeRule.java create mode 100644 aai-core/src/main/java/org/onap/aai/serialization/db/EdgeRules.java create mode 100644 aai-core/src/main/java/org/onap/aai/serialization/db/EdgeType.java create mode 100644 aai-core/src/main/java/org/onap/aai/serialization/db/GetAllPool.java create mode 100644 aai-core/src/main/java/org/onap/aai/serialization/db/GraphSingleton.java create mode 100644 aai-core/src/main/java/org/onap/aai/serialization/db/LegacyDBSerializer.java create mode 100644 aai-core/src/main/java/org/onap/aai/serialization/db/MultiplicityRule.java create mode 100644 aai-core/src/main/java/org/onap/aai/serialization/db/TitanGraphSingleton.java create mode 100644 aai-core/src/main/java/org/onap/aai/serialization/db/exceptions/EdgeMultiplicityException.java create mode 100644 aai-core/src/main/java/org/onap/aai/serialization/db/exceptions/NoEdgeRuleFoundException.java create mode 100644 aai-core/src/main/java/org/onap/aai/serialization/engines/QueryStyle.java create mode 100644 aai-core/src/main/java/org/onap/aai/serialization/engines/TitanDBEngine.java create mode 100644 aai-core/src/main/java/org/onap/aai/serialization/engines/TransactionalGraphEngine.java create mode 100644 aai-core/src/main/java/org/onap/aai/serialization/engines/query/GraphTraversalQueryEngine.java create mode 100644 aai-core/src/main/java/org/onap/aai/serialization/engines/query/GremlinPipelineQueryEngine.java create mode 100644 aai-core/src/main/java/org/onap/aai/serialization/engines/query/GremlinQueryEngine.java create mode 100644 aai-core/src/main/java/org/onap/aai/serialization/engines/query/QueryEngine.java create mode 100644 aai-core/src/main/java/org/onap/aai/serialization/queryformats/Console.java create mode 100644 aai-core/src/main/java/org/onap/aai/serialization/queryformats/Format.java create mode 100644 aai-core/src/main/java/org/onap/aai/serialization/queryformats/FormatFactory.java create mode 100644 aai-core/src/main/java/org/onap/aai/serialization/queryformats/FormatMapper.java create mode 100644 aai-core/src/main/java/org/onap/aai/serialization/queryformats/Formatter.java create mode 100644 aai-core/src/main/java/org/onap/aai/serialization/queryformats/GraphSON.java create mode 100644 aai-core/src/main/java/org/onap/aai/serialization/queryformats/IdURL.java create mode 100644 aai-core/src/main/java/org/onap/aai/serialization/queryformats/PathedURL.java create mode 100644 aai-core/src/main/java/org/onap/aai/serialization/queryformats/RawFormat.java create mode 100644 aai-core/src/main/java/org/onap/aai/serialization/queryformats/Resource.java create mode 100644 aai-core/src/main/java/org/onap/aai/serialization/queryformats/SimpleFormat.java create mode 100644 aai-core/src/main/java/org/onap/aai/serialization/queryformats/SubGraphStyle.java create mode 100644 aai-core/src/main/java/org/onap/aai/serialization/queryformats/exceptions/AAIFormatVertexException.java create mode 100644 aai-core/src/main/java/org/onap/aai/serialization/queryformats/exceptions/QueryParamInjectionException.java create mode 100644 aai-core/src/main/java/org/onap/aai/serialization/queryformats/params/Depth.java create mode 100644 aai-core/src/main/java/org/onap/aai/serialization/queryformats/params/Inject.java create mode 100644 aai-core/src/main/java/org/onap/aai/serialization/queryformats/params/NodesOnly.java create mode 100644 aai-core/src/main/java/org/onap/aai/serialization/queryformats/params/Setter.java create mode 100644 aai-core/src/main/java/org/onap/aai/serialization/queryformats/utils/QueryParamInjector.java create mode 100644 aai-core/src/main/java/org/onap/aai/serialization/queryformats/utils/UrlBuilder.java create mode 100644 aai-core/src/main/java/org/onap/aai/serialization/tinkerpop/TreeBackedEdge.java create mode 100644 aai-core/src/main/java/org/onap/aai/serialization/tinkerpop/TreeBackedVertex.java create mode 100644 aai-core/src/main/java/org/onap/aai/tasks/ScheduledTasks.java create mode 100644 aai-core/src/main/java/org/onap/aai/util/AAIApiServerURLBase.java create mode 100644 aai-core/src/main/java/org/onap/aai/util/AAIApiVersion.java create mode 100644 aai-core/src/main/java/org/onap/aai/util/AAICSVWriter.java create mode 100644 aai-core/src/main/java/org/onap/aai/util/AAIConfig.java create mode 100644 aai-core/src/main/java/org/onap/aai/util/AAIConfigCommandLinePropGetter.java create mode 100644 aai-core/src/main/java/org/onap/aai/util/AAIConstants.java create mode 100644 aai-core/src/main/java/org/onap/aai/util/AAIMechIdConfig.java create mode 100644 aai-core/src/main/java/org/onap/aai/util/AAIRSyncUtility.java create mode 100644 aai-core/src/main/java/org/onap/aai/util/Entity.java create mode 100644 aai-core/src/main/java/org/onap/aai/util/EntityList.java create mode 100644 aai-core/src/main/java/org/onap/aai/util/FileWatcher.java create mode 100644 aai-core/src/main/java/org/onap/aai/util/FormatDate.java create mode 100644 aai-core/src/main/java/org/onap/aai/util/GenerateXsd.java create mode 100644 aai-core/src/main/java/org/onap/aai/util/HbaseSaltPrefixer.java create mode 100644 aai-core/src/main/java/org/onap/aai/util/HttpsAuthClient.java create mode 100644 aai-core/src/main/java/org/onap/aai/util/KeyValueList.java create mode 100644 aai-core/src/main/java/org/onap/aai/util/MapperUtil.java create mode 100644 aai-core/src/main/java/org/onap/aai/util/PojoUtils.java create mode 100644 aai-core/src/main/java/org/onap/aai/util/Request.java create mode 100644 aai-core/src/main/java/org/onap/aai/util/RestObject.java create mode 100644 aai-core/src/main/java/org/onap/aai/util/RestURLEncoder.java create mode 100644 aai-core/src/main/java/org/onap/aai/util/StoreNotificationEvent.java create mode 100644 aai-core/src/main/java/org/onap/aai/util/UniquePropertyCheck.java create mode 100644 aai-core/src/main/java/org/onap/aai/util/swagger/Api.java create mode 100644 aai-core/src/main/java/org/onap/aai/util/swagger/Definition.java create mode 100644 aai-core/src/main/java/org/onap/aai/util/swagger/GenerateSwagger.java create mode 100644 aai-core/src/main/java/org/onap/aai/workarounds/LegacyURITransformer.java create mode 100644 aai-core/src/main/java/org/onap/aai/workarounds/NamingExceptions.java create mode 100644 aai-core/src/main/java/org/onap/aai/workarounds/RemoveDME2QueryParams.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/audit/ListEndpoints.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/auth/exceptions/AAIUnrecognizedFunctionException.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/db/DbMethHelper.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/db/props/AAIProperties.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/db/schema/AuditDoc.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/db/schema/AuditOXM.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/db/schema/AuditTitan.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/db/schema/Auditor.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/db/schema/AuditorFactory.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/db/schema/CompareByName.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/db/schema/DBIndex.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/db/schema/DBProperty.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/db/schema/EdgeProperty.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/db/schema/ManageTitanSchema.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/db/schema/Named.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/db/schema/ScriptDriver.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/dbgen/DataGrooming.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/dbgen/GenTester.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/dbgen/PropertyLimitDesc.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/dbgen/SchemaGenerator.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/dbmap/AAIGraph.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/dbmap/DBConnectionType.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/dmaap/AAIDmaapEventJMSConsumer.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/dmaap/AAIDmaapEventJMSProducer.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/domain/notificationEvent/NotificationEvent.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/domain/notificationEvent/ObjectFactory.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/domain/responseMessage/AAIResponseMessage.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/domain/responseMessage/AAIResponseMessageData.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/domain/responseMessage/AAIResponseMessageDatum.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/domain/responseMessage/AAIResponseMessages.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/domain/responseMessage/package-info.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/domain/restPolicyException/Fault.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/domain/restPolicyException/ObjectFactory.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/domain/restPolicyException/PolicyException.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/domain/restPolicyException/RESTResponse.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/domain/restPolicyException/RequestError.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/domain/restResponseInfo/Info.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/domain/restResponseInfo/ObjectFactory.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/domain/restServiceException/Fault.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/domain/restServiceException/ObjectFactory.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/domain/restServiceException/RESTResponse.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/domain/restServiceException/RequestError.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/domain/restServiceException/ServiceException.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/domain/translog/TransactionLogEntries.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/domain/translog/TransactionLogEntry.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/exceptions/AAIException.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/exceptions/AAIExceptionWithInfo.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/extensions/AAIExtensionMap.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/extensions/ExtensionController.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/ingestModel/CreateWidgetModels.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/introspection/Introspector.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/introspection/IntrospectorFactory.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/introspection/IntrospectorWalker.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/introspection/JSONStrategy.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/introspection/Loader.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/introspection/LoaderFactory.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/introspection/MarshallerProperties.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/introspection/ModelInjestor.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/introspection/ModelType.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/introspection/MoxyLoader.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/introspection/MoxyStrategy.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/introspection/PojoInjestor.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/introspection/PojoLoader.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/introspection/PojoStrategy.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/introspection/PropertyPredicate.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/introspection/PropertyPredicates.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/introspection/Version.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/introspection/Visibility.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/introspection/Wanderer.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/introspection/exceptions/AAIUnknownObjectException.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/introspection/exceptions/AAIUnmarshallingException.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/introspection/generator/CreateExample.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/introspection/sideeffect/DataCopy.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/introspection/sideeffect/DataLinkReader.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/introspection/sideeffect/DataLinkWriter.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/introspection/sideeffect/SideEffect.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/introspection/sideeffect/SideEffectRunner.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/introspection/sideeffect/SideEffectRunnerHelper.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/introspection/sideeffect/exceptions/AAIMissingRequiredPropertyException.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/introspection/sideeffect/exceptions/AAIMultiplePropertiesException.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/introspection/tools/CreateUUID.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/introspection/tools/DefaultFields.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/introspection/tools/InjectKeysFromURI.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/introspection/tools/IntrospectorValidator.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/introspection/tools/Issue.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/introspection/tools/IssueResolver.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/introspection/tools/IssueType.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/introspection/tools/RemoveNonVisibleProperty.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/introspection/tools/Severity.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/logging/CNName.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/logging/CustomLogPatternLayout.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/logging/CustomLogPatternLayoutEncoder.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/logging/DME2RestFlag.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/logging/EcompElapsedTime.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/logging/EcompEncoder.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/logging/EcompPatternLayout.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/logging/EcompStartTime.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/logging/EelfClassOfCaller.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/logging/ErrorLogHelper.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/logging/ErrorObject.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/logging/ErrorObjectFormatException.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/logging/ErrorObjectNotFoundException.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/logging/LogFormatTools.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/logging/LoggingContext.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/logging/LoggingContextNotExistsException.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/logging/StopWatch.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/logging/StopWatchNotStartedException.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/parsers/exceptions/AAIIdentityMapParseException.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/parsers/exceptions/AmbiguousMapAAIException.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/parsers/exceptions/DoesNotStartWithValidNamespaceException.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/parsers/query/LegacyQueryParser.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/parsers/query/ObjectNameQueryParser.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/parsers/query/QueryParser.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/parsers/query/QueryParserStrategy.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/parsers/query/RelationshipQueryParser.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/parsers/query/TraversalStrategy.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/parsers/query/UniqueRelationshipQueryParser.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/parsers/query/UniqueStrategy.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/parsers/query/UniqueURIQueryParser.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/parsers/relationship/RelationshipToURI.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/parsers/uri/Parsable.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/parsers/uri/URIParser.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/parsers/uri/URIToDBKey.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/parsers/uri/URIToExtensionInformation.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/parsers/uri/URIToObject.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/parsers/uri/URIToRelationshipObject.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/parsers/uri/URIValidate.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/query/builder/GraphTraversalBuilder.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/query/builder/GremlinQueryBuilder.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/query/builder/GremlinTraversal.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/query/builder/GremlinUnique.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/query/builder/QueryBuilder.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/query/builder/TraversalQuery.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/rest/RestTokens.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/rest/db/DBRequest.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/rest/db/HttpEntry.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/rest/ueb/NotificationEvent.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/rest/ueb/UEBNotification.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/restcore/CustomJacksonJaxBJsonProvider.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/restcore/HttpMethod.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/restcore/JettyObfuscationConversionCommandLineUtil.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/restcore/MediaType.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/restcore/RESTAPI.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/restcore/search/GremlinGroovyShellSingleton.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/restcore/util/GenerateEdgeRules.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/restcore/util/URITools.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/serialization/db/AAIDirection.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/serialization/db/DBSerializer.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/serialization/db/DeleteSemantic.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/serialization/db/EdgeProperties.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/serialization/db/EdgeProperty.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/serialization/db/EdgePropertyMap.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/serialization/db/EdgeRule.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/serialization/db/EdgeRules.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/serialization/db/EdgeType.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/serialization/db/GetAllPool.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/serialization/db/GraphSingleton.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/serialization/db/LegacyDBSerializer.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/serialization/db/MultiplicityRule.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/serialization/db/TitanGraphSingleton.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/serialization/db/exceptions/EdgeMultiplicityException.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/serialization/db/exceptions/NoEdgeRuleFoundException.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/serialization/engines/QueryStyle.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/serialization/engines/TitanDBEngine.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/serialization/engines/TransactionalGraphEngine.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/serialization/engines/query/GraphTraversalQueryEngine.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/serialization/engines/query/GremlinPipelineQueryEngine.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/serialization/engines/query/GremlinQueryEngine.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/serialization/engines/query/QueryEngine.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/Console.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/Format.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/FormatFactory.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/FormatMapper.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/Formatter.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/GraphSON.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/IdURL.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/PathedURL.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/RawFormat.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/Resource.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/SimpleFormat.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/SubGraphStyle.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/exceptions/AAIFormatVertexException.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/exceptions/QueryParamInjectionException.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/params/Depth.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/params/Inject.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/params/NodesOnly.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/params/Setter.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/utils/QueryParamInjector.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/utils/UrlBuilder.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/serialization/tinkerpop/TreeBackedEdge.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/serialization/tinkerpop/TreeBackedVertex.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/tasks/ScheduledTasks.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/util/AAIApiServerURLBase.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/util/AAIApiVersion.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/util/AAICSVWriter.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/util/AAIConfig.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/util/AAIConfigCommandLinePropGetter.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/util/AAIConstants.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/util/AAIMechIdConfig.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/util/AAIRSyncUtility.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/util/Entity.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/util/EntityList.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/util/FileWatcher.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/util/FormatDate.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/util/GenerateXsd.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/util/HbaseSaltPrefixer.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/util/HttpsAuthClient.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/util/KeyValueList.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/util/MapperUtil.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/util/PojoUtils.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/util/Request.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/util/RestObject.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/util/RestURLEncoder.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/util/StoreNotificationEvent.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/util/UniquePropertyCheck.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/util/swagger/Api.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/util/swagger/Definition.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/util/swagger/GenerateSwagger.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/workarounds/LegacyURITransformer.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/workarounds/NamingExceptions.java delete mode 100644 aai-core/src/main/java/org/openecomp/aai/workarounds/RemoveDME2QueryParams.java create mode 100644 aai-core/src/test/java/org/onap/aai/AAISetup.java create mode 100644 aai-core/src/test/java/org/onap/aai/exceptions/AAIExceptionTest.java create mode 100644 aai-core/src/test/java/org/onap/aai/exceptions/AAIExceptionWithInfoTest.java create mode 100644 aai-core/src/test/java/org/onap/aai/introspection/IntrospectorTestSpec.java create mode 100644 aai-core/src/test/java/org/onap/aai/introspection/MoxyEngineTest.java create mode 100644 aai-core/src/test/java/org/onap/aai/introspection/PojoInjestorTest.java create mode 100644 aai-core/src/test/java/org/onap/aai/introspection/PojoLoaderTest.java create mode 100644 aai-core/src/test/java/org/onap/aai/introspection/PojoStrategyTest.java create mode 100644 aai-core/src/test/java/org/onap/aai/introspection/PropertyPredicatesTest.java create mode 100644 aai-core/src/test/java/org/onap/aai/introspection/ReflectionEngineTest.java create mode 100644 aai-core/src/test/java/org/onap/aai/introspection/sideeffect/DataCopyTest.java create mode 100644 aai-core/src/test/java/org/onap/aai/introspection/sideeffect/DataLinkTest.java create mode 100644 aai-core/src/test/java/org/onap/aai/introspection/validation/IntrospectorValidationTest.java create mode 100644 aai-core/src/test/java/org/onap/aai/logging/CNNameTest.java create mode 100644 aai-core/src/test/java/org/onap/aai/logging/CustomLogPatternLayoutTest.java create mode 100644 aai-core/src/test/java/org/onap/aai/logging/DME2RestFlagTest.java create mode 100644 aai-core/src/test/java/org/onap/aai/logging/EelfClassOfCallerTest.java create mode 100644 aai-core/src/test/java/org/onap/aai/logging/ErrorObjectTest.java create mode 100644 aai-core/src/test/java/org/onap/aai/logging/LoggingContextTest.java create mode 100644 aai-core/src/test/java/org/onap/aai/parsers/query/GraphTraversalTest.java create mode 100644 aai-core/src/test/java/org/onap/aai/parsers/query/LegacyQueryTest.java create mode 100644 aai-core/src/test/java/org/onap/aai/parsers/query/RelationshipGremlinQueryTest.java create mode 100644 aai-core/src/test/java/org/onap/aai/parsers/query/RelationshipQueryTest.java create mode 100644 aai-core/src/test/java/org/onap/aai/parsers/query/UniqueRelationshipQueryTest.java create mode 100644 aai-core/src/test/java/org/onap/aai/parsers/query/UniqueURIQueryTest.java create mode 100644 aai-core/src/test/java/org/onap/aai/parsers/relationship/RelationshipToURITest.java create mode 100644 aai-core/src/test/java/org/onap/aai/parsers/uri/URIParserTest.java create mode 100644 aai-core/src/test/java/org/onap/aai/parsers/uri/URIToDBKeyTest.java create mode 100644 aai-core/src/test/java/org/onap/aai/parsers/uri/URIToExtensionInformationTest.java create mode 100644 aai-core/src/test/java/org/onap/aai/parsers/uri/URIToObjectTest.java create mode 100644 aai-core/src/test/java/org/onap/aai/parsers/uri/URIToRelationshipObjectTest.java create mode 100644 aai-core/src/test/java/org/onap/aai/query/builder/SimplePathTest.java create mode 100644 aai-core/src/test/java/org/onap/aai/query/builder/TraversalQueryTest.java create mode 100644 aai-core/src/test/java/org/onap/aai/query/builder/UntilTest.java create mode 100644 aai-core/src/test/java/org/onap/aai/serialization/db/DbAliasTest.java create mode 100644 aai-core/src/test/java/org/onap/aai/serialization/db/DbSerializerTest.java create mode 100644 aai-core/src/test/java/org/onap/aai/serialization/db/EdgePropertyMapTest.java create mode 100644 aai-core/src/test/java/org/onap/aai/serialization/db/EdgeRulesTest.java create mode 100644 aai-core/src/test/java/org/onap/aai/serialization/queryformats/QueryFormatTestHelper.java create mode 100644 aai-core/src/test/java/org/onap/aai/serialization/queryformats/SimpleFormatTest.java create mode 100644 aai-core/src/test/java/org/onap/aai/serialization/queryformats/utils/QueryParamInjectorTest.java create mode 100644 aai-core/src/test/java/org/onap/aai/serialization/queryformats/utils/UrlBuilderTest.java create mode 100644 aai-core/src/test/java/org/onap/aai/serialization/tinkerpop/TreeBackedVertexTest.java create mode 100644 aai-core/src/test/java/org/onap/aai/util/GenerateXsdTest.java create mode 100644 aai-core/src/test/java/org/onap/aai/workarounds/RemoveDME2QueryParamsTest.java delete mode 100644 aai-core/src/test/java/org/openecomp/aai/AAISetup.java delete mode 100644 aai-core/src/test/java/org/openecomp/aai/exceptions/AAIExceptionTest.java delete mode 100644 aai-core/src/test/java/org/openecomp/aai/exceptions/AAIExceptionWithInfoTest.java delete mode 100644 aai-core/src/test/java/org/openecomp/aai/introspection/IntrospectorTestSpec.java delete mode 100644 aai-core/src/test/java/org/openecomp/aai/introspection/MoxyEngineTest.java delete mode 100644 aai-core/src/test/java/org/openecomp/aai/introspection/PojoInjestorTest.java delete mode 100644 aai-core/src/test/java/org/openecomp/aai/introspection/PojoLoaderTest.java delete mode 100644 aai-core/src/test/java/org/openecomp/aai/introspection/PojoStrategyTest.java delete mode 100644 aai-core/src/test/java/org/openecomp/aai/introspection/PropertyPredicatesTest.java delete mode 100644 aai-core/src/test/java/org/openecomp/aai/introspection/ReflectionEngineTest.java delete mode 100644 aai-core/src/test/java/org/openecomp/aai/introspection/sideeffect/DataCopyTest.java delete mode 100644 aai-core/src/test/java/org/openecomp/aai/introspection/sideeffect/DataLinkTest.java delete mode 100644 aai-core/src/test/java/org/openecomp/aai/introspection/validation/IntrospectorValidationTest.java delete mode 100644 aai-core/src/test/java/org/openecomp/aai/logging/CNNameTest.java delete mode 100644 aai-core/src/test/java/org/openecomp/aai/logging/CustomLogPatternLayoutTest.java delete mode 100644 aai-core/src/test/java/org/openecomp/aai/logging/DME2RestFlagTest.java delete mode 100644 aai-core/src/test/java/org/openecomp/aai/logging/EelfClassOfCallerTest.java delete mode 100644 aai-core/src/test/java/org/openecomp/aai/logging/ErrorObjectTest.java delete mode 100644 aai-core/src/test/java/org/openecomp/aai/logging/LoggingContextTest.java delete mode 100644 aai-core/src/test/java/org/openecomp/aai/parsers/query/GraphTraversalTest.java delete mode 100644 aai-core/src/test/java/org/openecomp/aai/parsers/query/LegacyQueryTest.java delete mode 100644 aai-core/src/test/java/org/openecomp/aai/parsers/query/RelationshipGremlinQueryTest.java delete mode 100644 aai-core/src/test/java/org/openecomp/aai/parsers/query/RelationshipQueryTest.java delete mode 100644 aai-core/src/test/java/org/openecomp/aai/parsers/query/UniqueRelationshipQueryTest.java delete mode 100644 aai-core/src/test/java/org/openecomp/aai/parsers/query/UniqueURIQueryTest.java delete mode 100644 aai-core/src/test/java/org/openecomp/aai/parsers/relationship/RelationshipToURITest.java delete mode 100644 aai-core/src/test/java/org/openecomp/aai/parsers/uri/URIParserTest.java delete mode 100644 aai-core/src/test/java/org/openecomp/aai/parsers/uri/URIToDBKeyTest.java delete mode 100644 aai-core/src/test/java/org/openecomp/aai/parsers/uri/URIToExtensionInformationTest.java delete mode 100644 aai-core/src/test/java/org/openecomp/aai/parsers/uri/URIToObjectTest.java delete mode 100644 aai-core/src/test/java/org/openecomp/aai/parsers/uri/URIToRelationshipObjectTest.java delete mode 100644 aai-core/src/test/java/org/openecomp/aai/query/builder/SimplePathTest.java delete mode 100644 aai-core/src/test/java/org/openecomp/aai/query/builder/TraversalQueryTest.java delete mode 100644 aai-core/src/test/java/org/openecomp/aai/query/builder/UntilTest.java delete mode 100644 aai-core/src/test/java/org/openecomp/aai/serialization/db/DbAliasTest.java delete mode 100644 aai-core/src/test/java/org/openecomp/aai/serialization/db/DbSerializerTest.java delete mode 100644 aai-core/src/test/java/org/openecomp/aai/serialization/db/EdgePropertyMapTest.java delete mode 100644 aai-core/src/test/java/org/openecomp/aai/serialization/db/EdgeRulesTest.java delete mode 100644 aai-core/src/test/java/org/openecomp/aai/serialization/queryformats/QueryFormatTestHelper.java delete mode 100644 aai-core/src/test/java/org/openecomp/aai/serialization/queryformats/SimpleFormatTest.java delete mode 100644 aai-core/src/test/java/org/openecomp/aai/serialization/queryformats/utils/QueryParamInjectorTest.java delete mode 100644 aai-core/src/test/java/org/openecomp/aai/serialization/queryformats/utils/UrlBuilderTest.java delete mode 100644 aai-core/src/test/java/org/openecomp/aai/serialization/tinkerpop/TreeBackedVertexTest.java delete mode 100644 aai-core/src/test/java/org/openecomp/aai/util/GenerateXsdTest.java delete mode 100644 aai-core/src/test/java/org/openecomp/aai/workarounds/RemoveDME2QueryParamsTest.java (limited to 'aai-core') diff --git a/aai-core/LICENSE.TXT b/aai-core/LICENSE.TXT index 32bbcba4..72b8cfb7 100644 --- a/aai-core/LICENSE.TXT +++ b/aai-core/LICENSE.TXT @@ -1,23 +1,19 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP and OpenECOMP are trademarks - * and service marks of AT&T Intellectual Property. - * - */ +============LICENSE_START======================================================= +org.onap.aai +================================================================================ +Copyright © 2017 AT&T Intellectual Property. All rights reserved. +================================================================================ +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +============LICENSE_END========================================================= + +ECOMP is a trademark and service mark of AT&T Intellectual Property. diff --git a/aai-core/pom.xml b/aai-core/pom.xml index 675a0ca4..20575cb7 100644 --- a/aai-core/pom.xml +++ b/aai-core/pom.xml @@ -20,7 +20,7 @@ ${project.build.directory}/coverage-reports/jacoco.exec false ${project.version} - org/openecomp/aai/domain/** + org/onap/aai/domain/** v11 https://wiki.onap.org/ 1.0.2 @@ -41,7 +41,7 @@ java - org.openecomp.aai.util.GenerateXsd + org.onap.aai.util.GenerateXsd gen_version @@ -82,7 +82,7 @@ java - org.openecomp.aai.util.GenerateXsd + org.onap.aai.util.GenerateXsd gen_version @@ -123,7 +123,7 @@ java - org.openecomp.aai.util.swagger.GenerateSwagger + org.onap.aai.util.swagger.GenerateSwagger aai.generate.version 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 new file mode 100644 index 00000000..5ee973a3 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/audit/ListEndpoints.java @@ -0,0 +1,303 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.audit; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.commons.lang.StringUtils; + +import org.onap.aai.db.props.AAIProperties; +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.introspection.Version; +import org.onap.aai.introspection.exceptions.AAIUnknownObjectException; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.google.common.base.CaseFormat; + +/** + * The Class ListEndpoints. + */ +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 endpoints = new ArrayList<>(); + private Map endpointToLogicalName = new HashMap(); + + /** + * The main method. + * + * @param args the arguments + */ + public static void main(String[] args) { + ListEndpoints endPoints = new ListEndpoints(AAIProperties.LATEST); + + System.out.println(endPoints.toString("relationship-list")); + + } + + /** + * Instantiates a new list endpoints. + * + * @param version the version + */ + public ListEndpoints(Version version) { + + Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, version); + + try { + final Introspector start = loader.introspectorFromName(this.start); + Set startMap = new HashSet<>(); + beginAudit(start, "/aai/" + 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 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 properties = obj.getProperties(); + Set 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)", 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 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)", e); + } + } + } else if (obj.isComplexType(propName)) { + try { + final Introspector nestedObj = obj.newIntrospectorInstanceOfProperty(propName); + Set 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)", 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 getLogicalNames() { + + return endpointToLogicalName; + + } + + /** + * Gets the endpoints. + * + * @return the endpoints + */ + public List getEndpoints() { + + return this.getEndpoints(""); + + } + + /** + * Gets the endpoints. + * + * @param filterOut the filter out + * @return the endpoints + */ + public List getEndpoints(String filterOut) { + List 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/exceptions/AAIUnrecognizedFunctionException.java b/aai-core/src/main/java/org/onap/aai/auth/exceptions/AAIUnrecognizedFunctionException.java new file mode 100644 index 00000000..9758f98f --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/auth/exceptions/AAIUnrecognizedFunctionException.java @@ -0,0 +1,43 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.auth.exceptions; + +import org.onap.aai.exceptions.AAIException; + +public class AAIUnrecognizedFunctionException extends AAIException { + + private static final long serialVersionUID = 3297064867724071290L; + + public AAIUnrecognizedFunctionException() {} + + public AAIUnrecognizedFunctionException(String message) { + super("AAI_3012", message); + } + + public AAIUnrecognizedFunctionException(Throwable cause) { + super("AAI_3012",cause); + } + + public AAIUnrecognizedFunctionException(String message, Throwable cause) { + super("AAI_3012", cause, message); + } +} 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 new file mode 100644 index 00000000..a3e4d71f --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/db/DbMethHelper.java @@ -0,0 +1,159 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.db; + +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +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; +import org.onap.aai.introspection.exceptions.AAIUnknownObjectException; +import org.onap.aai.parsers.query.QueryParser; +import org.onap.aai.parsers.relationship.RelationshipToURI; +import org.onap.aai.query.builder.QueryBuilder; +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 searchVertexByIdentityMap(String type, Map 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 results = queryParser.getQueryBuilder().toList(); + + return reduceToSingleVertex(results, map); + } + + /** + * @param type + * @param map - form [{propname}:{value}] + * @return + * @throws AAIException + */ + public Optional locateUniqueVertex(String type, Map map) throws AAIException { + + return reduceToSingleVertex(locateUniqueVertices(type, map), map); + } + + public List locateUniqueVertices(String type, Map 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 map) throws AAIUnknownObjectException { + final Introspector relationship = loader.introspectorFromName("relationship"); + relationship.setValue("related-to", type); + final List data = relationship.getValue("relationship-data"); + for (Entry 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 propHash) throws AAIUnknownObjectException { + final Introspector result = loader.introspectorFromName(targetNodeType); + for (Entry entry : propHash.entrySet()) { + result.setValue(entry.getKey(), entry.getValue()); + } + return result; + } + + private Optional reduceToSingleVertex(List vertices, Map 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 getVertexProperties(Vertex v) { + List retArr = new ArrayList<>(); + if( v == null ){ + retArr.add("null Node object passed to showPropertiesForNode()\n"); + } + else { + String nodeType; + Object ob = v.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> pI = v.properties(); + while( pI.hasNext() ){ + VertexProperty 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 new file mode 100644 index 00000000..e481f3cf --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/db/props/AAIProperties.java @@ -0,0 +1,40 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.db.props; + +import org.onap.aai.introspection.Version; + +public class AAIProperties { + public static final String NODE_TYPE = "aai-node-type"; + public static final String LAST_MOD_SOURCE_OF_TRUTH = "last-mod-source-of-truth"; + public static final String SOURCE_OF_TRUTH = "source-of-truth"; + public static final String LAST_MOD_TS = "aai-last-mod-ts"; + public static final String UNIQUE_KEY = "aai-unique-key"; + public static final String CREATED_TS = "aai-created-ts"; + public static final String RESOURCE_VERSION = "resource-version"; + public static final String AAI_URI = "aai-uri"; + public static final Version LATEST = Version.v11; + public static final Integer MAXIMUM_DEPTH = 10000; + public static final String LINKED = "linked"; + public static final String DB_ALIAS_SUFFIX = "-local"; + +} diff --git a/aai-core/src/main/java/org/onap/aai/db/schema/AuditDoc.java b/aai-core/src/main/java/org/onap/aai/db/schema/AuditDoc.java new file mode 100644 index 00000000..dc92b220 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/db/schema/AuditDoc.java @@ -0,0 +1,90 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.db.schema; + +import java.util.List; + +import org.codehaus.jackson.annotate.JsonProperty; + +public class AuditDoc { + + private List properties; + private List indexes; + private List edgeLabels; + + /** + * Gets the properties. + * + * @return the properties + */ + public List getProperties() { + return properties; + } + + /** + * Sets the properties. + * + * @param properties the new properties + */ + public void setProperties(List properties) { + this.properties = properties; + } + + /** + * Gets the indexes. + * + * @return the indexes + */ + public List getIndexes() { + return indexes; + } + + /** + * Sets the indexes. + * + * @param indexes the new indexes + */ + public void setIndexes(List indexes) { + this.indexes = indexes; + } + + /** + * Gets the edge labels. + * + * @return the edge labels + */ + @JsonProperty("edge-labels") + public List getEdgeLabels() { + return edgeLabels; + } + + /** + * Sets the edge labels. + * + * @param edgeLabels the new edge labels + */ + public void setEdgeLabels(List edgeLabels) { + this.edgeLabels = edgeLabels; + } + + +} diff --git a/aai-core/src/main/java/org/onap/aai/db/schema/AuditOXM.java b/aai-core/src/main/java/org/onap/aai/db/schema/AuditOXM.java new file mode 100644 index 00000000..e64f3ea3 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/db/schema/AuditOXM.java @@ -0,0 +1,250 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.db.schema; + +import java.io.IOException; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; + +import javax.xml.XMLConstants; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + +import org.onap.aai.serialization.db.EdgeRule; +import org.onap.aai.serialization.db.EdgeRules; +import org.w3c.dom.Document; +import org.w3c.dom.NodeList; +import org.xml.sax.SAXException; + +import org.onap.aai.db.props.AAIProperties; +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.introspection.Version; +import org.onap.aai.introspection.exceptions.AAIUnknownObjectException; +import org.onap.aai.schema.enums.ObjectMetadata; +import org.onap.aai.util.AAIConstants; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.google.common.collect.Multimap; +import com.thinkaurelius.titan.core.Cardinality; +import com.thinkaurelius.titan.core.Multiplicity; +import com.thinkaurelius.titan.core.schema.SchemaStatus; + +public class AuditOXM extends Auditor { + + private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(AuditOXM.class); + + private Set allObjects; + + /** + * Instantiates a new audit OXM. + * + * @param version the version + */ + public AuditOXM(Version version) { + Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, version); + Set objectNames = getAllObjects(version); + allObjects = new HashSet<>(); + for (String key : objectNames) { + try { + final Introspector temp = loader.introspectorFromName(key); + allObjects.add(temp); + this.createDBProperties(temp); + } catch (AAIUnknownObjectException e) { + LOGGER.warn("Skipping audit for object " + key + " (Unknown Object)", e); + } + } + for (Introspector temp : allObjects) { + this.createDBIndexes(temp); + } + createEdgeLabels(); + + } + + /** + * Gets the all objects. + * + * @param version the version + * @return the all objects + */ + private Set getAllObjects(Version version) { + String fileName = AAIConstants.AAI_HOME_ETC_OXM + "aai_oxm_" + version.toString() + ".xml"; + Set result = new HashSet<>(); + DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); + try { + docFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); + DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); + Document doc = docBuilder.parse(fileName); + NodeList list = doc.getElementsByTagName("java-type"); + for (int i = 0; i < list.getLength(); i++) { + result.add(list.item(i).getAttributes().getNamedItem("name").getNodeValue()); + } + } catch (ParserConfigurationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (SAXException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + result.remove("EdgePropNames"); + return result; + + } + + /** + * Creates the DB properties. + * + * @param temp the temp + */ + private void createDBProperties(Introspector temp) { + Set objectProperties = temp.getProperties(); + + for (String prop : objectProperties) { + if (!properties.containsKey(prop)) { + DBProperty dbProperty = new DBProperty(); + dbProperty.setName(prop); + if (temp.isListType(prop)) { + dbProperty.setCardinality(Cardinality.SET); + if (temp.isSimpleGenericType(prop)) { + Class clazz = null; + try { + clazz = Class.forName(temp.getGenericType(prop)); + } catch (ClassNotFoundException e) { + clazz = Object.class; + } + dbProperty.setTypeClass(clazz); + properties.put(prop, dbProperty); + } + } else { + dbProperty.setCardinality(Cardinality.SINGLE); + if (temp.isSimpleType(prop)) { + Class clazz = null; + try { + clazz = Class.forName(temp.getType(prop)); + } catch (ClassNotFoundException e) { + clazz = Object.class; + } + dbProperty.setTypeClass(clazz); + properties.put(prop, dbProperty); + } + } + } + } + + } + + /** + * Creates the DB indexes. + * + * @param temp the temp + */ + private void createDBIndexes(Introspector temp) { + String uniqueProps = temp.getMetadata(ObjectMetadata.UNIQUE_PROPS); + String namespace = temp.getMetadata(ObjectMetadata.NAMESPACE); + if (uniqueProps == null) { + uniqueProps = ""; + } + if (namespace == null) { + namespace = ""; + } + boolean isTopLevel = namespace != ""; + List unique = Arrays.asList(uniqueProps.split(",")); + Set indexed = temp.getIndexedProperties(); + Set keys = temp.getKeys(); + + for (String prop : indexed) { + DBIndex dbIndex = new DBIndex(); + LinkedHashSet properties = new LinkedHashSet<>(); + if (!this.indexes.containsKey(prop)) { + dbIndex.setName(prop); + dbIndex.setUnique(unique.contains(prop)); + properties.add(this.properties.get(prop)); + dbIndex.setProperties(properties); + dbIndex.setStatus(SchemaStatus.ENABLED); + this.indexes.put(prop, dbIndex); + } + } + if (keys.size() > 1 || isTopLevel) { + DBIndex dbIndex = new DBIndex(); + LinkedHashSet properties = new LinkedHashSet<>(); + dbIndex.setName("key-for-" + temp.getDbName()); + if (!this.indexes.containsKey(dbIndex.getName())) { + boolean isUnique = false; + if (isTopLevel) { + properties.add(this.properties.get(AAIProperties.NODE_TYPE)); + } + for (String key : keys) { + properties.add(this.properties.get(key)); + + if (unique.contains(key) && !isUnique) { + isUnique = true; + } + } + dbIndex.setUnique(isUnique); + dbIndex.setProperties(properties); + dbIndex.setStatus(SchemaStatus.ENABLED); + this.indexes.put(dbIndex.getName(), dbIndex); + } + } + + } + + /** + * Creates the edge labels. + */ + private void createEdgeLabels() { + Multimap edgeRules = EdgeRules.getInstance().getAllRules(); + for (String key : edgeRules.keySet()) { + Collection collection = edgeRules.get(key); + EdgeProperty prop = new EdgeProperty(); + //there is only ever one, they used the wrong type for EdgeRules + String label = ""; + for (EdgeRule item : collection) { + label = item.getLabel(); + } + prop.setName(label); + prop.setMultiplicity(Multiplicity.MULTI); + this.edgeLabels.put(label, prop); + } + } + + /** + * Gets the all introspectors. + * + * @return the all introspectors + */ + public Set getAllIntrospectors() { + return this.allObjects; + } + +} diff --git a/aai-core/src/main/java/org/onap/aai/db/schema/AuditTitan.java b/aai-core/src/main/java/org/onap/aai/db/schema/AuditTitan.java new file mode 100644 index 00000000..ec1c2394 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/db/schema/AuditTitan.java @@ -0,0 +1,124 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.db.schema; + + +import java.util.Iterator; +import java.util.LinkedHashSet; + +import org.apache.tinkerpop.gremlin.structure.Vertex; + +import com.thinkaurelius.titan.core.EdgeLabel; +import com.thinkaurelius.titan.core.PropertyKey; +import com.thinkaurelius.titan.core.TitanGraph; +import com.thinkaurelius.titan.core.schema.TitanGraphIndex; +import com.thinkaurelius.titan.core.schema.TitanManagement; + +public class AuditTitan extends Auditor { + + private final TitanGraph graph; + + /** + * Instantiates a new audit titan. + * + * @param g the g + */ + public AuditTitan (TitanGraph g) { + this.graph = g; + buildSchema(); + } + + /** + * Builds the schema. + */ + private void buildSchema() { + populateProperties(); + populateIndexes(); + populateEdgeLabels(); + } + + /** + * Populate properties. + */ + private void populateProperties() { + TitanManagement mgmt = graph.openManagement(); + Iterable iterable = mgmt.getRelationTypes(PropertyKey.class); + Iterator titanProperties = iterable.iterator(); + PropertyKey propKey; + while (titanProperties.hasNext()) { + propKey = titanProperties.next(); + DBProperty prop = new DBProperty(); + + prop.setName(propKey.name()); + prop.setCardinality(propKey.cardinality()); + prop.setTypeClass(propKey.dataType()); + + this.properties.put(prop.getName(), prop); + } + } + + /** + * Populate indexes. + */ + private void populateIndexes() { + TitanManagement mgmt = graph.openManagement(); + Iterable iterable = mgmt.getGraphIndexes(Vertex.class); + Iterator titanIndexes = iterable.iterator(); + TitanGraphIndex titanIndex; + while (titanIndexes.hasNext()) { + titanIndex = titanIndexes.next(); + if (titanIndex.isCompositeIndex()) { + DBIndex index = new DBIndex(); + LinkedHashSet dbProperties = new LinkedHashSet<>(); + index.setName(titanIndex.name()); + index.setUnique(titanIndex.isUnique()); + PropertyKey[] keys = titanIndex.getFieldKeys(); + for (PropertyKey key : keys) { + dbProperties.add(this.properties.get(key.name())); + } + index.setProperties(dbProperties); + index.setStatus(titanIndex.getIndexStatus(keys[0])); + this.indexes.put(index.getName(), index); + } + } + } + + /** + * Populate edge labels. + */ + private void populateEdgeLabels() { + TitanManagement mgmt = graph.openManagement(); + Iterable iterable = mgmt.getRelationTypes(EdgeLabel.class); + Iterator titanEdgeLabels = iterable.iterator(); + EdgeLabel edgeLabel; + while (titanEdgeLabels.hasNext()) { + edgeLabel = titanEdgeLabels.next(); + EdgeProperty edgeProperty = new EdgeProperty(); + + edgeProperty.setName(edgeLabel.name()); + edgeProperty.setMultiplicity(edgeLabel.multiplicity()); + + this.edgeLabels.put(edgeProperty.getName(), edgeProperty); + } + } + +} diff --git a/aai-core/src/main/java/org/onap/aai/db/schema/Auditor.java b/aai-core/src/main/java/org/onap/aai/db/schema/Auditor.java new file mode 100644 index 00000000..3e7a595a --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/db/schema/Auditor.java @@ -0,0 +1,55 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.db.schema; + +import java.util.*; + +public abstract class Auditor { + + protected Map properties = new HashMap<>(); + protected Map indexes = new HashMap<>(); + protected Map edgeLabels = new HashMap<>(); + + /** + * Gets the audit doc. + * + * @return the audit doc + */ + public AuditDoc getAuditDoc() { + AuditDoc doc = new AuditDoc(); + List propertyList = new ArrayList<>(); + List indexList = new ArrayList<>(); + List edgeLabelList = new ArrayList<>(); + propertyList.addAll(this.properties.values()); + indexList.addAll(this.indexes.values()); + edgeLabelList.addAll(this.edgeLabels.values()); + Collections.sort(propertyList, new CompareByName()); + Collections.sort(indexList, new CompareByName()); + Collections.sort(edgeLabelList, new CompareByName()); + + doc.setProperties(propertyList); + doc.setIndexes(indexList); + doc.setEdgeLabels(edgeLabelList); + + return doc; + } +} diff --git a/aai-core/src/main/java/org/onap/aai/db/schema/AuditorFactory.java b/aai-core/src/main/java/org/onap/aai/db/schema/AuditorFactory.java new file mode 100644 index 00000000..9af7a11a --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/db/schema/AuditorFactory.java @@ -0,0 +1,48 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.db.schema; + +import org.onap.aai.introspection.Version; +import com.thinkaurelius.titan.core.TitanGraph; + +public class AuditorFactory { + + /** + * Gets the OXM auditor. + * + * @param v the v + * @return the OXM auditor + */ + public static Auditor getOXMAuditor (Version v) { + return new AuditOXM(v); + } + + /** + * Gets the graph auditor. + * + * @param g the g + * @return the graph auditor + */ + public static Auditor getGraphAuditor (TitanGraph g) { + return new AuditTitan(g); + } +} diff --git a/aai-core/src/main/java/org/onap/aai/db/schema/CompareByName.java b/aai-core/src/main/java/org/onap/aai/db/schema/CompareByName.java new file mode 100644 index 00000000..56fe1a44 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/db/schema/CompareByName.java @@ -0,0 +1,37 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.db.schema; + +import java.util.Comparator; + +public class CompareByName implements Comparator{ + + /** + * {@inheritDoc} + */ + @Override + public int compare(Named o1, Named o2) { + return o1.getName().compareTo(o2.getName()); + } + + +} diff --git a/aai-core/src/main/java/org/onap/aai/db/schema/DBIndex.java b/aai-core/src/main/java/org/onap/aai/db/schema/DBIndex.java new file mode 100644 index 00000000..9093a202 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/db/schema/DBIndex.java @@ -0,0 +1,106 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.db.schema; + +import java.util.LinkedHashSet; +import java.util.Set; + +import com.thinkaurelius.titan.core.schema.SchemaStatus; + +public class DBIndex implements Named { + + private String name = null; + private boolean unique = false; + private LinkedHashSet properties = new LinkedHashSet<>(); + private SchemaStatus status = null; + + /** + * Gets the name + */ + public String getName() { + return name; + } + + /** + * Sets the name. + * + * @param name the new name + */ + public void setName(String name) { + this.name = name; + } + + /** + * Checks if is unique. + * + * @return true, if is unique + */ + public boolean isUnique() { + return unique; + } + + /** + * Sets the unique. + * + * @param unique the new unique + */ + public void setUnique(boolean unique) { + this.unique = unique; + } + + /** + * Gets the properties. + * + * @return the properties + */ + public Set getProperties() { + return properties; + } + + /** + * Sets the properties. + * + * @param properties the new properties + */ + public void setProperties(LinkedHashSet properties) { + this.properties = properties; + } + + /** + * Gets the status. + * + * @return the status + */ + public SchemaStatus getStatus() { + return status; + } + + /** + * Sets the status. + * + * @param status the new status + */ + public void setStatus(SchemaStatus status) { + this.status = status; + } + +} diff --git a/aai-core/src/main/java/org/onap/aai/db/schema/DBProperty.java b/aai-core/src/main/java/org/onap/aai/db/schema/DBProperty.java new file mode 100644 index 00000000..e4f98cbf --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/db/schema/DBProperty.java @@ -0,0 +1,86 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.db.schema; + +import org.onap.aai.introspection.Introspector; +import com.thinkaurelius.titan.core.Cardinality; + +public class DBProperty implements Named { + + + private String name = null; + private Cardinality cardinality = null; + private Class typeClass = null; + + /** + * Gets the name + */ + public String getName() { + return name; + } + + /** + * Sets the name. + * + * @param name the new name + */ + public void setName(String name) { + this.name = name; + } + + /** + * Gets the cardinality. + * + * @return the cardinality + */ + public Cardinality getCardinality() { + return cardinality; + } + + /** + * Sets the cardinality. + * + * @param cardinality the new cardinality + */ + public void setCardinality(Cardinality cardinality) { + this.cardinality = cardinality; + } + + /** + * Gets the type class. + * + * @return the type class + */ + public Class getTypeClass() { + return typeClass; + } + + /** + * Sets the type class. + * + * @param type the new type class + */ + public void setTypeClass(Class type) { + this.typeClass = type; + } + +} diff --git a/aai-core/src/main/java/org/onap/aai/db/schema/EdgeProperty.java b/aai-core/src/main/java/org/onap/aai/db/schema/EdgeProperty.java new file mode 100644 index 00000000..4d0cf3b8 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/db/schema/EdgeProperty.java @@ -0,0 +1,70 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.db.schema; + +import com.thinkaurelius.titan.core.Multiplicity; +import org.codehaus.jackson.annotate.JsonProperty; +import org.codehaus.jackson.annotate.JsonPropertyOrder; + +@JsonPropertyOrder({ "label", "multiplicity" }) +public class EdgeProperty implements Named { + + private String name = null; + private Multiplicity multiplicity = null; + + /** + * Gets the name + */ + @JsonProperty("label") + public String getName() { + return name; + } + + /** + * Sets the name. + * + * @param name the new name + */ + @JsonProperty("label") + public void setName(String name) { + this.name = name; + } + + /** + * Gets the multiplicity. + * + * @return the multiplicity + */ + public Multiplicity getMultiplicity() { + return multiplicity; + } + + /** + * Sets the multiplicity. + * + * @param multiplicity the new multiplicity + */ + public void setMultiplicity(Multiplicity multiplicity) { + this.multiplicity = multiplicity; + } + +} diff --git a/aai-core/src/main/java/org/onap/aai/db/schema/ManageTitanSchema.java b/aai-core/src/main/java/org/onap/aai/db/schema/ManageTitanSchema.java new file mode 100644 index 00000000..0260543f --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/db/schema/ManageTitanSchema.java @@ -0,0 +1,330 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.db.schema; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +import org.apache.tinkerpop.gremlin.structure.Vertex; + +import org.onap.aai.introspection.Version; +import com.thinkaurelius.titan.core.PropertyKey; +import com.thinkaurelius.titan.core.TitanGraph; +import com.thinkaurelius.titan.core.schema.SchemaStatus; +import com.thinkaurelius.titan.core.schema.TitanGraphIndex; +import com.thinkaurelius.titan.core.schema.TitanManagement; +import com.thinkaurelius.titan.core.schema.TitanManagement.IndexBuilder; + +public class ManageTitanSchema { + + + private TitanManagement graphMgmt; + private TitanGraph graph; + private List aaiProperties; + private List aaiIndexes; + private List aaiEdgeProperties; + private Auditor oxmInfo = null; + private Auditor graphInfo = null; + + /** + * Instantiates a new manage titan schema. + * + * @param graph the graph + */ + public ManageTitanSchema(final TitanGraph graph) { + this.graph = graph; + oxmInfo = AuditorFactory.getOXMAuditor(Version.v8); + graphInfo = AuditorFactory.getGraphAuditor(graph); + } + + + /** + * Builds the schema. + */ + public void buildSchema() { + + this.graphMgmt = graph.openManagement(); + aaiProperties = new ArrayList<>(); + aaiEdgeProperties = new ArrayList<>(); + aaiIndexes = new ArrayList<>(); + aaiProperties.addAll(oxmInfo.getAuditDoc().getProperties()); + aaiIndexes.addAll(oxmInfo.getAuditDoc().getIndexes()); + aaiEdgeProperties.addAll(oxmInfo.getAuditDoc().getEdgeLabels()); + try { + createPropertyKeys(); + createIndexes(); + createEdgeLabels(); + } catch (Exception e) { + e.printStackTrace(); + graphMgmt.rollback(); + } + graphMgmt.commit(); + } + + /** + * Creates the property keys. + */ + private void createPropertyKeys() { + + + for (DBProperty prop : aaiProperties) { + + if (graphMgmt.containsPropertyKey(prop.getName())) { + PropertyKey key = graphMgmt.getPropertyKey(prop.getName()); + boolean isChanged = false; + if (!prop.getCardinality().equals(key.cardinality())) { + isChanged = true; + } + if (!prop.getTypeClass().equals(key.dataType())) { + isChanged = true; + } + if (isChanged) { + //must modify! + this.replaceProperty(prop); + } + } else { + //create a new property key + System.out.println("Key: " + prop.getName() + " not found - adding"); + graphMgmt.makePropertyKey(prop.getName()).dataType(prop.getTypeClass()).cardinality(prop.getCardinality()).make(); + } + } + + } + + /** + * Creates the indexes. + */ + private void createIndexes() { + + for (DBIndex index : aaiIndexes) { + Set props = index.getProperties(); + boolean isChanged = false; + boolean isNew = false; + List keyList = new ArrayList<>(); + for (DBProperty prop : props) { + keyList.add(graphMgmt.getPropertyKey(prop.getName())); + } + if (graphMgmt.containsGraphIndex(index.getName())) { + TitanGraphIndex titanIndex = graphMgmt.getGraphIndex(index.getName()); + PropertyKey[] dbKeys = titanIndex.getFieldKeys(); + if (dbKeys.length != keyList.size()) { + isChanged = true; + } else { + int i = 0; + for (PropertyKey key : keyList) { + if (!dbKeys[i].equals(key)) { + isChanged = true; + break; + } + i++; + } + } + } else { + isNew = true; + } + if (keyList.size() > 0) { + this.createIndex(graphMgmt, index.getName(), keyList, index.isUnique(), isNew, isChanged); + } + } + } + + // 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. + /** + * Creates the edge labels. + */ + private void createEdgeLabels() { + + + for (EdgeProperty prop : aaiEdgeProperties) { + + if (graphMgmt.containsEdgeLabel(prop.getName())) { + // see what changed + } else { + graphMgmt.makeEdgeLabel(prop.getName()).multiplicity(prop.getMultiplicity()).make(); + } + + } + + + } + + /** + * Creates the property. + * + * @param mgmt the mgmt + * @param prop the prop + */ + private void createProperty(TitanManagement mgmt, DBProperty prop) { + if (mgmt.containsPropertyKey(prop.getName())) { + PropertyKey key = mgmt.getPropertyKey(prop.getName()); + boolean isChanged = false; + if (!prop.getCardinality().equals(key.cardinality())) { + isChanged = true; + } + if (!prop.getTypeClass().equals(key.dataType())) { + isChanged = true; + } + if (isChanged) { + //must modify! + this.replaceProperty(prop); + } + } else { + //create a new property key + System.out.println("Key: " + prop.getName() + " not found - adding"); + mgmt.makePropertyKey(prop.getName()).dataType(prop.getTypeClass()).cardinality(prop.getCardinality()).make(); + } + } + + /** + * Creates the index. + * + * @param mgmt the mgmt + * @param indexName the index name + * @param keys the keys + * @param isUnique the is unique + * @param isNew the is new + * @param isChanged the is changed + */ + private void createIndex(TitanManagement mgmt, String indexName, List keys, boolean isUnique, boolean isNew, boolean isChanged) { + + /*if (isChanged) { + System.out.println("Changing index: " + indexName); + TitanGraphIndex oldIndex = mgmt.getGraphIndex(indexName); + mgmt.updateIndex(oldIndex, SchemaAction.DISABLE_INDEX); + mgmt.commit(); + //cannot remove indexes + //graphMgmt.updateIndex(oldIndex, SchemaAction.REMOVE_INDEX); + }*/ + if (isNew || isChanged) { + + if (isNew) { + IndexBuilder builder = mgmt.buildIndex(indexName,Vertex.class); + for (PropertyKey k : keys) { + builder.addKey(k); + } + if (isUnique) { + builder.unique(); + } + builder.buildCompositeIndex(); + System.out.println("Built index for " + indexName + " with keys: " + keys); + + //mgmt.commit(); + } + + //mgmt = graph.asAdmin().getManagementSystem(); + //mgmt.updateIndex(mgmt.getGraphIndex(indexName), SchemaAction.REGISTER_INDEX); + //mgmt.commit(); + + try { + //waitForCompletion(indexName); + //TitanIndexRepair.hbaseRepair(AAIConstants.AAI_CONFIG_FILENAME, indexName, ""); + } catch (Exception e) { + // TODO Auto-generated catch block + graph.tx().rollback(); + graph.close(); + e.printStackTrace(); + } + + //mgmt = graph.asAdmin().getManagementSystem(); + //mgmt.updateIndex(mgmt.getGraphIndex(indexName), SchemaAction.REINDEX); + + //mgmt.updateIndex(mgmt.getGraphIndex(indexName), SchemaAction.ENABLE_INDEX); + + //mgmt.commit(); + + } + } + + /** + * Wait for completion. + * + * @param name the name + * @throws InterruptedException the interrupted exception + */ + private void waitForCompletion(String name) throws InterruptedException { + + boolean registered = false; + long before = System.currentTimeMillis(); + while (!registered) { + Thread.sleep(500L); + TitanManagement mgmt = graph.openManagement(); + TitanGraphIndex idx = mgmt.getGraphIndex(name); + registered = true; + for (PropertyKey k : idx.getFieldKeys()) { + SchemaStatus s = idx.getIndexStatus(k); + registered &= s.equals(SchemaStatus.REGISTERED); + } + mgmt.rollback(); + } + System.out.println("Index REGISTERED in " + (System.currentTimeMillis() - before) + " ms"); + } + + /** + * Replace property. + * + * @param key the key + */ + private void replaceProperty(DBProperty key) { + + + + + } + + /** + * Update index. + * + * @param index the index + */ + public void updateIndex(DBIndex index) { + + TitanManagement mgmt = graph.openManagement(); + List keys = new ArrayList<>(); + boolean isNew = false; + boolean isChanged = false; + for (DBProperty prop : index.getProperties()) { + createProperty(mgmt, prop); + keys.add(mgmt.getPropertyKey(prop.getName())); + } + if (mgmt.containsGraphIndex(index.getName())) { + System.out.println("index already exists"); + isNew = false; + isChanged = true; + } else { + isNew = true; + isChanged = false; + } + this.createIndex(mgmt, index.getName(), keys, index.isUnique(), isNew, isChanged); + + mgmt.commit(); + + } + + + + + +} diff --git a/aai-core/src/main/java/org/onap/aai/db/schema/Named.java b/aai-core/src/main/java/org/onap/aai/db/schema/Named.java new file mode 100644 index 00000000..4f1f9e62 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/db/schema/Named.java @@ -0,0 +1,32 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.db.schema; + +public interface Named { + + /** + * Gets the name. + * + * @return the name + */ + public String getName(); +} diff --git a/aai-core/src/main/java/org/onap/aai/db/schema/ScriptDriver.java b/aai-core/src/main/java/org/onap/aai/db/schema/ScriptDriver.java new file mode 100644 index 00000000..fc494883 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/db/schema/ScriptDriver.java @@ -0,0 +1,94 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.db.schema; + +import java.io.IOException; + +import org.codehaus.jackson.JsonGenerationException; +import org.codehaus.jackson.map.JsonMappingException; +import org.codehaus.jackson.map.ObjectMapper; + +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.Version; +import org.onap.aai.util.AAIConfig; +import com.beust.jcommander.JCommander; +import com.beust.jcommander.Parameter; +import com.thinkaurelius.titan.core.TitanFactory; +import com.thinkaurelius.titan.core.TitanGraph; + +public class ScriptDriver { + + + /** + * The main method. + * + * @param args the arguments + * @throws AAIException the AAI exception + * @throws JsonGenerationException the json generation exception + * @throws JsonMappingException the json mapping exception + * @throws IOException Signals that an I/O exception has occurred. + */ + public static void main (String[] args) throws AAIException, IOException { + CommandLineArgs cArgs = new CommandLineArgs(); + + new JCommander(cArgs, args); + + if (cArgs.help) { + System.out.println("-c [path to graph configuration] -type [what you want to audit - oxm or graph]"); + } + String config = cArgs.config; + AAIConfig.init(); + try (TitanGraph graph = TitanFactory.open(config)) { + if (!("oxm".equals(cArgs.type) || "graph".equals(cArgs.type))) { + System.out.println("type: " + cArgs.type + " not recognized."); + System.exit(1); + } + + AuditDoc doc = null; + if ("oxm".equals(cArgs.type)) { + doc = AuditorFactory.getOXMAuditor(Version.v8).getAuditDoc(); + } else if ("graph".equals(cArgs.type)) { + doc = AuditorFactory.getGraphAuditor(graph).getAuditDoc(); + } + + ObjectMapper mapper = new ObjectMapper(); + + String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(doc); + System.out.println(json); + } + } + +} + +class CommandLineArgs { + + @Parameter(names = "--help", description = "Help") + public boolean help = false; + + @Parameter(names = "-c", description = "Configuration", required=true) + public String config; + + @Parameter(names = "-type", description = "Type", required=true) + public String type = "graph"; + + +} diff --git a/aai-core/src/main/java/org/onap/aai/dbgen/DataGrooming.java b/aai-core/src/main/java/org/onap/aai/dbgen/DataGrooming.java new file mode 100644 index 00000000..afc7807b --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/dbgen/DataGrooming.java @@ -0,0 +1,2320 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.dbgen; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Properties; +import java.util.Set; +import java.util.UUID; + +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__; +import org.apache.tinkerpop.gremlin.structure.Direction; +import org.apache.tinkerpop.gremlin.structure.Edge; +import org.apache.tinkerpop.gremlin.structure.Graph; +import org.apache.tinkerpop.gremlin.structure.Property; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.apache.tinkerpop.gremlin.structure.VertexProperty; +import org.onap.aai.db.props.AAIProperties; +import org.onap.aai.dbmap.AAIGraph; +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.introspection.ModelType; +import org.onap.aai.introspection.exceptions.AAIUnknownObjectException; +import org.onap.aai.logging.ErrorLogHelper; +import org.onap.aai.serialization.db.AAIDirection; +import org.onap.aai.serialization.db.EdgeProperty; +import org.onap.aai.util.AAIConfig; +import org.onap.aai.util.AAIConstants; +import org.onap.aai.util.FormatDate; + +import com.att.eelf.configuration.Configuration; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.thinkaurelius.titan.core.TitanFactory; +import com.thinkaurelius.titan.core.TitanGraph; + + +public class DataGrooming { + + private static EELFLogger LOGGER; + private static final String FROMAPPID = "AAI-DB"; + private static final String TRANSID = UUID.randomUUID().toString(); + private static int dupeGrpsDeleted = 0; + + /** + * The main method. + * + * @param args the arguments + */ + public static void main(String[] args) { + + // Set the logging file properties to be used by EELFManager + Properties props = System.getProperties(); + props.setProperty(Configuration.PROPERTY_LOGGING_FILE_NAME, AAIConstants.AAI_DATA_GROOMING_LOGBACK_PROPS); + props.setProperty(Configuration.PROPERTY_LOGGING_FILE_PATH, AAIConstants.AAI_HOME_ETC_APP_PROPERTIES); + LOGGER = EELFManager.getInstance().getLogger(DataGrooming.class); + String ver = "version"; // Placeholder + Boolean doAutoFix = false; + Boolean edgesOnlyFlag = false; + Boolean dontFixOrphansFlag = false; + Boolean skipHostCheck = false; + Boolean singleCommits = false; + Boolean dupeCheckOff = false; + Boolean dupeFixOn = false; + Boolean ghost2CheckOff = false; + Boolean ghost2FixOn = false; + Boolean neverUseCache = false; + Boolean skipEdgeCheckFlag = false; + + int timeWindowMinutes = 0; // A value of 0 means that we will not have a time-window -- we will look + // at all nodes of the passed-in nodeType. + long windowStartTime = 0; // Translation of the window into a starting timestamp + + int maxRecordsToFix = AAIConstants.AAI_GROOMING_DEFAULT_MAX_FIX; + int sleepMinutes = AAIConstants.AAI_GROOMING_DEFAULT_SLEEP_MINUTES; + try { + String maxFixStr = AAIConfig.get("aai.grooming.default.max.fix"); + if( maxFixStr != null && !maxFixStr.equals("") ){ + maxRecordsToFix = Integer.parseInt(maxFixStr); + } + String sleepStr = AAIConfig.get("aai.grooming.default.sleep.minutes"); + if( sleepStr != null && !sleepStr.equals("") ){ + sleepMinutes = Integer.parseInt(sleepStr); + } + } + catch ( Exception e ){ + // Don't worry, we'll just use the defaults that we got from AAIConstants + LOGGER.warn("WARNING - could not pick up aai.grooming values from aaiconfig.properties file. "); + } + + String prevFileName = ""; + dupeGrpsDeleted = 0; + FormatDate fd = new FormatDate("yyyyMMddHHmm", "GMT"); + String dteStr = fd.getDateTime(); + String groomOutFileName = "dataGrooming." + dteStr + ".out"; + + String argString = ""; + for( int x = 0; x < args.length; x++ ) { + argString = argString + " " + args[x]; + } + LOGGER.info(" DataGrooming called with these options: [" + argString + "]"); + + if (args.length > 0) { + // They passed some arguments in that will affect processing + + for (int i = 0; i < args.length; i++) { + String thisArg = args[i]; + if (thisArg.equals("-edgesOnly")) { + edgesOnlyFlag = true; + } else if (thisArg.equals("-autoFix")) { + doAutoFix = true; + } else if (thisArg.equals("-skipHostCheck")) { + skipHostCheck = true; + } else if (thisArg.equals("-dontFixOrphans")) { + dontFixOrphansFlag = true; + } else if (thisArg.equals("-singleCommits")) { + singleCommits = true; + } else if (thisArg.equals("-dupeCheckOff")) { + dupeCheckOff = true; + } else if (thisArg.equals("-dupeFixOn")) { + dupeFixOn = true; + } else if (thisArg.equals("-ghost2CheckOff")) { + ghost2CheckOff = true; + } else if (thisArg.equals("-neverUseCache")) { + neverUseCache = true; + } else if (thisArg.equals("-ghost2FixOn")) { + ghost2FixOn = true; + } else if (thisArg.equals("-skipEdgeChecks")) { + skipEdgeCheckFlag = true; + } else if (thisArg.equals("-maxFix")) { + i++; + if (i >= args.length) { + LOGGER.error(" No value passed with -maxFix option. "); + System.exit(0); + } + String nextArg = args[i]; + try { + maxRecordsToFix = Integer.parseInt(nextArg); + } catch (Exception e) { + LOGGER.error("Bad value passed with -maxFix option: [" + + nextArg + "]"); + System.exit(0); + } + } else if (thisArg.equals("-sleepMinutes")) { + i++; + if (i >= args.length) { + LOGGER.error("No value passed with -sleepMinutes option."); + System.exit(0); + } + String nextArg = args[i]; + try { + sleepMinutes = Integer.parseInt(nextArg); + } catch (Exception e) { + LOGGER.error("Bad value passed with -sleepMinutes option: [" + + nextArg + "]"); + System.exit(0); + } + } else if (thisArg.equals("-timeWindowMinutes")) { + i++; + if (i >= args.length) { + LOGGER.error("No value passed with -timeWindowMinutes option."); + System.exit(0); + } + String nextArg = args[i]; + try { + timeWindowMinutes = Integer.parseInt(nextArg); + } catch (Exception e) { + LOGGER.error("Bad value passed with -timeWindowMinutes option: [" + + nextArg + "]"); + System.exit(0); + } + if( timeWindowMinutes > 0 ){ + // Translate the window value (ie. 30 minutes) into a unix timestamp like + // we use in the db - so we can select data created after that time. + windowStartTime = figureWindowStartTime( timeWindowMinutes ); + } + } else if (thisArg.equals("-f")) { + i++; + if (i >= args.length) { + LOGGER.error(" No value passed with -f option. "); + System.exit(0); + } + prevFileName = args[i]; + } else { + LOGGER.error(" Unrecognized argument passed to DataGrooming: [" + + thisArg + "]. "); + LOGGER.error(" Valid values are: -f -autoFix -maxFix -edgesOnly -dupeFixOn -donFixOrphans -sleepMinutes -neverUseCache"); + System.exit(0); + } + } + } + + + try { + LoaderFactory.createLoaderForVersion(ModelType.MOXY, AAIProperties.LATEST); + + } + catch (Exception ex){ + LOGGER.error("ERROR - Could not create loader", ex); + System.exit(1); + } + + + try { + if (!prevFileName.equals("")) { + // They are trying to fix some data based on a data in a + // previous file. + LOGGER.info(" Call doTheGrooming() with a previous fileName [" + + prevFileName + "] for cleanup. "); + Boolean finalShutdownFlag = true; + Boolean cacheDbOkFlag = false; + doTheGrooming(prevFileName, edgesOnlyFlag, dontFixOrphansFlag, + maxRecordsToFix, groomOutFileName, ver, singleCommits, + dupeCheckOff, dupeFixOn, ghost2CheckOff, ghost2FixOn, + finalShutdownFlag, cacheDbOkFlag, + skipEdgeCheckFlag, windowStartTime); + } else if (doAutoFix) { + // They want us to run the processing twice -- first to look for + // delete candidates, then after + // napping for a while, run it again and delete any candidates + // that were found by the first run. + // Note: we will produce a separate output file for each of the + // two runs. + LOGGER.info(" Doing an auto-fix call to Grooming. "); + LOGGER.info(" First, Call doTheGrooming() to look at what's out there. "); + Boolean finalShutdownFlag = false; + Boolean cacheDbOkFlag = true; + int fixCandCount = doTheGrooming("", edgesOnlyFlag, + dontFixOrphansFlag, maxRecordsToFix, groomOutFileName, + ver, singleCommits, dupeCheckOff, dupeFixOn, ghost2CheckOff, ghost2FixOn, + finalShutdownFlag, cacheDbOkFlag, + skipEdgeCheckFlag, windowStartTime); + if (fixCandCount == 0) { + LOGGER.info(" No fix-Candidates were found by the first pass, so no second/fix-pass is needed. "); + } else { + // We'll sleep a little and then run a fix-pass based on the + // first-run's output file. + try { + LOGGER.info("About to sleep for " + sleepMinutes + + " minutes."); + int sleepMsec = sleepMinutes * 60 * 1000; + Thread.sleep(sleepMsec); + } catch (InterruptedException ie) { + LOGGER.info("\n >>> Sleep Thread has been Interrupted <<< "); + System.exit(0); + } + + dteStr = fd.getDateTime(); + String secondGroomOutFileName = "dataGrooming." + dteStr + + ".out"; + LOGGER.info(" Now, call doTheGrooming() a second time and pass in the name of the file " + + "generated by the first pass for fixing: [" + + groomOutFileName + "]"); + finalShutdownFlag = true; + cacheDbOkFlag = false; + doTheGrooming(groomOutFileName, edgesOnlyFlag, + dontFixOrphansFlag, maxRecordsToFix, + secondGroomOutFileName, ver, singleCommits, + dupeCheckOff, dupeFixOn, ghost2CheckOff, ghost2FixOn, + finalShutdownFlag, cacheDbOkFlag, + skipEdgeCheckFlag, windowStartTime); + } + } else { + // Do the grooming - plain vanilla (no fix-it-file, no + // auto-fixing) + Boolean finalShutdownFlag = true; + LOGGER.info(" Call doTheGrooming() "); + Boolean cacheDbOkFlag = true; + if( neverUseCache ){ + // They have forbidden us from using a cached db connection. + cacheDbOkFlag = false; + } + doTheGrooming("", edgesOnlyFlag, dontFixOrphansFlag, + maxRecordsToFix, groomOutFileName, ver, singleCommits, + dupeCheckOff, dupeFixOn, ghost2CheckOff, ghost2FixOn, + finalShutdownFlag, cacheDbOkFlag, + skipEdgeCheckFlag, windowStartTime); + } + } catch (Exception ex) { + LOGGER.error("Exception while grooming data", ex); + } + + LOGGER.info(" Done! "); + System.exit(0); + + }// End of main() + + /** + * Do the grooming. + * + * @param fileNameForFixing the file name for fixing + * @param edgesOnlyFlag the edges only flag + * @param dontFixOrphansFlag the dont fix orphans flag + * @param maxRecordsToFix the max records to fix + * @param groomOutFileName the groom out file name + * @param version the version + * @param singleCommits the single commits + * @param dupeCheckOff the dupe check off + * @param dupeFixOn the dupe fix on + * @param ghost2CheckOff the ghost 2 check off + * @param ghost2FixOn the ghost 2 fix on + * @param finalShutdownFlag the final shutdown flag + * @param cacheDbOkFlag the cacheDbOk flag + * @return the int + */ + private static int doTheGrooming(String fileNameForFixing, + Boolean edgesOnlyFlag, Boolean dontFixOrphansFlag, + int maxRecordsToFix, String groomOutFileName, String version, + Boolean singleCommits, + Boolean dupeCheckOff, Boolean dupeFixOn, + Boolean ghost2CheckOff, Boolean ghost2FixOn, + Boolean finalShutdownFlag, Boolean cacheDbOkFlag, + Boolean skipEdgeCheckFlag, long windowStartTime) { + + LOGGER.debug(" Entering doTheGrooming \n"); + + int cleanupCandidateCount = 0; + BufferedWriter bw = null; + TitanGraph graph = null; + TitanGraph graph2 = null; + int deleteCount = 0; + boolean executeFinalCommit = false; + Set deleteCandidateList = new LinkedHashSet<>(); + Set processedVertices = new LinkedHashSet<>(); + Graph g = null; + Graph g2 = null; + try { + AAIConfig.init(); + String targetDir = AAIConstants.AAI_HOME + AAIConstants.AAI_FILESEP + + "logs" + AAIConstants.AAI_FILESEP + "data" + + AAIConstants.AAI_FILESEP + "dataGrooming"; + + // Make sure the target directory exists + new File(targetDir).mkdirs(); + + if (!fileNameForFixing.equals("")) { + deleteCandidateList = getDeleteList(targetDir, + fileNameForFixing, edgesOnlyFlag, dontFixOrphansFlag, + dupeFixOn); + } + + if (deleteCandidateList.size() > maxRecordsToFix) { + LOGGER.warn(" >> WARNING >> Delete candidate list size (" + + deleteCandidateList.size() + + ") is too big. The maxFix we are using is: " + + maxRecordsToFix + + ". No candidates will be deleted. "); + // Clear out the list so it won't be processed below. + deleteCandidateList = new LinkedHashSet<>(); + } + + String fullOutputFileName = targetDir + AAIConstants.AAI_FILESEP + + groomOutFileName; + File groomOutFile = new File(fullOutputFileName); + try { + groomOutFile.createNewFile(); + } catch (IOException e) { + String emsg = " Problem creating output file [" + + fullOutputFileName + "], exception=" + e.getMessage(); + throw new AAIException("AAI_6124", emsg); + } + + LOGGER.info(" Will write to " + fullOutputFileName ); + bw = new BufferedWriter(new FileWriter(groomOutFile.getAbsoluteFile())); + ErrorLogHelper.loadProperties(); + + LOGGER.info(" ---- NOTE --- about to open graph (takes a little while)--------\n"); + + if( cacheDbOkFlag ){ + // Since we're just reading (not deleting/fixing anything), we can use + // a cached connection to the DB + graph = TitanFactory.open(AAIConstants.CACHED_DB_CONFIG); + } + else { + graph = TitanFactory.open(AAIConstants.REALTIME_DB_CONFIG); + } + if (graph == null) { + String emsg = "null graph object in DataGrooming\n"; + throw new AAIException("AAI_6101", emsg); + } + + LOGGER.debug(" Got the graph object. "); + + g = graph.newTransaction(); + if (g == null) { + String emsg = "null graphTransaction object in DataGrooming\n"; + throw new AAIException("AAI_6101", emsg); + } + GraphTraversalSource source1 = g.traversal(); + + ArrayList errArr = new ArrayList<>(); + int totalNodeCount = 0; + HashMap misMatchedHash = new HashMap(); + HashMap orphanNodeHash = new HashMap(); + HashMap missingDepNodeHash = new HashMap(); + HashMap oneArmedEdgeHash = new HashMap(); + HashMap emptyVertexHash = new HashMap(); + HashMap ghostNodeHash = new HashMap(); + ArrayList dupeGroups = new ArrayList<>(); + + Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, AAIProperties.LATEST); + + Set> entrySet = loader.getAllObjects().entrySet(); + String ntList = ""; + + LOGGER.info(" Starting DataGrooming Processing "); + + if (edgesOnlyFlag) { + LOGGER.info(" NOTE >> Skipping Node processing as requested. Will only process Edges. << "); + } + else { + for (Entry entry : entrySet) { + String nType = entry.getKey(); + int thisNtCount = 0; + int thisNtDeleteCount = 0; + LOGGER.debug(" > Look at : [" + nType + "] ..."); + ntList = ntList + "," + nType; + + // Get a collection of the names of the key properties for this nodeType to use later + // Determine what the key fields are for this nodeType + Collection keyProps = entry.getValue().getKeys(); + + // Get the types of nodes that this nodetype depends on for uniqueness (if any) + Collection depNodeTypes = loader.introspectorFromName(nType).getDependentOn(); + + // Loop through all the nodes of this Node type + int lastShownForNt = 0; + ArrayList tmpList = new ArrayList <> (); + Iterator iterv = source1.V().has("aai-node-type",nType); + while (iterv.hasNext()) { + // We put the nodes into an ArrayList because the graph.query iterator can time out + tmpList.add(iterv.next()); + } + + Iterator iter = tmpList.iterator(); + while (iter.hasNext()) { + try { + thisNtCount++; + if( thisNtCount == lastShownForNt + 250 ){ + lastShownForNt = thisNtCount; + LOGGER.debug("count for " + nType + " so far = " + thisNtCount ); + } + Vertex thisVtx = iter.next(); + if( windowStartTime > 0 ){ + // We only want nodes that are created after a passed-in timestamp + Object objTimeStamp = thisVtx.property("aai-created-ts").orElse(null); + if( objTimeStamp != null ){ + long thisNodeCreateTime = (long)objTimeStamp; + if( thisNodeCreateTime < windowStartTime ){ + // It is NOT in our window, so we can pass over it + continue; + } + } + } + + String thisVid = thisVtx.id().toString(); + if (processedVertices.contains(thisVid)) { + LOGGER.debug("skipping already processed vertex: " + thisVid); + continue; + } + totalNodeCount++; + List secondGetList = new ArrayList <> (); + // ----------------------------------------------------------------------- + // For each vertex of this nodeType, we want to: + // a) make sure that it can be retrieved using it's AAI defined key + // b) make sure that it is not a duplicate + // ----------------------------------------------------------------------- + + // For this instance of this nodeType, get the key properties + HashMap propHashWithKeys = new HashMap<>(); + Iterator keyPropI = keyProps.iterator(); + while (keyPropI.hasNext()) { + String propName = keyPropI.next(); + String propVal = ""; + //delete an already deleted vertex + Object obj = thisVtx.property(propName).orElse(null); + if (obj != null) { + propVal = obj.toString(); + } + propHashWithKeys.put(propName, propVal); + } + try { + // If this node is dependent on another for uniqueness, then do the query from that parent node + // Note - all of our nodes that are dependent on others for uniqueness are + // "children" of that node. + boolean depNodeOk = true; + if( depNodeTypes.isEmpty() ){ + // This kind of node is not dependent on any other. + // Make sure we can get it back using it's key properties and that we only get one. + secondGetList = getNodeJustUsingKeyParams( TRANSID, FROMAPPID, source1, nType, + propHashWithKeys, version ); + } + else { + // This kind of node is dependent on another for uniqueness. + // Start at it's parent (the dependent vertex) and make sure we can get it + // back using it's key properties and that we only get one. + Iterator vertI2 = source1.V(thisVtx).union(__.inE().has(EdgeProperty.CONTAINS.toString(), AAIDirection.OUT.toString()).outV(), __.outE().has(EdgeProperty.CONTAINS.toString(), AAIDirection.IN.toString()).inV()); + Vertex parentVtx = null; + int pCount = 0; + while( vertI2 != null && vertI2.hasNext() ){ + parentVtx = vertI2.next(); + pCount++; + } + if( pCount <= 0 ){ + + + //List vertI2 = g.traversal().V(thisVtx).union(__.outE().has("isParent-REV",true).outV(),__.inE().has("isParent",true).inV()).toList(); + //if( vertI2.isEmpty()){ + + // It's Missing it's dependent/parent node + depNodeOk = false; + boolean zeroEdges = false; + try { + Iterator tmpEdgeIter = thisVtx.edges(Direction.BOTH); + int edgeCount = 0; + while( tmpEdgeIter.hasNext() ){ + edgeCount++; + tmpEdgeIter.next(); + } + if( edgeCount == 0 ){ + zeroEdges = true; + } + } catch (Exception ex) { + LOGGER.warn("WARNING from inside the for-each-vid-loop orphan-edges-check ", ex); + } + + if (deleteCandidateList.contains(thisVid)) { + boolean okFlag = true; + try { + processedVertices.add(thisVtx.id().toString()); + thisVtx.remove(); + deleteCount++; + thisNtDeleteCount++; + } catch (Exception e) { + okFlag = false; + LOGGER.error("ERROR trying to delete missing-dep-node VID = " + thisVid, e); + } + if (okFlag) { + LOGGER.info(" DELETED missing-dep-node VID = " + thisVid); + } + } else { + // We count nodes missing their depNodes two ways - the first if it has + // at least some edges, and the second if it has zero edges. Either + // way, they are effectively orphaned. + // NOTE - Only nodes that have dependent nodes are ever considered "orphaned". + if( zeroEdges ){ + missingDepNodeHash.put(thisVid, thisVtx); + } + else { + orphanNodeHash.put(thisVid, thisVtx); + } + } + } + else if ( pCount > 1 ){ + // Not sure how this could happen? Should we do something here? + depNodeOk = false; + } + else { + // We found the parent - so use it to do the second-look. + // NOTE --- We're just going to do the same check from the other direction - because + // there could be duplicates or the pointer going the other way could be broken + ArrayList tmpListSec = new ArrayList <> (); + + tmpListSec = getConnectedChildrenOfOneType( source1, parentVtx, nType ) ; + Iterator vIter = tmpListSec.iterator(); + while (vIter.hasNext()) { + Vertex tmpV = vIter.next(); + if( vertexHasTheseKeys(tmpV, propHashWithKeys) ){ + secondGetList.add(tmpV); + } + } + } + } + + if( depNodeOk && (secondGetList == null || secondGetList.size() == 0) ){ + // We could not get the node back using it's own key info. + // So, it's a PHANTOM + if (deleteCandidateList.contains(thisVid)) { + boolean okFlag = true; + try { + thisVtx.remove(); + deleteCount++; + thisNtDeleteCount++; + } catch (Exception e) { + okFlag = false; + LOGGER.error("ERROR trying to delete phantom VID = " + thisVid, e); + } + if (okFlag) { + LOGGER.info(" DELETED VID = " + thisVid); + } + } else { + ghostNodeHash.put(thisVid, thisVtx); + } + } + else if( (secondGetList.size() > 1) && depNodeOk && !dupeCheckOff ){ + // Found some DUPLICATES - need to process them + LOGGER.info(" - now check Dupes for this guy - "); + List tmpDupeGroups = checkAndProcessDupes( + TRANSID, FROMAPPID, g, source1, version, + nType, secondGetList, dupeFixOn, + deleteCandidateList, singleCommits, dupeGroups, loader); + Iterator dIter = tmpDupeGroups.iterator(); + while (dIter.hasNext()) { + // Add in any newly found dupes to our running list + String tmpGrp = dIter.next(); + LOGGER.info("Found set of dupes: [" + tmpGrp + "]"); + dupeGroups.add(tmpGrp); + } + } + } + catch (AAIException e1) { + LOGGER.warn(" For nodeType = " + nType + " Caught exception", e1); + errArr.add(e1.getErrorObject().toString()); + } + catch (Exception e2) { + LOGGER.warn(" For nodeType = " + nType + + " Caught exception", e2); + errArr.add(e2.getMessage()); + } + }// try block to enclose looping of a single vertex + catch (Exception exx) { + LOGGER.warn("WARNING from inside the while-verts-loop ", exx); + } + + } // while loop for each record of a nodeType + + if ( (thisNtDeleteCount > 0) && singleCommits ) { + // NOTE - the singleCommits option is not used in normal processing + g.tx().commit(); + g = AAIGraph.getInstance().getGraph().newTransaction(); + + } + thisNtDeleteCount = 0; + LOGGER.info( " Processed " + thisNtCount + " records for [" + nType + "], " + totalNodeCount + " total overall. " ); + + }// While-loop for each node type + }// end of check to make sure we weren't only supposed to do edges + + + if( !skipEdgeCheckFlag ){ + // -------------------------------------------------------------------------------------- + // Now, we're going to look for one-armed-edges. Ie. an edge that + // should have + // been deleted (because a vertex on one side was deleted) but + // somehow was not deleted. + // So the one end of it points to a vertexId -- but that vertex is + // empty. + // -------------------------------------------------------------------------------------- + + // To do some strange checking - we need a second graph object + LOGGER.debug(" ---- DEBUG --- about to open a SECOND graph (takes a little while)--------\n"); + // Note - graph2 just reads - but we want it to use a fresh connection to + // the database, so we are NOT using the CACHED DB CONFIG here. + graph2 = TitanFactory.open(AAIConstants.REALTIME_DB_CONFIG); + if (graph2 == null) { + String emsg = "null graph2 object in DataGrooming\n"; + throw new AAIException("AAI_6101", emsg); + } else { + LOGGER.debug("Got the graph2 object... \n"); + } + g2 = graph2.newTransaction(); + if (g2 == null) { + String emsg = "null graphTransaction2 object in DataGrooming\n"; + throw new AAIException("AAI_6101", emsg); + } + + ArrayList vertList = new ArrayList<>(); + Iterator vItor3 = g.traversal().V(); + // Gotta hold these in a List - or else HBase times out as you cycle + // through these + while (vItor3.hasNext()) { + Vertex v = vItor3.next(); + vertList.add(v); + } + int counter = 0; + int lastShown = 0; + Iterator vItor2 = vertList.iterator(); + LOGGER.info(" Checking for bad edges --- "); + + while (vItor2.hasNext()) { + Vertex v = null; + try { + try { + v = vItor2.next(); + } catch (Exception vex) { + LOGGER.warn(">>> WARNING trying to get next vertex on the vItor2 "); + continue; + } + + counter++; + String thisVertId = ""; + try { + thisVertId = v.id().toString(); + } catch (Exception ev) { + LOGGER.warn("WARNING when doing getId() on a vertex from our vertex list. "); + continue; + } + if (ghostNodeHash.containsKey(thisVertId)) { + // This is a phantom node, so don't try to use it + LOGGER.info(" >> Skipping edge check for edges from vertexId = " + + thisVertId + + ", since that guy is a Phantom Node"); + continue; + } + + if( windowStartTime > 0 ){ + // We only want to look at nodes that are created after a passed-in timestamp + Object objTimeStamp = v.property("aai-created-ts").orElse(null); + if( objTimeStamp != null ){ + long thisNodeCreateTime = (long)objTimeStamp; + if( thisNodeCreateTime < windowStartTime ){ + // It is NOT in our window, so we can pass over it + continue; + } + } + } + + if (counter == lastShown + 250) { + lastShown = counter; + LOGGER.info("... Checking edges for vertex # " + + counter); + } + Iterator eItor = v.edges(Direction.BOTH); + while (eItor.hasNext()) { + Edge e = null; + Vertex vIn = null; + Vertex vOut = null; + try { + e = eItor.next(); + } catch (Exception iex) { + LOGGER.warn(">>> WARNING trying to get next edge on the eItor ", iex); + continue; + } + + try { + vIn = e.inVertex(); + } catch (Exception err) { + LOGGER.warn(">>> WARNING trying to get edge's In-vertex ", err); + } + String vNtI = ""; + String vIdI = ""; + Vertex ghost2 = null; + + Boolean keysMissing = true; + Boolean cantGetUsingVid = false; + if (vIn != null) { + try { + Object ob = vIn.property("aai-node-type").orElse(null); + if (ob != null) { + vNtI = ob.toString(); + keysMissing = anyKeyFieldsMissing(vNtI, vIn, loader); + } + ob = vIn.id(); + long vIdLong = 0L; + if (ob != null) { + vIdI = ob.toString(); + vIdLong = Long.parseLong(vIdI); + } + + if( ! ghost2CheckOff ){ + Vertex connectedVert = g2.traversal().V(vIdLong).next(); + if( connectedVert == null ) { + LOGGER.warn( "GHOST2 -- got NULL when doing getVertex for vid = " + vIdLong); + cantGetUsingVid = true; + + // If we can NOT get this ghost with the SECOND graph-object, + // it is still a ghost since even though we can get data about it using the FIRST graph + // object. + try { + ghost2 = g.traversal().V(vIdLong).next(); + } + catch( Exception ex){ + LOGGER.warn( "GHOST2 -- Could not get the ghost info for a bad edge for vtxId = " + vIdLong, ex); + } + if( ghost2 != null ){ + ghostNodeHash.put(vIdI, ghost2); + } + } + }// end of the ghost2 checking + } + catch (Exception err) { + LOGGER.warn(">>> WARNING trying to get edge's In-vertex props ", err); + } + } + if (keysMissing || vIn == null || vNtI.equals("") + || cantGetUsingVid) { + // this is a bad edge because it points to a vertex + // that isn't there anymore or is corrupted + String thisEid = e.id().toString(); + if (deleteCandidateList.contains(thisEid) || deleteCandidateList.contains(vIdI)) { + boolean okFlag = true; + if (!vIdI.equals("")) { + // try to get rid of the corrupted vertex + try { + if( (ghost2 != null) && ghost2FixOn ){ + ghost2.remove(); + } + else { + vIn.remove(); + } + if (singleCommits) { + // NOTE - the singleCommits option is not used in normal processing + g.tx().commit(); + g = AAIGraph.getInstance().getGraph().newTransaction(); + } + deleteCount++; + } catch (Exception e1) { + okFlag = false; + LOGGER.warn("WARNING when trying to delete bad-edge-connected VERTEX VID = " + + vIdI, e1); + } + if (okFlag) { + LOGGER.info(" DELETED vertex from bad edge = " + + vIdI); + } + } else { + // remove the edge if we couldn't get the + // vertex + try { + e.remove(); + if (singleCommits) { + // NOTE - the singleCommits option is not used in normal processing + g.tx().commit(); + g = AAIGraph.getInstance().getGraph().newTransaction(); + } + deleteCount++; + } catch (Exception ex) { + // NOTE - often, the exception is just + // that this edge has already been + // removed + okFlag = false; + LOGGER.warn("WARNING when trying to delete edge = " + + thisEid); + } + if (okFlag) { + LOGGER.info(" DELETED edge = " + thisEid); + } + } + } else { + oneArmedEdgeHash.put(thisEid, e); + if ((vIn != null) && (vIn.id() != null)) { + emptyVertexHash.put(thisEid, vIn.id() + .toString()); + } + } + } + + try { + vOut = e.outVertex(); + } catch (Exception err) { + LOGGER.warn(">>> WARNING trying to get edge's Out-vertex "); + } + String vNtO = ""; + String vIdO = ""; + ghost2 = null; + keysMissing = true; + cantGetUsingVid = false; + if (vOut != null) { + try { + Object ob = vOut.property("aai-node-type").orElse(null); + if (ob != null) { + vNtO = ob.toString(); + keysMissing = anyKeyFieldsMissing(vNtO, + vOut, loader); + } + ob = vOut.id(); + long vIdLong = 0L; + if (ob != null) { + vIdO = ob.toString(); + vIdLong = Long.parseLong(vIdO); + } + + if( ! ghost2CheckOff ){ + Vertex connectedVert = g2.traversal().V(vIdLong).next(); + if( connectedVert == null ) { + cantGetUsingVid = true; + LOGGER.info( "GHOST2 -- got NULL when doing getVertex for vid = " + vIdLong); + // If we can get this ghost with the other graph-object, then get it -- it's still a ghost + try { + ghost2 = g.traversal().V(vIdLong).next(); + } + catch( Exception ex){ + LOGGER.warn( "GHOST2 -- Could not get the ghost info for a bad edge for vtxId = " + vIdLong, ex); + } + if( ghost2 != null ){ + ghostNodeHash.put(vIdO, ghost2); + } + } + } + } catch (Exception err) { + LOGGER.warn(">>> WARNING trying to get edge's Out-vertex props ", err); + } + } + if (keysMissing || vOut == null || vNtO.equals("") + || cantGetUsingVid) { + // this is a bad edge because it points to a vertex + // that isn't there anymore + String thisEid = e.id().toString(); + if (deleteCandidateList.contains(thisEid) || deleteCandidateList.contains(vIdO)) { + boolean okFlag = true; + if (!vIdO.equals("")) { + // try to get rid of the corrupted vertex + try { + if( (ghost2 != null) && ghost2FixOn ){ + ghost2.remove(); + } + else if (vOut != null) { + vOut.remove(); + } + if (singleCommits) { + // NOTE - the singleCommits option is not used in normal processing + g.tx().commit(); + g = AAIGraph.getInstance().getGraph().newTransaction(); + } + deleteCount++; + } catch (Exception e1) { + okFlag = false; + LOGGER.warn("WARNING when trying to delete bad-edge-connected VID = " + + vIdO, e1); + } + if (okFlag) { + LOGGER.info(" DELETED vertex from bad edge = " + + vIdO); + } + } else { + // remove the edge if we couldn't get the + // vertex + try { + e.remove(); + if (singleCommits) { + // NOTE - the singleCommits option is not used in normal processing + g.tx().commit(); + g = AAIGraph.getInstance().getGraph().newTransaction(); + } + deleteCount++; + } catch (Exception ex) { + // NOTE - often, the exception is just + // that this edge has already been + // removed + okFlag = false; + LOGGER.warn("WARNING when trying to delete edge = " + + thisEid, ex); + } + if (okFlag) { + LOGGER.info(" DELETED edge = " + thisEid); + } + } + } else { + oneArmedEdgeHash.put(thisEid, e); + if ((vOut != null) && (vOut.id() != null)) { + emptyVertexHash.put(thisEid, vOut.id() + .toString()); + } + } + } + }// End of while-edges-loop + } catch (Exception exx) { + LOGGER.warn("WARNING from in the while-verts-loop ", exx); + } + }// End of while-vertices-loop (the edge-checking) + } // end of -- if we're not skipping the edge-checking + + + deleteCount = deleteCount + dupeGrpsDeleted; + if (!singleCommits && deleteCount > 0) { + try { + LOGGER.info("About to do the commit for " + + deleteCount + " removes. "); + executeFinalCommit = true; + LOGGER.info("Commit was successful "); + } catch (Exception excom) { + LOGGER.error(" >>>> ERROR <<<< Could not commit changes. ", excom); + deleteCount = 0; + } + } + + int ghostNodeCount = ghostNodeHash.size(); + int orphanNodeCount = orphanNodeHash.size(); + int missingDepNodeCount = missingDepNodeHash.size(); + int oneArmedEdgeCount = oneArmedEdgeHash.size(); + int dupeCount = dupeGroups.size(); + + deleteCount = deleteCount + dupeGrpsDeleted; + + bw.write("\n\n ============ Summary ==============\n"); + bw.write("Ran these nodeTypes: " + ntList + "\n\n"); + bw.write("There were this many delete candidates from previous run = " + + deleteCandidateList.size() + "\n"); + if (dontFixOrphansFlag) { + bw.write(" Note - we are not counting orphan nodes since the -dontFixOrphans parameter was used. \n"); + } + bw.write("Deleted this many delete candidates = " + deleteCount + + "\n"); + bw.write("Total number of nodes looked at = " + totalNodeCount + + "\n"); + bw.write("Ghost Nodes identified = " + ghostNodeCount + "\n"); + bw.write("Orphan Nodes identified = " + orphanNodeCount + "\n"); + bw.write("Bad Edges identified = " + oneArmedEdgeCount + "\n"); + bw.write("Missing Dependent Edge (but not orphaned) node count = " + + missingDepNodeCount + "\n"); + bw.write("Duplicate Groups count = " + dupeCount + "\n"); + bw.write("MisMatching Label/aai-node-type count = " + + misMatchedHash.size() + "\n"); + + bw.write("\n ------------- Delete Candidates ---------\n"); + for (Map.Entry entry : ghostNodeHash + .entrySet()) { + String vid = entry.getKey(); + bw.write("DeleteCandidate: Phantom Vid = [" + vid + "]\n"); + cleanupCandidateCount++; + } + for (Map.Entry entry : orphanNodeHash + .entrySet()) { + String vid = entry.getKey(); + bw.write("DeleteCandidate: OrphanDepNode Vid = [" + vid + "]\n"); + if (!dontFixOrphansFlag) { + cleanupCandidateCount++; + } + } + for (Map.Entry entry : oneArmedEdgeHash.entrySet()) { + String eid = entry.getKey(); + bw.write("DeleteCandidate: Bad EDGE Edge-id = [" + eid + "]\n"); + cleanupCandidateCount++; + } + for (Map.Entry entry : missingDepNodeHash + .entrySet()) { + String vid = entry.getKey(); + bw.write("DeleteCandidate: (maybe) missingDepNode Vid = [" + + vid + "]\n"); + cleanupCandidateCount++; + } + bw.write("\n-- NOTE - To see DeleteCandidates for Duplicates, you need to look in the Duplicates Detail section below.\n"); + + bw.write("\n ------------- GHOST NODES - detail "); + for (Map.Entry entry : ghostNodeHash + .entrySet()) { + try { + String vid = entry.getKey(); + bw.write("\n ==> Phantom Vid = " + vid + "\n"); + ArrayList retArr = showPropertiesForNode( + TRANSID, FROMAPPID, entry.getValue()); + for (String info : retArr) { + bw.write(info + "\n"); + } + + retArr = showAllEdgesForNode(TRANSID, FROMAPPID, + entry.getValue()); + for (String info : retArr) { + bw.write(info + "\n"); + } + } catch (Exception dex) { + LOGGER.error("error trying to print detail info for a ghost-node: ", dex); + } + } + + bw.write("\n ------------- Missing Dependent Edge ORPHAN NODES - detail: "); + for (Map.Entry entry : orphanNodeHash + .entrySet()) { + try { + String vid = entry.getKey(); + bw.write("\n> Orphan Node Vid = " + vid + "\n"); + ArrayList retArr = showPropertiesForNode( + TRANSID, FROMAPPID, entry.getValue()); + for (String info : retArr) { + bw.write(info + "\n"); + } + + retArr = showAllEdgesForNode(TRANSID, FROMAPPID, + entry.getValue()); + for (String info : retArr) { + bw.write(info + "\n"); + } + } catch (Exception dex) { + LOGGER.error("error trying to print detail info for a Orphan Node /missing dependent edge", dex); + } + } + + bw.write("\n ------------- Missing Dependent Edge (but not orphan) NODES: "); + for (Map.Entry entry : missingDepNodeHash + .entrySet()) { + try { + String vid = entry.getKey(); + bw.write("\n> Missing edge to Dependent Node (but has edges) Vid = " + + vid + "\n"); + ArrayList retArr = showPropertiesForNode( + TRANSID, FROMAPPID, entry.getValue()); + for (String info : retArr) { + bw.write(info + "\n"); + } + + retArr = showAllEdgesForNode(TRANSID, FROMAPPID, + entry.getValue()); + for (String info : retArr) { + bw.write(info + "\n"); + } + } catch (Exception dex) { + LOGGER.error("error trying to print detail info for a node missing its dependent edge but not an orphan", dex); + } + } + + bw.write("\n ------------- EDGES pointing to empty/bad vertices: "); + for (Map.Entry entry : oneArmedEdgeHash.entrySet()) { + try { + String eid = entry.getKey(); + Edge thisE = entry.getValue(); + String badVid = emptyVertexHash.get(eid); + bw.write("\n> Edge pointing to bad vertex (Vid = " + + badVid + ") EdgeId = " + eid + "\n"); + bw.write("Label: [" + thisE.label() + "]\n"); + Iterator> pI = thisE.properties(); + while (pI.hasNext()) { + Property propKey = pI.next(); + bw.write("Prop: [" + propKey + "], val = [" + + propKey.value() + "]\n"); + } + } catch (Exception pex) { + LOGGER.error("error trying to print empty/bad vertex data: ", pex); + } + } + + bw.write("\n ------------- Duplicates: "); + Iterator dupeIter = dupeGroups.iterator(); + int dupeSetCounter = 0; + while (dupeIter.hasNext()) { + dupeSetCounter++; + String dset = (String) dupeIter.next(); + + bw.write("\n --- Duplicate Group # " + dupeSetCounter + + " Detail -----------\n"); + try { + // We expect each line to have at least two vid's, followed + // by the preferred one to KEEP + String[] dupeArr = dset.split("\\|"); + ArrayList idArr = new ArrayList<>(); + int lastIndex = dupeArr.length - 1; + for (int i = 0; i <= lastIndex; i++) { + if (i < lastIndex) { + // This is not the last entry, it is one of the + // dupes, so we want to show all its info + bw.write(" >> Duplicate Group # " + + dupeSetCounter + " Node # " + i + + " ----\n"); + String vidString = dupeArr[i]; + idArr.add(vidString); + long longVertId = Long.parseLong(vidString); + Iterator vtxIterator = g.vertices(longVertId); + Vertex vtx = null; + if (vtxIterator.hasNext()) { + vtx = vtxIterator.next(); + } + ArrayList retArr = showPropertiesForNode(TRANSID, FROMAPPID, vtx); + for (String info : retArr) { + bw.write(info + "\n"); + } + + retArr = showAllEdgesForNode(TRANSID, + FROMAPPID, vtx); + for (String info : retArr) { + bw.write(info + "\n"); + } + } else { + // This is the last entry which should tell us if we + // have a preferred keeper + String prefString = dupeArr[i]; + if (prefString.equals("KeepVid=UNDETERMINED")) { + bw.write("\n For this group of duplicates, could not tell which one to keep.\n"); + bw.write(" >>> This group needs to be taken care of with a manual/forced-delete.\n"); + } else { + // If we know which to keep, then the prefString + // should look like, "KeepVid=12345" + String[] prefArr = prefString.split("="); + if (prefArr.length != 2 + || (!prefArr[0].equals("KeepVid"))) { + throw new Exception("Bad format. Expecting KeepVid=999999"); + } else { + String keepVidStr = prefArr[1]; + if (idArr.contains(keepVidStr)) { + bw.write("\n The vertex we want to KEEP has vertexId = " + + keepVidStr); + bw.write("\n The others become delete candidates: \n"); + idArr.remove(keepVidStr); + for (int x = 0; x < idArr.size(); x++) { + cleanupCandidateCount++; + bw.write("DeleteCandidate: Duplicate Vid = [" + + idArr.get(x) + "]\n"); + } + } else { + throw new Exception("ERROR - Vertex Id to keep not found in list of dupes. dset = [" + + dset + "]"); + } + } + }// else we know which one to keep + }// else last entry + }// for each vertex in a group + } catch (Exception dex) { + LOGGER.error("error trying to print duplicate vertex data", dex); + } + + }// while - work on each group of dupes + + bw.write("\n ------------- Mis-matched Label/aai-node-type Nodes: \n "); + for (Map.Entry entry : misMatchedHash.entrySet()) { + String msg = entry.getValue(); + bw.write("MixedMsg = " + msg + "\n"); + } + + bw.write("\n ------------- Got these errors while processing: \n"); + Iterator errIter = errArr.iterator(); + while (errIter.hasNext()) { + String line = (String) errIter.next(); + bw.write(line + "\n"); + } + + bw.close(); + + LOGGER.info("\n ------------- Done doing all the checks ------------ "); + LOGGER.info("Output will be written to " + fullOutputFileName); + + if (cleanupCandidateCount > 0) { + // Technically, this is not an error -- but we're throwing this + // error so that hopefully a + // monitoring system will pick it up and do something with it. + throw new AAIException("AAI_6123", "See file: [" + fullOutputFileName + + "] and investigate delete candidates. "); + } + } catch (AAIException e) { + LOGGER.error("Caught AAIException while grooming data", e); + ErrorLogHelper.logException(e); + } catch (Exception ex) { + LOGGER.error("Caught exception while grooming data", ex); + ErrorLogHelper.logError("AAI_6128", ex.getMessage() + ", resolve and rerun dataGrooming"); + } finally { + + if (bw != null) { + try { + bw.close(); + } catch (IOException iox) { + LOGGER.warn("Got an IOException trying to close bufferedWriter() \n", iox); + } + } + + if (g != null && g.tx().isOpen()) { + // Any changes that worked correctly should have already done + // their commits. + try { + if (executeFinalCommit) { + g.tx().commit(); + } + g.tx().rollback(); + } catch (Exception ex) { + // Don't throw anything because Titan sometimes is just saying that the graph is already closed + LOGGER.warn("WARNING from final graphTransaction.rollback()", ex); + } + } + + if (g2 != null && g2.tx().isOpen()) { + // Any changes that worked correctly should have already done + // their commits. + try { + g2.tx().rollback(); + } catch (Exception ex) { + // Don't throw anything because Titan sometimes is just saying that the graph is already closed + LOGGER.warn("WARNING from final graphTransaction2.rollback()", ex); + } + } + + if( finalShutdownFlag ){ + try { + if( graph != null && graph.isOpen() ){ + graph.tx().close(); + graph.close(); + } + } catch (Exception ex) { + // Don't throw anything because Titan sometimes is just saying that the graph is already closed{ + LOGGER.warn("WARNING from final graph.shutdown()", ex); + } + + try { + if( graph2 != null && graph2.isOpen() ){ + graph2.tx().close(); + graph2.close(); + } + } catch (Exception ex) { + // Don't throw anything because Titan sometimes is just saying that the graph is already closed{ + LOGGER.warn("WARNING from final graph2.shutdown()", ex); + } + } + + } + + return cleanupCandidateCount; + + }// end of doTheGrooming() + + + /** + * Vertex has these keys. + * + * @param tmpV the tmp V + * @param propHashWithKeys the prop hash with keys + * @return the boolean + */ + private static Boolean vertexHasTheseKeys( Vertex tmpV, HashMap propHashWithKeys) { + Iterator it = propHashWithKeys.entrySet().iterator(); + while( it.hasNext() ){ + String propName = ""; + String propVal = ""; + Map.Entry propEntry = (Map.Entry)it.next(); + Object propNameObj = propEntry.getKey(); + if( propNameObj != null ){ + propName = propNameObj.toString(); + } + Object propValObj = propEntry.getValue(); + if( propValObj != null ){ + propVal = propValObj.toString(); + } + Object checkValObj = tmpV.property(propName).orElse(null); + if( checkValObj == null ) { + return false; + } + else if( !propVal.equals(checkValObj.toString()) ){ + return false; + } + } + return true; + } + + + /** + * Any key fields missing. + * + * @param nType the n type + * @param v the v + * @return the boolean + */ + private static Boolean anyKeyFieldsMissing(String nType, Vertex v, Loader loader) { + + try { + Introspector obj = null; + try { + obj = loader.introspectorFromName(nType); + } catch (AAIUnknownObjectException e) { + // They gave us a non-empty nodeType but our NodeKeyProps does + // not have data for it. Since we do not know what the + // key params are for this type of node, we will just + // return "false". + String emsg = " -- WARNING -- Unrecognized nodeType: [" + nType + + "]. We cannot determine required keys for this nType. "; + // NOTE - this will be caught below and a "false" returned + throw new AAIException("AAI_6121", emsg); + } + + // Determine what the key fields are for this nodeType + Collection keyPropNamesColl = obj.getKeys(); + Iterator keyPropI = keyPropNamesColl.iterator(); + while (keyPropI.hasNext()) { + String propName = keyPropI.next(); + Object ob = v.property(propName).orElse(null); + if (ob == null || ob.toString().equals("")) { + // It is missing a key property + return true; + } + } + } catch (AAIException e) { + // Something was wrong -- but since we weren't able to check + // the keys, we will not declare that it is missing keys. + return false; + } + return false; + } + + + /** + * Gets the delete list. + * + * @param targetDir the target dir + * @param fileName the file name + * @param edgesOnlyFlag the edges only flag + * @param dontFixOrphans the dont fix orphans + * @param dupeFixOn the dupe fix on + * @return the delete list + * @throws AAIException the AAI exception + */ + private static Set getDeleteList(String targetDir, + String fileName, Boolean edgesOnlyFlag, Boolean dontFixOrphans, + Boolean dupeFixOn) throws AAIException { + + // Look in the file for lines formated like we expect - pull out any + // Vertex Id's to delete on this run + Set delList = new LinkedHashSet<>(); + String fullFileName = targetDir + AAIConstants.AAI_FILESEP + fileName; + + try(BufferedReader br = new BufferedReader(new FileReader(fullFileName))) { + String line = br.readLine(); + while (line != null) { + if (!"".equals(line) && line.startsWith("DeleteCandidate")) { + if (edgesOnlyFlag && (!line.contains("Bad Edge"))) { + // We're not going to process edge guys + } else if (dontFixOrphans && line.contains("Orphan")) { + // We're not going to process orphans + } else if (!dupeFixOn && line.contains("Duplicate")) { + // We're not going to process Duplicates + } else { + int begIndex = line.indexOf("id = "); + int endIndex = line.indexOf("]"); + String vidVal = line.substring(begIndex + 6, endIndex); + delList.add(vidVal); + } + } + line = br.readLine(); + } + br.close(); + } catch (IOException e) { + throw new AAIException("AAI_6124", e, "Could not open input-file [" + fullFileName + + "], exception= " + e.getMessage()); + } + + return delList; + + }// end of getDeleteList + + /** + * Gets the preferred dupe. + * + * @param transId the trans id + * @param fromAppId the from app id + * @param g the g + * @param dupeVertexList the dupe vertex list + * @param ver the ver + * @return Vertex + * @throws AAIException the AAI exception + */ + public static Vertex getPreferredDupe(String transId, + String fromAppId, GraphTraversalSource g, + ArrayList dupeVertexList, String ver, Loader loader) + throws AAIException { + + // This method assumes that it is being passed a List of vertex objects + // which + // violate our uniqueness constraints. + + Vertex nullVtx = null; + + if (dupeVertexList == null) { + return nullVtx; + } + int listSize = dupeVertexList.size(); + if (listSize == 0) { + return nullVtx; + } + if (listSize == 1) { + return (dupeVertexList.get(0)); + } + + Vertex vtxPreferred = null; + Vertex currentFaveVtx = dupeVertexList.get(0); + for (int i = 1; i < listSize; i++) { + Vertex vtxB = dupeVertexList.get(i); + vtxPreferred = pickOneOfTwoDupes(transId, fromAppId, g, + currentFaveVtx, vtxB, ver, loader); + if (vtxPreferred == null) { + // We couldn't choose one + return nullVtx; + } else { + currentFaveVtx = vtxPreferred; + } + } + + return (currentFaveVtx); + + } // end of getPreferredDupe() + + /** + * Pick one of two dupes. + * + * @param transId the trans id + * @param fromAppId the from app id + * @param g the g + * @param vtxA the vtx A + * @param vtxB the vtx B + * @param ver the ver + * @return Vertex + * @throws AAIException the AAI exception + */ + public static Vertex pickOneOfTwoDupes(String transId, + String fromAppId, GraphTraversalSource g, Vertex vtxA, + Vertex vtxB, String ver, Loader loader) throws AAIException { + + Vertex nullVtx = null; + Vertex preferredVtx = null; + + Long vidA = new Long(vtxA.id().toString()); + Long vidB = new Long(vtxB.id().toString()); + + String vtxANodeType = ""; + String vtxBNodeType = ""; + Object objType = vtxA.property("aai-node-type").orElse(null); + if (objType != null) { + vtxANodeType = objType.toString(); + } + objType = vtxB.property("aai-node-type").orElse(null); + if (objType != null) { + vtxBNodeType = objType.toString(); + } + + if (vtxANodeType.equals("") || (!vtxANodeType.equals(vtxBNodeType))) { + // Either they're not really dupes or there's some bad data - so + // don't pick one + return nullVtx; + } + + // Check that node A and B both have the same key values (or else they + // are not dupes) + // (We'll check dep-node later) + // Determine what the key fields are for this nodeType + Collection keyProps = new ArrayList <>(); + try { + keyProps = loader.introspectorFromName(vtxANodeType).getKeys(); + } catch (AAIUnknownObjectException e) { + LOGGER.warn("Required property not found", e); + throw new AAIException("AAI_6105", "Required Property name(s) not found for nodeType = " + vtxANodeType + ")"); + } + + Iterator keyPropI = keyProps.iterator(); + while (keyPropI.hasNext()) { + String propName = keyPropI.next(); + String vtxAKeyPropVal = ""; + objType = vtxA.property(propName).orElse(null); + if (objType != null) { + vtxAKeyPropVal = objType.toString(); + } + String vtxBKeyPropVal = ""; + objType = vtxB.property(propName).orElse(null); + if (objType != null) { + vtxBKeyPropVal = objType.toString(); + } + + if (vtxAKeyPropVal.equals("") + || (!vtxAKeyPropVal.equals(vtxBKeyPropVal))) { + // Either they're not really dupes or they are missing some key + // data - so don't pick one + return nullVtx; + } + } + + // Collect the vid's and aai-node-types of the vertices that each vertex + // (A and B) is connected to. + ArrayList vtxIdsConn2A = new ArrayList<>(); + ArrayList vtxIdsConn2B = new ArrayList<>(); + HashMap nodeTypesConn2A = new HashMap<>(); + HashMap nodeTypesConn2B = new HashMap<>(); + + ArrayList vertListA = getConnectedNodes( g, vtxA ); + if (vertListA != null) { + Iterator iter = vertListA.iterator(); + while (iter.hasNext()) { + Vertex tvCon = iter.next(); + String conVid = tvCon.id().toString(); + String nt = ""; + objType = tvCon.property("aai-node-type").orElse(null); + if (objType != null) { + nt = objType.toString(); + } + nodeTypesConn2A.put(nt, conVid); + vtxIdsConn2A.add(conVid); + } + } + + ArrayList vertListB = getConnectedNodes( g, vtxB ); + if (vertListB != null) { + Iterator iter = vertListB.iterator(); + while (iter.hasNext()) { + Vertex tvCon = iter.next(); + String conVid = tvCon.id().toString(); + String nt = ""; + objType = tvCon.property("aai-node-type").orElse(null); + if (objType != null) { + nt = objType.toString(); + } + nodeTypesConn2B.put(nt, conVid); + vtxIdsConn2B.add(conVid); + } + } + + // 1 - If this kind of node needs a dependent node for uniqueness, then + // verify that they both nodes + // point to the same dependent node (otherwise they're not really + // duplicates) + // Note - there are sometimes more than one dependent node type since + // one nodeType can be used in + // different ways. But for a particular node, it will only have one + // dependent node that it's + // connected to. + Collection depNodeTypes = loader.introspectorFromName(vtxANodeType).getDependentOn(); + + if (depNodeTypes.isEmpty()) { + // This kind of node is not dependent on any other. That is ok. + } else { + String depNodeVtxId4A = ""; + String depNodeVtxId4B = ""; + Iterator iter = depNodeTypes.iterator(); + while (iter.hasNext()) { + String depNodeType = iter.next(); + if (nodeTypesConn2A.containsKey(depNodeType)) { + // This is the dependent node type that vertex A is using + depNodeVtxId4A = nodeTypesConn2A.get(depNodeType); + } + if (nodeTypesConn2B.containsKey(depNodeType)) { + // This is the dependent node type that vertex B is using + depNodeVtxId4B = nodeTypesConn2B.get(depNodeType); + } + } + if (depNodeVtxId4A.equals("") + || (!depNodeVtxId4A.equals(depNodeVtxId4B))) { + // Either they're not really dupes or there's some bad data - so + // don't pick either one + return nullVtx; + } + } + + if (vtxIdsConn2A.size() == vtxIdsConn2B.size()) { + // 2 - If they both have edges to all the same vertices, then return + // the one with the lower vertexId. + boolean allTheSame = true; + Iterator iter = vtxIdsConn2A.iterator(); + while (iter.hasNext()) { + String vtxIdConn2A = iter.next(); + if (!vtxIdsConn2B.contains(vtxIdConn2A)) { + allTheSame = false; + break; + } + } + + if (allTheSame) { + if (vidA < vidB) { + preferredVtx = vtxA; + } else { + preferredVtx = vtxB; + } + } + } else if (vtxIdsConn2A.size() > vtxIdsConn2B.size()) { + // 3 - VertexA is connected to more things than vtxB. + // We'll pick VtxA if its edges are a superset of vtxB's edges. + boolean missingOne = false; + Iterator iter = vtxIdsConn2B.iterator(); + while (iter.hasNext()) { + String vtxIdConn2B = iter.next(); + if (!vtxIdsConn2A.contains(vtxIdConn2B)) { + missingOne = true; + break; + } + } + if (!missingOne) { + preferredVtx = vtxA; + } + } else if (vtxIdsConn2B.size() > vtxIdsConn2A.size()) { + // 4 - VertexB is connected to more things than vtxA. + // We'll pick VtxB if its edges are a superset of vtxA's edges. + boolean missingOne = false; + Iterator iter = vtxIdsConn2A.iterator(); + while (iter.hasNext()) { + String vtxIdConn2A = iter.next(); + if (!vtxIdsConn2B.contains(vtxIdConn2A)) { + missingOne = true; + break; + } + } + if (!missingOne) { + preferredVtx = vtxB; + } + } else { + preferredVtx = nullVtx; + } + + return (preferredVtx); + + } // end of pickOneOfTwoDupes() + + /** + * Check and process dupes. + * + * @param transId the trans id + * @param fromAppId the from app id + * @param g the g + * @param version the version + * @param nType the n type + * @param passedVertList the passed vert list + * @param dupeFixOn the dupe fix on + * @param deleteCandidateList the delete candidate list + * @param singleCommits the single commits + * @param alreadyFoundDupeGroups the already found dupe groups + * @param dbMaps the db maps + * @return the array list + */ + private static List checkAndProcessDupes(String transId, + String fromAppId, Graph g, GraphTraversalSource source, String version, String nType, + List passedVertList, Boolean dupeFixOn, + Set deleteCandidateList, Boolean singleCommits, + ArrayList alreadyFoundDupeGroups, Loader loader ) { + + ArrayList returnList = new ArrayList<>(); + ArrayList checkVertList = new ArrayList<>(); + ArrayList alreadyFoundDupeVidArr = new ArrayList<>(); + Boolean noFilterList = true; + Iterator afItr = alreadyFoundDupeGroups.iterator(); + while (afItr.hasNext()) { + String dupeGrpStr = afItr.next(); + String[] dupeArr = dupeGrpStr.split("\\|"); + int lastIndex = dupeArr.length - 1; + for (int i = 0; i < lastIndex; i++) { + // Note: we don't want the last one... + String vidString = dupeArr[i]; + alreadyFoundDupeVidArr.add(vidString); + noFilterList = false; + } + } + + // For a given set of Nodes that were found with a set of KEY + // Parameters, (nodeType + key data) we will + // see if we find any duplicate nodes that need to be cleaned up. Note - + // it's legit to have more than one + // node with the same key data if the nodes depend on a parent for + // uniqueness -- as long as the two nodes + // don't hang off the same Parent. + // If we find duplicates, and we can figure out which of each set of + // duplicates is the one that we + // think should be preserved, we will record that. Whether we can tell + // which one should be + // preserved or not, we will return info about any sets of duplicates + // found. + // + // Each element in the returned arrayList might look like this: + // "1234|5678|keepVid=UNDETERMINED" (if there were 2 dupes, and we + // couldn't figure out which one to keep) + // or, "100017|200027|30037|keepVid=30037" (if there were 3 dupes and we + // thought the third one was the one that should survive) + + // Because of the way the calling code loops over stuff, we can get the + // same data multiple times - so we should + // not process any vertices that we've already seen. + + try { + Iterator pItr = passedVertList.iterator(); + while (pItr.hasNext()) { + Vertex tvx = pItr.next(); + String passedId = tvx.id().toString(); + if (noFilterList || !alreadyFoundDupeVidArr.contains(passedId)) { + // We haven't seen this one before - so we should check it. + checkVertList.add(tvx); + } + } + + if (checkVertList.size() < 2) { + // Nothing new to check. + return returnList; + } + + if (loader.introspectorFromName(nType).isTopLevel()) { + // If this was a node that does NOT depend on other nodes for + // uniqueness, and we + // found more than one node using its key -- record the found + // vertices as duplicates. + String dupesStr = ""; + for (int i = 0; i < checkVertList.size(); i++) { + dupesStr = dupesStr + + ((checkVertList.get(i))).id() + .toString() + "|"; + } + if (dupesStr != "") { + Vertex prefV = getPreferredDupe(transId, fromAppId, + source, checkVertList, version, loader); + if (prefV == null) { + // We could not determine which duplicate to keep + dupesStr = dupesStr + "KeepVid=UNDETERMINED"; + returnList.add(dupesStr); + } else { + dupesStr = dupesStr + "KeepVid=" + prefV.id(); + Boolean didRemove = false; + if (dupeFixOn) { + didRemove = deleteNonKeepersIfAppropriate(g, + dupesStr, prefV.id().toString(), + deleteCandidateList, singleCommits); + } + if (didRemove) { + dupeGrpsDeleted++; + } else { + // keep them on our list + returnList.add(dupesStr); + } + } + } + } else { + // More than one node have the same key fields since they may + // depend on a parent node for uniqueness. Since we're finding + // more than one, we want to check to see if any of the + // vertices that have this set of keys (and are the same nodeType) + // are also pointing at the same 'parent' node. + // Note: for a given set of key data, it is possible that there + // could be more than one set of duplicates. + HashMap> vertsGroupedByParentHash = groupVertsByDepNodes( + transId, fromAppId, source, version, nType, + checkVertList, loader); + for (Map.Entry> entry : vertsGroupedByParentHash + .entrySet()) { + ArrayList thisParentsVertList = entry + .getValue(); + if (thisParentsVertList.size() > 1) { + // More than one vertex found with the same key info + // hanging off the same parent/dependent node + String dupesStr = ""; + for (int i = 0; i < thisParentsVertList.size(); i++) { + dupesStr = dupesStr + + ((thisParentsVertList + .get(i))).id() + "|"; + } + if (dupesStr != "") { + Vertex prefV = getPreferredDupe(transId, + fromAppId, source, thisParentsVertList, + version, loader); + + if (prefV == null) { + // We could not determine which duplicate to + // keep + dupesStr = dupesStr + "KeepVid=UNDETERMINED"; + returnList.add(dupesStr); + } else { + Boolean didRemove = false; + dupesStr = dupesStr + "KeepVid=" + + prefV.id().toString(); + if (dupeFixOn) { + didRemove = deleteNonKeepersIfAppropriate( + g, dupesStr, prefV.id() + .toString(), + deleteCandidateList, singleCommits); + } + if (didRemove) { + dupeGrpsDeleted++; + } else { + // keep them on our list + returnList.add(dupesStr); + } + } + } + } + } + } + } catch (Exception e) { + LOGGER.warn(" >>> Threw an error in checkAndProcessDupes - just absorb this error and move on. ", e); + } + + return returnList; + + }// End of checkAndProcessDupes() + + /** + * Group verts by dep nodes. + * + * @param transId the trans id + * @param fromAppId the from app id + * @param g the g + * @param version the version + * @param nType the n type + * @param passedVertList the passed vert list + * @param dbMaps the db maps + * @return the hash map + * @throws AAIException the AAI exception + */ + private static HashMap> groupVertsByDepNodes( + String transId, String fromAppId, GraphTraversalSource g, String version, + String nType, ArrayList passedVertList, Loader loader) + throws AAIException { + // Given a list of Titan Vertices of one nodeType (see AAI-8956), group + // them together by the parent node they depend on. + // Ie. if given a list of ip address nodes (assumed to all have the + // same key info) they might sit under several different parent vertices. + // Under Normal conditions, there would only be one per parent -- but + // we're trying to find duplicates - so we + // allow for the case where more than one is under the same parent node. + + HashMap> retHash = new HashMap>(); + if (loader.introspectorFromName(nType).isTopLevel()) { + // This method really should not have been called if this is not the + // kind of node + // that depends on a parent for uniqueness, so just return the empty + // hash. + return retHash; + } + + // Find out what types of nodes the passed in nodes can depend on + ArrayList depNodeTypeL = new ArrayList<>(); + Collection depNTColl = loader.introspectorFromName(nType).getDependentOn(); + Iterator ntItr = depNTColl.iterator(); + while (ntItr.hasNext()) { + depNodeTypeL.add(ntItr.next()); + } + // For each vertex, we want find its depended-on/parent vertex so we + // can track what other vertexes that are dependent on that same guy. + if (passedVertList != null) { + Iterator iter = passedVertList.iterator(); + while (iter.hasNext()) { + Vertex thisVert = iter.next(); + Vertex tmpParentVtx = getConnectedParent( g, thisVert ); + if( tmpParentVtx != null ) { + String parentNt = null; + Object obj = tmpParentVtx.property("aai-node-type").orElse(null); + if (obj != null) { + parentNt = obj.toString(); + } + if (depNTColl.contains(parentNt)) { + // This must be the parent/dependent node + String parentVid = tmpParentVtx.id().toString(); + if (retHash.containsKey(parentVid)) { + // add this vert to the list for this parent key + retHash.get(parentVid).add(thisVert); + } else { + // This is the first one we found on this parent + ArrayList vList = new ArrayList<>(); + vList.add(thisVert); + retHash.put(parentVid, vList); + } + } + } + } + } + + return retHash; + + }// end of groupVertsByDepNodes() + + /** + * Delete non keepers if appropriate. + * + * @param g the g + * @param dupeInfoString the dupe info string + * @param vidToKeep the vid to keep + * @param deleteCandidateList the delete candidate list + * @param singleCommits the single commits + * @return the boolean + */ + private static Boolean deleteNonKeepersIfAppropriate(Graph g, + String dupeInfoString, String vidToKeep, + Set deleteCandidateList, Boolean singleCommits) { + + Boolean deletedSomething = false; + // This assumes that the dupeInfoString is in the format of + // pipe-delimited vid's followed by + // ie. "3456|9880|keepVid=3456" + if (deleteCandidateList == null || deleteCandidateList.size() == 0) { + // No vid's on the candidate list -- so no deleting will happen on + // this run + return false; + } + + String[] dupeArr = dupeInfoString.split("\\|"); + ArrayList idArr = new ArrayList<>(); + int lastIndex = dupeArr.length - 1; + for (int i = 0; i <= lastIndex; i++) { + if (i < lastIndex) { + // This is not the last entry, it is one of the dupes, + String vidString = dupeArr[i]; + idArr.add(vidString); + } else { + // This is the last entry which should tell us if we have a + // preferred keeper + String prefString = dupeArr[i]; + if (prefString.equals("KeepVid=UNDETERMINED")) { + // They sent us a bad string -- nothing should be deleted if + // no dupe could be tagged as preferred + return false; + } else { + // If we know which to keep, then the prefString should look + // like, "KeepVid=12345" + String[] prefArr = prefString.split("="); + if (prefArr.length != 2 || (!prefArr[0].equals("KeepVid"))) { + LOGGER.error("Bad format. Expecting KeepVid=999999"); + return false; + } else { + String keepVidStr = prefArr[1]; + if (idArr.contains(keepVidStr)) { + idArr.remove(keepVidStr); + + // So now, the idArr should just contain the vid's + // that we want to remove. + for (int x = 0; x < idArr.size(); x++) { + boolean okFlag = true; + String thisVid = idArr.get(x); + if (deleteCandidateList.contains(thisVid)) { + // This vid is a valid delete candidate from + // a prev. run, so we can remove it. + try { + long longVertId = Long + .parseLong(thisVid); + Vertex vtx = g + .traversal().V(longVertId).next(); + vtx.remove(); + if (singleCommits) { + // NOTE - the singleCommits option is not used in normal processing + g.tx().commit(); + g = AAIGraph.getInstance().getGraph().newTransaction(); + } + } catch (Exception e) { + okFlag = false; + LOGGER.error("ERROR trying to delete VID = " + thisVid, e); + } + if (okFlag) { + LOGGER.info(" DELETED VID = " + thisVid); + deletedSomething = true; + } + } + } + } else { + LOGGER.error("ERROR - Vertex Id to keep not found in list of dupes. dupeInfoString = [" + + dupeInfoString + "]"); + return false; + } + } + }// else we know which one to keep + }// else last entry + }// for each vertex in a group + + return deletedSomething; + + }// end of deleteNonKeepersIfAppropriate() + + + /** + * Gets the node just using key params. + * + * @param transId the trans id + * @param fromAppId the from app id + * @param graph the graph + * @param nodeType the node type + * @param keyPropsHash the key props hash + * @param apiVersion the api version + * @return the node just using key params + * @throws AAIException the AAI exception + */ + public static List getNodeJustUsingKeyParams( String transId, String fromAppId, GraphTraversalSource graph, String nodeType, + HashMap keyPropsHash, String apiVersion ) throws AAIException{ + + List retVertList = new ArrayList <> (); + + // We assume that all NodeTypes have at least one key-property defined. + // Note - instead of key-properties (the primary key properties), a user could pass + // alternate-key values if they are defined for the nodeType. + List kName = new ArrayList<>(); + List kVal = new ArrayList<>(); + if( keyPropsHash == null || keyPropsHash.isEmpty() ) { + throw new AAIException("AAI_6120", " NO key properties passed for this getNodeJustUsingKeyParams() request. NodeType = [" + nodeType + "]. "); + } + + int i = -1; + for( Map.Entry entry : keyPropsHash.entrySet() ){ + i++; + kName.add(i, entry.getKey()); + kVal.add(i, entry.getValue()); + } + int topPropIndex = i; + Vertex tiV = null; + String propsAndValuesForMsg = ""; + Iterator verts = null; + + try { + if( topPropIndex == 0 ){ + propsAndValuesForMsg = " (" + kName.get(0) + " = " + kVal.get(0) + ") "; + verts= graph.V().has(kName.get(0),kVal.get(0)).has("aai-node-type",nodeType); + } + else if( topPropIndex == 1 ){ + propsAndValuesForMsg = " (" + kName.get(0) + " = " + kVal.get(0) + ", " + + kName.get(1) + " = " + kVal.get(1) + ") "; + verts = graph.V().has(kName.get(0),kVal.get(0)).has(kName.get(1),kVal.get(1)).has("aai-node-type",nodeType); + } + else if( topPropIndex == 2 ){ + propsAndValuesForMsg = " (" + kName.get(0) + " = " + kVal.get(0) + ", " + + kName.get(1) + " = " + kVal.get(1) + ", " + + kName.get(2) + " = " + kVal.get(2) + ") "; + verts= graph.V().has(kName.get(0),kVal.get(0)).has(kName.get(1),kVal.get(1)).has(kName.get(2),kVal.get(2)).has("aai-node-type",nodeType); + } + else if( topPropIndex == 3 ){ + propsAndValuesForMsg = " (" + kName.get(0) + " = " + kVal.get(0) + ", " + + kName.get(1) + " = " + kVal.get(1) + ", " + + kName.get(2) + " = " + kVal.get(2) + ", " + + kName.get(3) + " = " + kVal.get(3) + ") "; + verts= graph.V().has(kName.get(0),kVal.get(0)).has(kName.get(1),kVal.get(1)).has(kName.get(2),kVal.get(2)).has(kName.get(3),kVal.get(3)).has("aai-node-type",nodeType); + } + else { + throw new AAIException("AAI_6114", " We only support 4 keys per nodeType for now \n"); + } + } + catch( Exception ex ){ + LOGGER.error( " ERROR trying to get node for: [" + propsAndValuesForMsg + "]", ex); + } + + if( verts != null ){ + while( verts.hasNext() ){ + tiV = verts.next(); + retVertList.add(tiV); + } + } + + if( retVertList.size() == 0 ){ + LOGGER.debug("DEBUG No node found for nodeType = [" + nodeType + + "], propsAndVal = " + propsAndValuesForMsg ); + } + + return retVertList; + + }// End of getNodeJustUsingKeyParams() + + /** + * Show all edges for node. + * + * @param transId the trans id + * @param fromAppId the from app id + * @param tVert the t vert + * @return the array list + */ + private static ArrayList showAllEdgesForNode( String transId, String fromAppId, Vertex tVert ){ + + ArrayList retArr = new ArrayList <> (); + Iterator eI = tVert.edges(Direction.IN); + if( ! eI.hasNext() ){ + retArr.add("No IN edges were found for this vertex. "); + } + while( eI.hasNext() ){ + Edge ed = eI.next(); + String lab = ed.label(); + Vertex vtx; + if (tVert.equals(ed.inVertex())) { + vtx = ed.outVertex(); + } else { + vtx = ed.inVertex(); + } + if( vtx == null ){ + retArr.add(" >>> COULD NOT FIND VERTEX on the other side of this edge edgeId = " + ed.id() + " <<< "); + } + else { + String nType = vtx.property("aai-node-type").orElse(null); + String vid = vtx.id().toString(); + retArr.add("Found an IN edge (" + lab + ") to this vertex from a [" + nType + "] node with VtxId = " + vid ); + + } + } + + eI = tVert.edges(Direction.OUT); + if( ! eI.hasNext() ){ + retArr.add("No OUT edges were found for this vertex. "); + } + while( eI.hasNext() ){ + Edge ed = eI.next(); + String lab = ed.label(); + Vertex vtx; + if (tVert.equals(ed.inVertex())) { + vtx = ed.outVertex(); + } else { + vtx = ed.inVertex(); + } + if( vtx == null ){ + retArr.add(" >>> COULD NOT FIND VERTEX on the other side of this edge edgeId = " + ed.id() + " <<< "); + } + else { + String nType = vtx.property("aai-node-type").orElse(null); + String vid = vtx.id().toString(); + retArr.add("Found an OUT edge (" + lab + ") from this vertex to a [" + nType + "] node with VtxId = " + vid ); + } + } + return retArr; + } + + + /** + * Show properties for node. + * + * @param transId the trans id + * @param fromAppId the from app id + * @param tVert the t vert + * @return the array list + */ + private static ArrayList showPropertiesForNode( String transId, String fromAppId, Vertex tVert ){ + + ArrayList retArr = new ArrayList <> (); + if( tVert == null ){ + retArr.add("null Node object passed to showPropertiesForNode()\n"); + } + else { + String nodeType = ""; + Object ob = tVert.property("aai-node-type").orElse(null); + if( ob == null ){ + nodeType = "null"; + } + else{ + nodeType = ob.toString(); + } + + retArr.add(" AAINodeType/VtxID for this Node = [" + nodeType + "/" + tVert.id() + "]"); + retArr.add(" Property Detail: "); + Iterator> pI = tVert.properties(); + while( pI.hasNext() ){ + VertexProperty tp = pI.next(); + Object val = tp.value(); + retArr.add("Prop: [" + tp.key() + "], val = [" + val + "] "); + } + } + return retArr; + } + + + private static ArrayList getConnectedNodes(GraphTraversalSource g, Vertex startVtx ) + throws AAIException { + + ArrayList retArr = new ArrayList <> (); + if( startVtx == null ){ + return retArr; + } + else { + GraphTraversal modPipe = null; + modPipe = g.V(startVtx).both(); + if( modPipe != null && modPipe.hasNext() ){ + while( modPipe.hasNext() ){ + Vertex conVert = modPipe.next(); + retArr.add(conVert); + } + } + } + return retArr; + + }// End of getConnectedNodes() + + + private static ArrayList getConnectedChildrenOfOneType( GraphTraversalSource g, + Vertex startVtx, String childNType ) throws AAIException{ + + ArrayList childList = new ArrayList <> (); + Iterator vertI = g.V(startVtx).union(__.outE().has(EdgeProperty.CONTAINS.toString(), AAIDirection.OUT.toString()).inV(), __.inE().has(EdgeProperty.CONTAINS.toString(), AAIDirection.IN.toString()).outV()); + + Vertex tmpVtx = null; + while( vertI != null && vertI.hasNext() ){ + tmpVtx = vertI.next(); + Object ob = tmpVtx.property("aai-node-type").orElse(null); + if (ob != null) { + String tmpNt = ob.toString(); + if( tmpNt.equals(childNType)){ + childList.add(tmpVtx); + } + } + } + + return childList; + + }// End of getConnectedChildrenOfOneType() + + + private static Vertex getConnectedParent( GraphTraversalSource g, + Vertex startVtx ) throws AAIException{ + + Vertex parentVtx = null; + Iterator vertI = g.V(startVtx).union(__.inE().has(EdgeProperty.CONTAINS.toString(), AAIDirection.OUT.toString()).outV(), __.outE().has(EdgeProperty.CONTAINS.toString(), AAIDirection.IN.toString()).inV()); + + while( vertI != null && vertI.hasNext() ){ + // Note - there better only be one! + parentVtx = vertI.next(); + } + + return parentVtx; + + }// End of getConnectedParent() + + + private static long figureWindowStartTime( int timeWindowMinutes ){ + // Given a window size, calculate what the start-timestamp would be. + + if( timeWindowMinutes <= 0 ){ + // This just means that there is no window... + return 0; + } + long unixTimeNow = System.currentTimeMillis(); + long windowInMillis = timeWindowMinutes * 60L * 1000; + + long startTimeStamp = unixTimeNow - windowInMillis; + + return startTimeStamp; + } // End of figureWindowStartTime() + + +} diff --git a/aai-core/src/main/java/org/onap/aai/dbgen/GenTester.java b/aai-core/src/main/java/org/onap/aai/dbgen/GenTester.java new file mode 100644 index 00000000..7b9eb2fc --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/dbgen/GenTester.java @@ -0,0 +1,144 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.dbgen; + +import com.att.eelf.configuration.Configuration; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.thinkaurelius.titan.core.TitanGraph; +import com.thinkaurelius.titan.core.schema.TitanManagement; +import org.onap.aai.dbmap.AAIGraph; +import org.onap.aai.logging.ErrorLogHelper; +import org.onap.aai.util.AAIConfig; +import org.onap.aai.util.AAIConstants; + +import java.util.Properties; + + +public class GenTester { + + private static EELFLogger LOGGER; + + /** + * The main method. + * + * @param args the arguments + */ + public static void main(String[] args) { + + TitanGraph graph = null; + + // Set the logging file properties to be used by EELFManager + Properties props = System.getProperties(); + props.setProperty(Configuration.PROPERTY_LOGGING_FILE_NAME, AAIConstants.AAI_CREATE_DB_SCHEMA_LOGBACK_PROPS); + props.setProperty(Configuration.PROPERTY_LOGGING_FILE_PATH, AAIConstants.AAI_HOME_ETC_APP_PROPERTIES); + LOGGER = EELFManager.getInstance().getLogger(GenTester.class); + boolean addDefaultCR = true; + + try { + AAIConfig.init(); + if (args != null && args.length > 0 ){ + if( "genDbRulesOnly".equals(args[0]) ){ + ErrorLogHelper.logError("AAI_3100", + " This option is no longer supported. What was in DbRules is now derived from the OXM files. "); + return; + } + else if ( "GEN_DB_WITH_NO_SCHEMA".equals(args[0]) ){ + // Note this is done to create an empty DB with no Schema so that + // an HBase copyTable can be used to set up a copy of the db. + String imsg = " ---- NOTE --- about to load a graph without doing any schema processing (takes a little while) -------- "; + System.out.println(imsg); + LOGGER.info(imsg); + graph = AAIGraph.getInstance().getGraph(); + + if( graph == null ){ + ErrorLogHelper.logError("AAI_5102", "Error creating Titan graph."); + return; + } + else { + String amsg = "Successfully loaded a Titan graph without doing any schema work. "; + System.out.println(amsg); + LOGGER.auditEvent(amsg); + return; + } + } else if ("GEN_DB_WITH_NO_DEFAULT_CR".equals(args[0])) { + addDefaultCR = false; + } + else { + ErrorLogHelper.logError("AAI_3000", "Unrecognized argument passed to GenTester.java: [" + args[0] + "]. "); + + String emsg = "Unrecognized argument passed to GenTester.java: [" + args[0] + "]. "; + System.out.println(emsg); + LOGGER.error(emsg); + + emsg = "Either pass no argument for normal processing, or use 'GEN_DB_WITH_NO_SCHEMA'."; + System.out.println(emsg); + LOGGER.error(emsg); + + return; + } + } + + //AAIConfig.init(); + ErrorLogHelper.loadProperties(); + String imsg = " ---- NOTE --- about to open graph (takes a little while)--------;"; + System.out.println(imsg); + LOGGER.info(imsg); + graph = AAIGraph.getInstance().getGraph(); + + if( graph == null ){ + ErrorLogHelper.logError("AAI_5102", "Error creating Titan graph. "); + return; + } + + // Load the propertyKeys, indexes and edge-Labels into the DB + TitanManagement graphMgt = graph.openManagement(); + + imsg = "-- Loading new schema elements into Titan --"; + System.out.println(imsg); + LOGGER.info(imsg); + SchemaGenerator.loadSchemaIntoTitan( graph, graphMgt, addDefaultCR ); + + } catch(Exception ex) { + ErrorLogHelper.logError("AAI_4000", ex.getMessage()); + } + + + if( graph != null ){ + String imsg = "-- graph commit"; + System.out.println(imsg); + LOGGER.info(imsg); + graph.tx().commit(); + + imsg = "-- graph shutdown "; + System.out.println(imsg); + LOGGER.info(imsg); + graph.close(); + } + + LOGGER.auditEvent("-- all done, if program does not exit, please kill."); + System.exit(0); + } + +} + + 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 new file mode 100644 index 00000000..b71e7ba2 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/dbgen/PropertyLimitDesc.java @@ -0,0 +1,28 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.dbgen; + +public enum PropertyLimitDesc { + 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 new file mode 100644 index 00000000..132ad46a --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/dbgen/SchemaGenerator.java @@ -0,0 +1,194 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.dbgen; + + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Optional; +import java.util.Set; + +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.onap.aai.db.props.AAIProperties; +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.schema.enums.PropertyMetadata; +import org.onap.aai.serialization.db.EdgeRule; +import org.onap.aai.serialization.db.EdgeRules; +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 com.thinkaurelius.titan.core.Cardinality; +import com.thinkaurelius.titan.core.Multiplicity; +import com.thinkaurelius.titan.core.PropertyKey; +import com.thinkaurelius.titan.core.TitanGraph; +import com.thinkaurelius.titan.core.schema.TitanManagement; + + + +public class SchemaGenerator{ + + private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(SchemaGenerator.class); + private static boolean addDefaultCR = true; + + + /** + * Load schema into titan. + * + * @param graph the graph + * @param graphMgmt the graph mgmt + * @param addDefaultCloudRegion the add default cloud region + */ + public static void loadSchemaIntoTitan(final TitanGraph graph, final TitanManagement graphMgmt, boolean addDefaultCloudRegion) { + addDefaultCR = addDefaultCloudRegion; + loadSchemaIntoTitan(graph, graphMgmt); + } + + /** + * Load schema into titan. + * + * @param graph the graph + * @param graphMgmt the graph mgmt + */ + public static void loadSchemaIntoTitan(final TitanGraph graph, final TitanManagement graphMgmt) { + + try { + AAIConfig.init(); + } + catch (Exception ex){ + LOGGER.error(" ERROR - Could not run AAIConfig.init(). ", ex); + System.out.println(" ERROR - Could not run AAIConfig.init(). "); + System.exit(1); + } + + // NOTE - Titan 0.5.3 doesn't keep a list of legal node Labels. + // They are only used when a vertex is actually being created. Titan 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 edges = null; + Set labels = new HashSet<>(); + + edges = EdgeRules.getInstance().getAllRules(); + for (EdgeRule rule : edges.values()) { + labels.add(rule.getLabel()); + } + + for( String label: labels){ + if( graphMgmt.containsRelationType(label) ) { + String dmsg = " EdgeLabel [" + label + "] already existed. "; + System.out.println(dmsg); + LOGGER.debug(dmsg); + } else { + String dmsg = "Making EdgeLabel: [" + label + "]"; + System.out.println(dmsg); + LOGGER.debug(dmsg); + graphMgmt.makeEdgeLabel(label).multiplicity(Multiplicity.valueOf("MULTI")).make(); + } + } + + Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, AAIProperties.LATEST); + Map objs = loader.getAllObjects(); + Map seenProps = new HashMap<>(); + + for (Introspector obj : objs.values()) { + for (String propName : obj.getProperties()) { + String dbPropName = propName; + Optional alias = obj.getPropertyMetadata(propName, PropertyMetadata.DB_ALIAS); + if (alias.isPresent()) { + dbPropName = alias.get(); + } + if( graphMgmt.containsRelationType(propName) ){ + String dmsg = " PropertyKey [" + propName + "] already existed in the DB. "; + System.out.println(dmsg); + 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 + "]"; + System.out.println(imsg); + 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. "; + System.out.println(dmsg); + LOGGER.debug(dmsg); + } else { + if( obj.getIndexedProperties().contains(propName) ){ + if( obj.getUniqueProperties().contains(propName) ){ + imsg = "Add Unique index for PropertyKey: [" + dbPropName + "]"; + System.out.println(imsg); + LOGGER.info(imsg); + graphMgmt.buildIndex(dbPropName,Vertex.class).addKey(propK).unique().buildCompositeIndex(); + } else { + imsg = "Add index for PropertyKey: [" + dbPropName + "]"; + System.out.println(imsg); + LOGGER.info(imsg); + graphMgmt.buildIndex(dbPropName,Vertex.class).addKey(propK).buildCompositeIndex(); + } + } else { + imsg = "No index added for PropertyKey: [" + dbPropName + "]"; + System.out.println(imsg); + LOGGER.info(imsg); + } + } + } + } + } + } + + String imsg = "-- About to call graphMgmt commit"; + System.out.println(imsg); + LOGGER.info(imsg); + + graphMgmt.commit(); + }// End of loadSchemaIntoTitan() + +} + + 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 new file mode 100644 index 00000000..e62e8e7e --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/dbmap/AAIGraph.java @@ -0,0 +1,197 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.dbmap; + +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +import org.apache.commons.lang.exception.ExceptionUtils; +import org.apache.tinkerpop.gremlin.structure.Graph; +import org.apache.tinkerpop.gremlin.structure.io.IoCore; +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 com.thinkaurelius.titan.core.TitanFactory; +import com.thinkaurelius.titan.core.TitanGraph; +import com.thinkaurelius.titan.core.schema.TitanManagement; + +/** + * Database Mapping class which acts as the middle man between the REST + * interface objects and Titan DB objects. This class provides methods to commit + * the objects received on the REST interface into the Titan graph database as + * vertices and edges. Transactions are also managed here by using a TitanGraph + * object to load, commit/rollback and shutdown for each request. The data model + * rules such as keys/required properties are handled by calling DBMeth methods + * which are driven by a specification file in json. + * + + */ +public class AAIGraph { + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(AAIGraph.class); + protected static final String COMPONENT = "aaidbmap"; + protected Map graphs = new HashMap<>(); + private final String REALTIME_DB = "realtime"; + private final String CACHED_DB = "cached"; + + + + /** + * Instantiates a new AAI graph. + */ + private AAIGraph() { + try { + String rtConfig = System.getProperty("realtime.db.config"); + String cachedConfig = System.getProperty("cached.db.config"); + if (rtConfig == null) { + rtConfig = AAIConstants.REALTIME_DB_CONFIG; + } + if (cachedConfig == null) { + cachedConfig = AAIConstants.CACHED_DB_CONFIG; + } + this.loadGraph(REALTIME_DB, rtConfig); + this.loadGraph(CACHED_DB, cachedConfig); + } catch (Exception e) { + throw new RuntimeException("Failed to instantiate graphs", e); + } + } + + private static class Helper { + private static final AAIGraph INSTANCE = new AAIGraph(); + } + + /** + * Gets the single instance of AAIGraph. + * + * @return single instance of AAIGraph + */ + public static AAIGraph getInstance() { + return Helper.INSTANCE; + } + + private void loadGraph(String name, String configPath) throws AAIException { + // Graph being opened by TitanFactory is being placed in hashmap to be used later + // These graphs shouldn't be closed until the application shutdown + TitanGraph graph = TitanFactory.open(configPath); + try (InputStream is = new FileInputStream(configPath)) { + + Properties graphProps = new Properties(); + graphProps.load(is); + + if ("inmemory".equals(graphProps.get("storage.backend"))) { + // Load the propertyKeys, indexes and edge-Labels into the DB + loadSchema(graph); + loadSnapShotToInMemoryGraph(graph, graphProps); + } + + if (graph == null) { + throw new AAIException("AAI_5102"); + } + + graphs.put(name, graph); + } catch (FileNotFoundException fnfe) { + throw new AAIException("AAI_4001"); + } catch (IOException e) { + throw new AAIException("AAI_4002"); + } + } + + private void loadSnapShotToInMemoryGraph(TitanGraph graph, Properties graphProps) { + if (logger.isDebugEnabled()) { + logger.debug("Load Snapshot to InMemory Graph"); + } + if (graphProps.containsKey("load.snapshot.file")) { + String value = graphProps.getProperty("load.snapshot.file"); + if ("true".equals(value)) { + try (Graph transaction = graph.newTransaction()) { + String location = System.getProperty("snapshot.location"); + logAndPrint(logger, "Loading snapshot to inmemory graph."); + transaction.io(IoCore.graphson()).readGraph(location); + 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" + + ExceptionUtils.getFullStackTrace(e)); + System.exit(0); + } + } + } + } + + private void loadSchema(TitanGraph graph) { + // Load the propertyKeys, indexes and edge-Labels into the DB + TitanManagement graphMgt = graph.openManagement(); + + System.out.println("-- loading schema into Titan"); + SchemaGenerator.loadSchemaIntoTitan( graph, graphMgt ); + } + + /** + * Graph shutdown. + */ + public void graphShutdown() { + graphs.get(REALTIME_DB).close(); + } + + /** + * Gets the graph. + * + * @return the graph + */ + public TitanGraph getGraph() { + return graphs.get(REALTIME_DB); + } + + public void graphShutdown(DBConnectionType connectionType) { + + graphs.get(this.getGraphName(connectionType)).close(); + } + + public TitanGraph getGraph(DBConnectionType connectionType) { + return graphs.get(this.getGraphName(connectionType)); + } + + private String getGraphName(DBConnectionType connectionType) { + String graphName = ""; + if (DBConnectionType.CACHED.equals(connectionType)) { + graphName = this.CACHED_DB; + } 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/DBConnectionType.java b/aai-core/src/main/java/org/onap/aai/dbmap/DBConnectionType.java new file mode 100644 index 00000000..6095c86c --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/dbmap/DBConnectionType.java @@ -0,0 +1,27 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.dbmap; + +public enum DBConnectionType { + REALTIME, + CACHED +} 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 new file mode 100644 index 00000000..d5389981 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/dmaap/AAIDmaapEventJMSConsumer.java @@ -0,0 +1,144 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.dmaap; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.sun.jersey.api.client.Client; +import com.sun.jersey.api.client.ClientResponse; +import com.sun.jersey.api.client.WebResource; +import org.apache.log4j.MDC; +import org.json.JSONException; +import org.json.JSONObject; +import org.onap.aai.logging.ErrorLogHelper; +import org.onap.aai.util.AAIConstants; +import org.onap.aai.logging.LoggingContext; +import org.onap.aai.logging.LoggingContext.LoggingField; +import org.onap.aai.logging.LoggingContext.StatusCode; + +import javax.jms.JMSException; +import javax.jms.Message; +import javax.jms.MessageListener; +import javax.jms.TextMessage; +import javax.ws.rs.core.MediaType; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.Properties; + +public class AAIDmaapEventJMSConsumer implements MessageListener { + + private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(AAIDmaapEventJMSConsumer.class); + + private Client httpClient; + + private Properties aaiEventProps; + private String aaiEventUrl = ""; + + public AAIDmaapEventJMSConsumer() throws org.apache.commons.configuration.ConfigurationException { + super(); + try(FileReader reader = new FileReader(new File(AAIConstants.AAI_EVENT_DMAAP_PROPS))) { + + if (this.httpClient == null) { + aaiEventProps = new Properties(); + aaiEventProps.load(reader); + + String host = aaiEventProps.getProperty("host"); + String topic = aaiEventProps.getProperty("topic"); + String protocol = aaiEventProps.getProperty("Protocol"); + + aaiEventUrl = protocol + "://" + host + "/events/" + topic; + httpClient = Client.create(); + } + + } catch (IOException e) { + ErrorLogHelper.logError("AAI_4000", "Error updating dmaap config file for aai event."); + LOGGER.error(e.getMessage(), e); + } + + } + + @Override + public void onMessage(Message message) { + + String jsmMessageTxt = ""; + String aaiEvent = ""; + String eventName = ""; + + if (message instanceof TextMessage) { + try { + jsmMessageTxt = ((TextMessage) message).getText(); + JSONObject jo = new JSONObject(jsmMessageTxt); + + if (jo.has("aaiEventPayload")) { + aaiEvent = jo.getJSONObject("aaiEventPayload").toString(); + } else { + return; + } + if (jo.getString("transId") != null) { + MDC.put("requestId", jo.getString("transId")); + } + if (jo.getString("fromAppId") != null) { + MDC.put("partnerName", jo.getString("fromAppId")); + } + if (jo.getString("event-topic") != null) { + eventName = jo.getString("event-topic"); + } + + LOGGER.info(eventName + "|" + aaiEvent); + if ("AAI-EVENT".equals(eventName)) { + this.sentWithHttp(this.httpClient, this.aaiEventUrl, aaiEvent); + } else { + LoggingContext.statusCode(StatusCode.ERROR); + LOGGER.error(eventName + "|Event Topic invalid."); + } + } catch (java.net.SocketException e) { + if (!e.getMessage().contains("Connection reset")) { + LOGGER.error("AAI_7304 Error reaching DMaaP to send event. " + aaiEvent, e); + } + } catch (IOException e) { + LOGGER.error("AAI_7304 Error reaching DMaaP to send event. " + aaiEvent, e); + } catch (JMSException | JSONException e) { + LOGGER.error("AAI_7350 Error parsing aaievent jsm message for sending to dmaap. " + jsmMessageTxt, e); + } catch (Exception e) { + LOGGER.error("AAI_7350 Error sending message to dmaap. " + jsmMessageTxt, e); + } + } + + } + + private boolean sentWithHttp(Client client, String url, String aaiEvent) throws IOException { + + WebResource webResource = client.resource(url); + + ClientResponse response = webResource + .accept(MediaType.APPLICATION_JSON) + .type(MediaType.APPLICATION_JSON) + .post(ClientResponse.class, aaiEvent); + + if (response.getStatus() != 200) { + LOGGER.info("Failed : HTTP error code : " + response.getStatus()); + return false; + } + return true; + } +} 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 new file mode 100644 index 00000000..d41f4768 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/dmaap/AAIDmaapEventJMSProducer.java @@ -0,0 +1,50 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.dmaap; + +import org.apache.activemq.ActiveMQConnectionFactory; +import org.apache.activemq.command.ActiveMQQueue; +import org.json.JSONObject; +import org.onap.aai.util.AAIConfig; +import org.springframework.jms.connection.CachingConnectionFactory; +import org.springframework.jms.core.JmsTemplate; + +public class AAIDmaapEventJMSProducer { + + private JmsTemplate jmsTemplate; + + public AAIDmaapEventJMSProducer() { + if(AAIConfig.get("aai.jms.enable", "true").equals("true")){ + this.jmsTemplate = new JmsTemplate(); + this.jmsTemplate.setConnectionFactory(new CachingConnectionFactory(new ActiveMQConnectionFactory("tcp://localhost:61447"))); + this.jmsTemplate.setDefaultDestination(new ActiveMQQueue("IN_QUEUE")); + } + } + + public void sendMessageToDefaultDestination(JSONObject finalJson) { + 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/domain/notificationEvent/NotificationEvent.java b/aai-core/src/main/java/org/onap/aai/domain/notificationEvent/NotificationEvent.java new file mode 100644 index 00000000..311b8574 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/domain/notificationEvent/NotificationEvent.java @@ -0,0 +1,565 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2016.01.06 at 05:38:00 PM EST +// + + +package org.onap.aai.domain.notificationEvent; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +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; + + +/** + *

Java class for anonymous complex type. + * + *

The following schema fragment specifies the expected content contained within this class. + * + *

+ * <complexType>
+ *   <complexContent>
+ *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *       <sequence>
+ *         <element name="cambria.partition" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *         <element name="event-header" minOccurs="0">
+ *           <complexType>
+ *             <complexContent>
+ *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *                 <sequence>
+ *                   <element name="id" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *                   <element name="timestamp" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *                   <element name="source-name" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *                   <element name="domain" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *                   <element name="sequence-number" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *                   <element name="severity" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *                   <element name="event-type" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *                   <element name="version" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *                   <element name="action" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *                   <element name="entity-type" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *                   <element name="top-entity-type" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *                   <element name="entity-link" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *                   <element name="status" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *                 </sequence>
+ *               </restriction>
+ *             </complexContent>
+ *           </complexType>
+ *         </element>
+ *         <any processContents='lax' namespace='##other' minOccurs="0"/>
+ *       </sequence>
+ *     </restriction>
+ *   </complexContent>
+ * </complexType>
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "", propOrder = { + "cambriaPartition", + "eventHeader", + "entity" +}) +@XmlRootElement(name = "NotificationEvent") +public class NotificationEvent { + + @XmlElement(name = "cambria.partition") + protected String cambriaPartition; + @XmlElement(name = "event-header") + protected NotificationEvent.EventHeader eventHeader; + @XmlAnyElement(lax = true) + protected Object entity; + + /** + * Gets the value of the eventHeader property. + * + * @return + * possible object is + * {@link NotificationEvent.EventHeader } + * + */ + public NotificationEvent.EventHeader getEventHeader() { + return eventHeader; + } + + /** + * Sets the value of the eventHeader property. + * + * @param value + * allowed object is + * {@link NotificationEvent.EventHeader } + * + */ + public void setEventHeader(NotificationEvent.EventHeader value) { + this.eventHeader = value; + } + + /** + * Gets the value of the any property. + * + * @return + * possible object is + * {@link Object } + * {@link Element } + * + */ + public Object getEntity() { + return entity; + } + + /** + * Sets the value of the any property. + * + * @param value + * allowed object is + * {@link Object } + * {@link Element } + * + */ + public void setEntity(Object value) { + this.entity = value; + } + + /** + * Gets the value of the cambriaPartition property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getCambriaPartition() { + return cambriaPartition; + } + + /** + * Sets the value of the cambriaPartition property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setCambriaPartition(String value) { + this.cambriaPartition = value; + } + + + /** + *

Java class for anonymous complex type. + * + *

The following schema fragment specifies the expected content contained within this class. + * + *

+     * <complexType>
+     *   <complexContent>
+     *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+     *       <sequence>
+     *         <element name="id" type="{http://www.w3.org/2001/XMLSchema}string"/>
+     *         <element name="timestamp" type="{http://www.w3.org/2001/XMLSchema}string"/>
+     *         <element name="source-name" type="{http://www.w3.org/2001/XMLSchema}string"/>
+     *         <element name="domain" type="{http://www.w3.org/2001/XMLSchema}string"/>
+     *         <element name="sequence-number" type="{http://www.w3.org/2001/XMLSchema}string"/>
+     *         <element name="severity" type="{http://www.w3.org/2001/XMLSchema}string"/>
+     *         <element name="event-type" type="{http://www.w3.org/2001/XMLSchema}string"/>
+     *         <element name="version" type="{http://www.w3.org/2001/XMLSchema}string"/>
+     *         <element name="action" type="{http://www.w3.org/2001/XMLSchema}string"/>
+     *         <element name="entity-type" type="{http://www.w3.org/2001/XMLSchema}string"/>
+     *         <element name="top-entity-type" type="{http://www.w3.org/2001/XMLSchema}string"/>
+     *         <element name="entity-link" type="{http://www.w3.org/2001/XMLSchema}string"/>
+     *         <element name="status" type="{http://www.w3.org/2001/XMLSchema}string"/>
+     *       </sequence>
+     *     </restriction>
+     *   </complexContent>
+     * </complexType>
+     * 
+ * + * + */ + @XmlAccessorType(XmlAccessType.FIELD) + @XmlType(name = "", propOrder = { + "id", + "timestamp", + "sourceName", + "domain", + "sequenceNumber", + "severity", + "eventType", + "version", + "action", + "entityType", + "topEntityType", + "entityLink", + "status" + }) + public static class EventHeader { + + @XmlElement(required = true) + protected String id; + @XmlElement(required = true) + protected String timestamp; + @XmlElement(name = "source-name", required = true) + protected String sourceName; + @XmlElement(required = true) + protected String domain; + @XmlElement(name = "sequence-number", required = true) + protected String sequenceNumber; + @XmlElement(required = true) + protected String severity; + @XmlElement(name = "event-type", required = true) + protected String eventType; + @XmlElement(required = true) + protected String version; + @XmlElement(required = true) + protected String action; + @XmlElement(name = "entity-type", required = true) + protected String entityType; + @XmlElement(name = "top-entity-type", required = true) + protected String topEntityType; + @XmlElement(name = "entity-link", required = true) + protected String entityLink; + @XmlElement(required = true) + protected String status; + + /** + * Gets the value of the id property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getId() { + return id; + } + + /** + * Sets the value of the id property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setId(String value) { + this.id = value; + } + + /** + * Gets the value of the timestamp property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getTimestamp() { + return timestamp; + } + + /** + * Sets the value of the timestamp property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setTimestamp(String value) { + this.timestamp = value; + } + + /** + * Gets the value of the sourceName property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getSourceName() { + return sourceName; + } + + /** + * Sets the value of the sourceName property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setSourceName(String value) { + this.sourceName = value; + } + + /** + * Gets the value of the domain property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getDomain() { + return domain; + } + + /** + * Sets the value of the domain property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setDomain(String value) { + this.domain = value; + } + + /** + * Gets the value of the sequenceNumber property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getSequenceNumber() { + return sequenceNumber; + } + + /** + * Sets the value of the sequenceNumber property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setSequenceNumber(String value) { + this.sequenceNumber = value; + } + + /** + * Gets the value of the severity property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getSeverity() { + return severity; + } + + /** + * Sets the value of the severity property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setSeverity(String value) { + this.severity = value; + } + + /** + * Gets the value of the eventType property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getEventType() { + return eventType; + } + + /** + * Sets the value of the eventType property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setEventType(String value) { + this.eventType = value; + } + + /** + * Gets the value of the version property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getVersion() { + return version; + } + + /** + * Sets the value of the version property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setVersion(String value) { + this.version = value; + } + + /** + * Gets the value of the action property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getAction() { + return action; + } + + /** + * Sets the value of the action property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setAction(String value) { + this.action = value; + } + + /** + * Gets the value of the entityType property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getEntityType() { + return entityType; + } + + /** + * Sets the value of the entityType property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setEntityType(String value) { + this.entityType = value; + } + + /** + * Gets the value of the topEntityType property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getTopEntityType() { + return topEntityType; + } + + /** + * Sets the value of the topEntityType property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setTopEntityType(String value) { + this.topEntityType = value; + } + + /** + * Gets the value of the entityLink property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getEntityLink() { + return entityLink; + } + + /** + * Sets the value of the entityLink property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setEntityLink(String value) { + this.entityLink = 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; + } + + } + +} 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 new file mode 100644 index 00000000..7c456fb2 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/domain/notificationEvent/ObjectFactory.java @@ -0,0 +1,78 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// 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. + *

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 + * + */ + public ObjectFactory() { + } + + /** + * Create an instance of {@link NotificationEvent }. + * + * @return the notification event + */ + public NotificationEvent createNotificationEvent() { + return new NotificationEvent(); + } + + /** + * Create an instance of {@link NotificationEvent.EventHeader } + * + * @return the event header + */ + public NotificationEvent.EventHeader createNotificationEventEventHeader() { + return new NotificationEvent.EventHeader(); + } + +} 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 new file mode 100644 index 00000000..03a31ff3 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/domain/responseMessage/AAIResponseMessage.java @@ -0,0 +1,126 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.domain.responseMessage; + +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; + +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "", propOrder = { + "aaiResponseMessageCode", + "aaiResponseMessageResourceType", + "aaiResponseMessageDescription", + "aaiResponseMessageData", +}) +@XmlRootElement(name = "aai-response-message", namespace = "http://org.onap.aai.inventory") +public class AAIResponseMessage { + + @XmlElement(name = "aai-response-message-code", required = true) + protected String aaiResponseMessageCode; + @XmlElement(name = "aai-response-message-resource-type") + protected String aaiResponseMessageResourceType; + @XmlElement(name = "aai-response-message-description") + 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; + } +} 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 new file mode 100644 index 00000000..5c33b93c --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/domain/responseMessage/AAIResponseMessageData.java @@ -0,0 +1,79 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.domain.responseMessage; + + +// +//This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 +//See http://java.sun.com/xml/jaxb +//Any modifications to this file will be lost upon recompilation of the source schema. +//Generated on: 2015.09.11 at 11:53:27 AM EDT +// + +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.XmlAnyElement; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "", propOrder = { + "aaiResponseMessageDatum", + "any" +}) +@XmlRootElement(name = "aai-response-message-data", namespace = "http://org.onap.aai.inventory") +public class AAIResponseMessageData { + + @XmlElement(name = "aai-response-message-datum") + protected List aaiResponseMessageDatum; + @XmlAnyElement(lax = true) + protected List any; + + /** + * Gets the AAI response message datum. + * + * @return the AAI response message datum + */ + public List getAAIResponseMessageDatum() { + if (aaiResponseMessageDatum == null) { + aaiResponseMessageDatum = new ArrayList(); + } + return this.aaiResponseMessageDatum; + } + + /** + * Gets the any. + * + * @return the any + */ + public List getAny() { + if (any == null) { + any = new ArrayList(); + } + return this.any; + } + +} 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 new file mode 100644 index 00000000..3830ce7f --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/domain/responseMessage/AAIResponseMessageDatum.java @@ -0,0 +1,82 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.domain.responseMessage; + +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; + +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "", propOrder = { + "aaiResponseMessageDatumKey", + "aaiResponseMessageDatumValue", + +}) + +@XmlRootElement(name = "aai-response-message-datum", namespace = "http://org.onap.aai.inventory") +public class AAIResponseMessageDatum { + + @XmlElement(name = "aai-response-message-datum-key", required = true) + 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; + } + + +} 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 new file mode 100644 index 00000000..7e5fb686 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/domain/responseMessage/AAIResponseMessages.java @@ -0,0 +1,119 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.domain.responseMessage; + + +// +//This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 +//See http://java.sun.com/xml/jaxb +//Any modifications to this file will be lost upon recompilation of the source schema. +//Generated on: 2015.09.11 at 11:53:27 AM EDT +// + +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.XmlAnyElement; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + +/** + *

Java class for anonymous complex type. + * + *

The following schema fragment specifies the expected content contained within this class. + * + *

+ * <complexType>
+ *   <complexContent>
+ *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *       <sequence>
+ *         <element name="flavor" maxOccurs="unbounded" minOccurs="0">
+ *           <complexType>
+ *             <complexContent>
+ *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *                 <sequence>
+ *                   <element name="flavor-id" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *                   <element name="flavor-name" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ *                   <element name="flavor-vcpus" type="{http://www.w3.org/2001/XMLSchema}short" minOccurs="0"/>
+ *                   <element name="flavor-ram" type="{http://www.w3.org/2001/XMLSchema}short" minOccurs="0"/>
+ *                   <element name="flavor-disk" type="{http://www.w3.org/2001/XMLSchema}short" minOccurs="0"/>
+ *                   <element name="flavor-ephemeral" type="{http://www.w3.org/2001/XMLSchema}short" minOccurs="0"/>
+ *                   <element name="flavor-swap" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ *                   <element name="flavor-is-public" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
+ *                   <element name="flavor-selflink" type="{urn:ietf:params:xml:ns:yang:ietf-inet-types}uri" minOccurs="0"/>
+ *                   <element name="flavor-disabled" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
+ *                   <any processContents='lax' namespace='##other' maxOccurs="unbounded" minOccurs="0"/>
+ *                   <element ref="{http://org.onap.aai.inventory/v3}relationship-list" minOccurs="0"/>
+ *                 </sequence>
+ *               </restriction>
+ *             </complexContent>
+ *           </complexType>
+ *         </element>
+ *         <any processContents='lax' namespace='##other' maxOccurs="unbounded" minOccurs="0"/>
+ *       </sequence>
+ *     </restriction>
+ *   </complexContent>
+ * </complexType>
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@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; + @XmlAnyElement(lax = true) + protected List any; + + /** + * Gets the AAI response message. + * + * @return the AAI response message + */ + public List getAAIResponseMessage() { + if (aaiResponseMessage == null) { + aaiResponseMessage = new ArrayList(); + } + return this.aaiResponseMessage; + } + + /** + * Gets the any. + * + * @return the any + */ + public List getAny() { + if (any == null) { + any = new ArrayList(); + } + 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 new file mode 100644 index 00000000..43e98422 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/domain/responseMessage/package-info.java @@ -0,0 +1,33 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 +// See http://java.sun.com/xml/jaxb +// 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) +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 new file mode 100644 index 00000000..dd937095 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/domain/restPolicyException/Fault.java @@ -0,0 +1,383 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// 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; + + +/** + *

Java class for anonymous complex type. + * + *

The following schema fragment specifies the expected content contained within this class. + * + *

+ * <complexType>
+ *   <complexContent>
+ *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *       <sequence>
+ *         <element name="requestError">
+ *           <complexType>
+ *             <complexContent>
+ *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *                 <sequence>
+ *                   <element name="policyException">
+ *                     <complexType>
+ *                       <complexContent>
+ *                         <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *                           <sequence>
+ *                             <element name="messageId" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *                             <element name="text" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *                             <element name="variables">
+ *                               <complexType>
+ *                                 <complexContent>
+ *                                   <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *                                     <sequence>
+ *                                       <element name="variable" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/>
+ *                                     </sequence>
+ *                                   </restriction>
+ *                                 </complexContent>
+ *                               </complexType>
+ *                             </element>
+ *                           </sequence>
+ *                         </restriction>
+ *                       </complexContent>
+ *                     </complexType>
+ *                   </element>
+ *                 </sequence>
+ *               </restriction>
+ *             </complexContent>
+ *           </complexType>
+ *         </element>
+ *       </sequence>
+ *     </restriction>
+ *   </complexContent>
+ * </complexType>
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "", propOrder = { + "requestError" +}) +@XmlRootElement(name = "Fault") +public class Fault { + + @XmlElement(required = true) + protected Fault.RequestError requestError; + + /** + * Gets the value of the requestError property. + * + * @return + * possible object is + * {@link Fault.RequestError } + * + */ + public Fault.RequestError getRequestError() { + return requestError; + } + + /** + * Sets the value of the requestError property. + * + * @param value + * allowed object is + * {@link Fault.RequestError } + * + */ + public void setRequestError(Fault.RequestError value) { + this.requestError = value; + } + + + /** + *

Java class for anonymous complex type. + * + *

The following schema fragment specifies the expected content contained within this class. + * + *

+     * <complexType>
+     *   <complexContent>
+     *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+     *       <sequence>
+     *         <element name="policyException">
+     *           <complexType>
+     *             <complexContent>
+     *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+     *                 <sequence>
+     *                   <element name="messageId" type="{http://www.w3.org/2001/XMLSchema}string"/>
+     *                   <element name="text" type="{http://www.w3.org/2001/XMLSchema}string"/>
+     *                   <element name="variables">
+     *                     <complexType>
+     *                       <complexContent>
+     *                         <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+     *                           <sequence>
+     *                             <element name="variable" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/>
+     *                           </sequence>
+     *                         </restriction>
+     *                       </complexContent>
+     *                     </complexType>
+     *                   </element>
+     *                 </sequence>
+     *               </restriction>
+     *             </complexContent>
+     *           </complexType>
+     *         </element>
+     *       </sequence>
+     *     </restriction>
+     *   </complexContent>
+     * </complexType>
+     * 
+ * + * + */ + @XmlAccessorType(XmlAccessType.FIELD) + @XmlType(name = "", propOrder = { + "policyException" + }) + public static class RequestError { + + @XmlElement(required = true) + protected Fault.RequestError.PolicyException policyException; + + /** + * Gets the value of the policyException property. + * + * @return + * possible object is + * {@link Fault.RequestError.PolicyException } + * + */ + public Fault.RequestError.PolicyException getPolicyException() { + return policyException; + } + + /** + * Sets the value of the policyException property. + * + * @param value + * allowed object is + * {@link Fault.RequestError.PolicyException } + * + */ + public void setPolicyException(Fault.RequestError.PolicyException value) { + this.policyException = value; + } + + + /** + *

Java class for anonymous complex type. + * + *

The following schema fragment specifies the expected content contained within this class. + * + *

+         * <complexType>
+         *   <complexContent>
+         *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+         *       <sequence>
+         *         <element name="messageId" type="{http://www.w3.org/2001/XMLSchema}string"/>
+         *         <element name="text" type="{http://www.w3.org/2001/XMLSchema}string"/>
+         *         <element name="variables">
+         *           <complexType>
+         *             <complexContent>
+         *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+         *                 <sequence>
+         *                   <element name="variable" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/>
+         *                 </sequence>
+         *               </restriction>
+         *             </complexContent>
+         *           </complexType>
+         *         </element>
+         *       </sequence>
+         *     </restriction>
+         *   </complexContent>
+         * </complexType>
+         * 
+ * + * + */ + @XmlAccessorType(XmlAccessType.FIELD) + @XmlType(name = "", propOrder = { + "messageId", + "text", + "variables" + }) + public static class PolicyException { + + @XmlElement(required = true) + protected String messageId; + @XmlElement(required = true) + protected String text; + @XmlElement(required = true) + protected Fault.RequestError.PolicyException.Variables variables; + + /** + * Gets the value of the messageId property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getMessageId() { + return messageId; + } + + /** + * Sets the value of the messageId property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setMessageId(String value) { + this.messageId = value; + } + + /** + * Gets the value of the text property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getText() { + return text; + } + + /** + * Sets the value of the text property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setText(String value) { + this.text = value; + } + + /** + * Gets the value of the variables property. + * + * @return + * possible object is + * {@link Fault.RequestError.PolicyException.Variables } + * + */ + public Fault.RequestError.PolicyException.Variables getVariables() { + return variables; + } + + /** + * Sets the value of the variables property. + * + * @param value + * allowed object is + * {@link Fault.RequestError.PolicyException.Variables } + * + */ + public void setVariables(Fault.RequestError.PolicyException.Variables value) { + this.variables = value; + } + + + /** + *

Java class for anonymous complex type. + * + *

The following schema fragment specifies the expected content contained within this class. + * + *

+             * <complexType>
+             *   <complexContent>
+             *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+             *       <sequence>
+             *         <element name="variable" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/>
+             *       </sequence>
+             *     </restriction>
+             *   </complexContent>
+             * </complexType>
+             * 
+ * + * + */ + @XmlAccessorType(XmlAccessType.FIELD) + @XmlType(name = "", propOrder = { + "variable" + }) + public static class Variables { + + protected List variable; + + /** + * Gets the value of the variable property. + * + *

+ * This accessor method returns a reference to the live list, + * not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. + * This is why there is not a set method for the variable property. + * + *

+ * For example, to add a new item, do as follows: + *

+                 *    getVariable().add(newItem);
+                 * 
+ * + * + *

+ * Objects of the following type(s) are allowed in the list + * {@link String } + * + * @return the variable + */ + public List getVariable() { + if (variable == null) { + variable = new ArrayList(); + } + return this.variable; + } + + } + + } + + } + +} 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 new file mode 100644 index 00000000..ba09fa78 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/domain/restPolicyException/ObjectFactory.java @@ -0,0 +1,96 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// 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. + *

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 + * + */ + public ObjectFactory() { + } + + /** + * Create an instance of {@link Fault }. + * + * @return the fault + */ + public Fault createFault() { + return new Fault(); + } + + /** + * Create an instance of {@link Fault.RequestError } + * + * @return the request error + */ + public Fault.RequestError createFaultRequestError() { + return new Fault.RequestError(); + } + + /** + * Create an instance of {@link Fault.RequestError.PolicyException } + * + * @return the policy exception + */ + public Fault.RequestError.PolicyException createFaultRequestErrorPolicyException() { + return new Fault.RequestError.PolicyException(); + } + + /** + * Create an instance of {@link Fault.RequestError.PolicyException.Variables } + * + * @return the variables + */ + public Fault.RequestError.PolicyException.Variables createFaultRequestErrorPolicyExceptionVariables() { + return new Fault.RequestError.PolicyException.Variables(); + } + +} 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 new file mode 100644 index 00000000..3f8d7641 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/domain/restPolicyException/PolicyException.java @@ -0,0 +1,135 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.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; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@Generated("org.jsonschema2pojo") +@JsonPropertyOrder({ + "messageId", + "text", + "variables" +}) +public class PolicyException { + + @JsonProperty("messageId") + private String messageId; + @JsonProperty("text") + private String text; + @JsonProperty("variables") + private List variables = new ArrayList(); + @JsonIgnore + private Map additionalProperties = new HashMap(); + + /** + * Gets the message id. + * + * @return The messageId + */ + @JsonProperty("messageId") + public String getMessageId() { + return messageId; + } + + /** + * Sets the message id. + * + * @param messageId The messageId + */ + @JsonProperty("messageId") + public void setMessageId(String messageId) { + this.messageId = messageId; + } + + /** + * Gets the text. + * + * @return The text + */ + @JsonProperty("text") + public String getText() { + return text; + } + + /** + * Sets the text. + * + * @param text The text + */ + @JsonProperty("text") + public void setText(String text) { + this.text = text; + } + + /** + * Gets the variables. + * + * @return The variables + */ + @JsonProperty("variables") + public List getVariables() { + return variables; + } + + /** + * Sets the variables. + * + * @param variables The variables + */ + @JsonProperty("variables") + public void setVariables(List variables) { + this.variables = variables; + } + + /** + * Gets the additional properties. + * + * @return the additional properties + */ + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + /** + * Sets the additional property. + * + * @param name the name + * @param value the value + */ + @JsonAnySetter + public void setAdditionalProperty(String name, Object value) { + this.additionalProperties.put(name, value); + } + +} 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 new file mode 100644 index 00000000..df4a86bf --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/domain/restPolicyException/RESTResponse.java @@ -0,0 +1,87 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.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; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@Generated("org.jsonschema2pojo") +@JsonPropertyOrder({ + "requestError" +}) +public class RESTResponse { + + @JsonProperty("requestError") + private RequestError requestError; + @JsonIgnore + private Map additionalProperties = new HashMap(); + + /** + * Gets the request error. + * + * @return The requestError + */ + @JsonProperty("requestError") + public RequestError getRequestError() { + return requestError; + } + + /** + * Sets the request error. + * + * @param requestError The requestError + */ + @JsonProperty("requestError") + public void setRequestError(RequestError requestError) { + this.requestError = requestError; + } + + /** + * Gets the additional properties. + * + * @return the additional properties + */ + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + /** + * Sets the additional property. + * + * @param name the name + * @param value the value + */ + @JsonAnySetter + public void setAdditionalProperty(String name, Object value) { + this.additionalProperties.put(name, value); + } + +} 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 new file mode 100644 index 00000000..e210341d --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/domain/restPolicyException/RequestError.java @@ -0,0 +1,88 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.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; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@Generated("org.jsonschema2pojo") +@JsonPropertyOrder({ + "policyException" +}) +public class RequestError { + + @JsonProperty("policyException") + private PolicyException policyException; + @JsonIgnore + private Map additionalProperties = new HashMap(); + + /** + * Gets the policy exception. + * + * @return The policyException + */ + @JsonProperty("policyException") + public PolicyException getPolicyException() { + return policyException; + } + + /** + * Sets the policy exception. + * + * @param policyException The policyException + */ + @JsonProperty("policyException") + public void setPolicyException(PolicyException policyException) { + this.policyException = policyException; + } + + /** + * Gets the additional properties. + * + * @return the additional properties + */ + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + /** + * Sets the additional property. + * + * @param name the name + * @param value the value + */ + @JsonAnySetter + public void setAdditionalProperty(String name, Object value) { + this.additionalProperties.put(name, value); + } + +} + 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 new file mode 100644 index 00000000..4ef131a1 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/domain/restResponseInfo/Info.java @@ -0,0 +1,386 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// 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; + + +/** + *

Java class for anonymous complex type. + * + *

The following schema fragment specifies the expected content contained within this class. + * + *

+ * <complexType>
+ *   <complexContent>
+ *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *       <sequence>
+ *         <element name="responseMessages" minOccurs="0">
+ *           <complexType>
+ *             <complexContent>
+ *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *                 <sequence>
+ *                   <element name="responseMessage" maxOccurs="unbounded" minOccurs="0">
+ *                     <complexType>
+ *                       <complexContent>
+ *                         <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *                           <sequence>
+ *                             <element name="messageId" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *                             <element name="text" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *                             <element name="variables">
+ *                               <complexType>
+ *                                 <complexContent>
+ *                                   <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *                                     <sequence>
+ *                                       <element name="variable" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/>
+ *                                     </sequence>
+ *                                   </restriction>
+ *                                 </complexContent>
+ *                               </complexType>
+ *                             </element>
+ *                           </sequence>
+ *                         </restriction>
+ *                       </complexContent>
+ *                     </complexType>
+ *                   </element>
+ *                 </sequence>
+ *               </restriction>
+ *             </complexContent>
+ *           </complexType>
+ *         </element>
+ *       </sequence>
+ *     </restriction>
+ *   </complexContent>
+ * </complexType>
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "", propOrder = { + "responseMessages" +}) +@XmlRootElement(name = "Info") +public class Info { + + protected Info.ResponseMessages responseMessages; + + /** + * Gets the value of the responseMessages property. + * + * @return + * possible object is + * {@link Info.ResponseMessages } + * + */ + public Info.ResponseMessages getResponseMessages() { + return responseMessages; + } + + /** + * Sets the value of the responseMessages property. + * + * @param value + * allowed object is + * {@link Info.ResponseMessages } + * + */ + public void setResponseMessages(Info.ResponseMessages value) { + this.responseMessages = value; + } + + + /** + *

Java class for anonymous complex type. + * + *

The following schema fragment specifies the expected content contained within this class. + * + *

+     * <complexType>
+     *   <complexContent>
+     *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+     *       <sequence>
+     *         <element name="responseMessage" maxOccurs="unbounded" minOccurs="0">
+     *           <complexType>
+     *             <complexContent>
+     *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+     *                 <sequence>
+     *                   <element name="messageId" type="{http://www.w3.org/2001/XMLSchema}string"/>
+     *                   <element name="text" type="{http://www.w3.org/2001/XMLSchema}string"/>
+     *                   <element name="variables">
+     *                     <complexType>
+     *                       <complexContent>
+     *                         <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+     *                           <sequence>
+     *                             <element name="variable" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/>
+     *                           </sequence>
+     *                         </restriction>
+     *                       </complexContent>
+     *                     </complexType>
+     *                   </element>
+     *                 </sequence>
+     *               </restriction>
+     *             </complexContent>
+     *           </complexType>
+     *         </element>
+     *       </sequence>
+     *     </restriction>
+     *   </complexContent>
+     * </complexType>
+     * 
+ * + * + */ + @XmlAccessorType(XmlAccessType.FIELD) + @XmlType(name = "", propOrder = { + "responseMessage" + }) + public static class ResponseMessages { + + protected List responseMessage; + + /** + * Gets the value of the responseMessage property. + * + *

+ * This accessor method returns a reference to the live list, + * not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. + * This is why there is not a set method for the responseMessage property. + * + *

+ * For example, to add a new item, do as follows: + *

+         *    getResponseMessage().add(newItem);
+         * 
+ * + * + *

+ * Objects of the following type(s) are allowed in the list + * {@link Info.ResponseMessages.ResponseMessage } + * + * @return the response message + */ + public List getResponseMessage() { + if (responseMessage == null) { + responseMessage = new ArrayList(); + } + return this.responseMessage; + } + + + /** + *

Java class for anonymous complex type. + * + *

The following schema fragment specifies the expected content contained within this class. + * + *

+         * <complexType>
+         *   <complexContent>
+         *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+         *       <sequence>
+         *         <element name="messageId" type="{http://www.w3.org/2001/XMLSchema}string"/>
+         *         <element name="text" type="{http://www.w3.org/2001/XMLSchema}string"/>
+         *         <element name="variables">
+         *           <complexType>
+         *             <complexContent>
+         *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+         *                 <sequence>
+         *                   <element name="variable" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/>
+         *                 </sequence>
+         *               </restriction>
+         *             </complexContent>
+         *           </complexType>
+         *         </element>
+         *       </sequence>
+         *     </restriction>
+         *   </complexContent>
+         * </complexType>
+         * 
+ * + * + */ + @XmlAccessorType(XmlAccessType.FIELD) + @XmlType(name = "", propOrder = { + "messageId", + "text", + "variables" + }) + public static class ResponseMessage { + + @XmlElement(required = true) + protected String messageId; + @XmlElement(required = true) + protected String text; + @XmlElement(required = true) + protected Info.ResponseMessages.ResponseMessage.Variables variables; + + /** + * Gets the value of the messageId property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getMessageId() { + return messageId; + } + + /** + * Sets the value of the messageId property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setMessageId(String value) { + this.messageId = value; + } + + /** + * Gets the value of the text property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getText() { + return text; + } + + /** + * Sets the value of the text property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setText(String value) { + this.text = value; + } + + /** + * Gets the value of the variables property. + * + * @return + * possible object is + * {@link Info.ResponseMessages.ResponseMessage.Variables } + * + */ + public Info.ResponseMessages.ResponseMessage.Variables getVariables() { + return variables; + } + + /** + * Sets the value of the variables property. + * + * @param value + * allowed object is + * {@link Info.ResponseMessages.ResponseMessage.Variables } + * + */ + public void setVariables(Info.ResponseMessages.ResponseMessage.Variables value) { + this.variables = value; + } + + + /** + *

Java class for anonymous complex type. + * + *

The following schema fragment specifies the expected content contained within this class. + * + *

+             * <complexType>
+             *   <complexContent>
+             *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+             *       <sequence>
+             *         <element name="variable" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/>
+             *       </sequence>
+             *     </restriction>
+             *   </complexContent>
+             * </complexType>
+             * 
+ * + * + */ + @XmlAccessorType(XmlAccessType.FIELD) + @XmlType(name = "", propOrder = { + "variable" + }) + public static class Variables { + + protected List variable; + + /** + * Gets the value of the variable property. + * + *

+ * This accessor method returns a reference to the live list, + * not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. + * This is why there is not a set method for the variable property. + * + *

+ * For example, to add a new item, do as follows: + *

+                 *    getVariable().add(newItem);
+                 * 
+ * + * + *

+ * Objects of the following type(s) are allowed in the list + * {@link String } + * + * @return the variable + */ + public List getVariable() { + if (variable == null) { + variable = new ArrayList(); + } + return this.variable; + } + + } + + } + + } + +} 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 new file mode 100644 index 00000000..461e7f0c --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/domain/restResponseInfo/ObjectFactory.java @@ -0,0 +1,96 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// 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. + *

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 + * + */ + public ObjectFactory() { + } + + /** + * Create an instance of {@link Info }. + * + * @return the info + */ + public Info createInfo() { + return new Info(); + } + + /** + * Create an instance of {@link Info.ResponseMessages } + * + * @return the response messages + */ + public Info.ResponseMessages createInfoResponseMessages() { + return new Info.ResponseMessages(); + } + + /** + * Create an instance of {@link Info.ResponseMessages.ResponseMessage } + * + * @return the response message + */ + public Info.ResponseMessages.ResponseMessage createInfoResponseMessagesResponseMessage() { + return new Info.ResponseMessages.ResponseMessage(); + } + + /** + * Create an instance of {@link Info.ResponseMessages.ResponseMessage.Variables } + * + * @return the variables + */ + public Info.ResponseMessages.ResponseMessage.Variables createInfoResponseMessagesResponseMessageVariables() { + return new Info.ResponseMessages.ResponseMessage.Variables(); + } + +} 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 new file mode 100644 index 00000000..2032cc5c --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/domain/restServiceException/Fault.java @@ -0,0 +1,383 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// 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; + + +/** + *

Java class for anonymous complex type. + * + *

The following schema fragment specifies the expected content contained within this class. + * + *

+ * <complexType>
+ *   <complexContent>
+ *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *       <sequence>
+ *         <element name="requestError">
+ *           <complexType>
+ *             <complexContent>
+ *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *                 <sequence>
+ *                   <element name="serviceException">
+ *                     <complexType>
+ *                       <complexContent>
+ *                         <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *                           <sequence>
+ *                             <element name="messageId" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *                             <element name="text" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *                             <element name="variables">
+ *                               <complexType>
+ *                                 <complexContent>
+ *                                   <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *                                     <sequence>
+ *                                       <element name="variable" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/>
+ *                                     </sequence>
+ *                                   </restriction>
+ *                                 </complexContent>
+ *                               </complexType>
+ *                             </element>
+ *                           </sequence>
+ *                         </restriction>
+ *                       </complexContent>
+ *                     </complexType>
+ *                   </element>
+ *                 </sequence>
+ *               </restriction>
+ *             </complexContent>
+ *           </complexType>
+ *         </element>
+ *       </sequence>
+ *     </restriction>
+ *   </complexContent>
+ * </complexType>
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "", propOrder = { + "requestError" +}) +@XmlRootElement(name = "Fault") +public class Fault { + + @XmlElement(required = true) + protected Fault.RequestError requestError; + + /** + * Gets the value of the requestError property. + * + * @return + * possible object is + * {@link Fault.RequestError } + * + */ + public Fault.RequestError getRequestError() { + return requestError; + } + + /** + * Sets the value of the requestError property. + * + * @param value + * allowed object is + * {@link Fault.RequestError } + * + */ + public void setRequestError(Fault.RequestError value) { + this.requestError = value; + } + + + /** + *

Java class for anonymous complex type. + * + *

The following schema fragment specifies the expected content contained within this class. + * + *

+     * <complexType>
+     *   <complexContent>
+     *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+     *       <sequence>
+     *         <element name="serviceException">
+     *           <complexType>
+     *             <complexContent>
+     *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+     *                 <sequence>
+     *                   <element name="messageId" type="{http://www.w3.org/2001/XMLSchema}string"/>
+     *                   <element name="text" type="{http://www.w3.org/2001/XMLSchema}string"/>
+     *                   <element name="variables">
+     *                     <complexType>
+     *                       <complexContent>
+     *                         <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+     *                           <sequence>
+     *                             <element name="variable" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/>
+     *                           </sequence>
+     *                         </restriction>
+     *                       </complexContent>
+     *                     </complexType>
+     *                   </element>
+     *                 </sequence>
+     *               </restriction>
+     *             </complexContent>
+     *           </complexType>
+     *         </element>
+     *       </sequence>
+     *     </restriction>
+     *   </complexContent>
+     * </complexType>
+     * 
+ * + * + */ + @XmlAccessorType(XmlAccessType.FIELD) + @XmlType(name = "", propOrder = { + "serviceException" + }) + public static class RequestError { + + @XmlElement(required = true) + protected Fault.RequestError.ServiceException serviceException; + + /** + * Gets the value of the serviceException property. + * + * @return + * possible object is + * {@link Fault.RequestError.ServiceException } + * + */ + public Fault.RequestError.ServiceException getServiceException() { + return serviceException; + } + + /** + * Sets the value of the serviceException property. + * + * @param value + * allowed object is + * {@link Fault.RequestError.ServiceException } + * + */ + public void setServiceException(Fault.RequestError.ServiceException value) { + this.serviceException = value; + } + + + /** + *

Java class for anonymous complex type. + * + *

The following schema fragment specifies the expected content contained within this class. + * + *

+         * <complexType>
+         *   <complexContent>
+         *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+         *       <sequence>
+         *         <element name="messageId" type="{http://www.w3.org/2001/XMLSchema}string"/>
+         *         <element name="text" type="{http://www.w3.org/2001/XMLSchema}string"/>
+         *         <element name="variables">
+         *           <complexType>
+         *             <complexContent>
+         *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+         *                 <sequence>
+         *                   <element name="variable" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/>
+         *                 </sequence>
+         *               </restriction>
+         *             </complexContent>
+         *           </complexType>
+         *         </element>
+         *       </sequence>
+         *     </restriction>
+         *   </complexContent>
+         * </complexType>
+         * 
+ * + * + */ + @XmlAccessorType(XmlAccessType.FIELD) + @XmlType(name = "", propOrder = { + "messageId", + "text", + "variables" + }) + public static class ServiceException { + + @XmlElement(required = true) + protected String messageId; + @XmlElement(required = true) + protected String text; + @XmlElement(required = true) + protected Fault.RequestError.ServiceException.Variables variables; + + /** + * Gets the value of the messageId property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getMessageId() { + return messageId; + } + + /** + * Sets the value of the messageId property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setMessageId(String value) { + this.messageId = value; + } + + /** + * Gets the value of the text property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getText() { + return text; + } + + /** + * Sets the value of the text property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setText(String value) { + this.text = value; + } + + /** + * Gets the value of the variables property. + * + * @return + * possible object is + * {@link Fault.RequestError.ServiceException.Variables } + * + */ + public Fault.RequestError.ServiceException.Variables getVariables() { + return variables; + } + + /** + * Sets the value of the variables property. + * + * @param value + * allowed object is + * {@link Fault.RequestError.ServiceException.Variables } + * + */ + public void setVariables(Fault.RequestError.ServiceException.Variables value) { + this.variables = value; + } + + + /** + *

Java class for anonymous complex type. + * + *

The following schema fragment specifies the expected content contained within this class. + * + *

+             * <complexType>
+             *   <complexContent>
+             *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+             *       <sequence>
+             *         <element name="variable" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/>
+             *       </sequence>
+             *     </restriction>
+             *   </complexContent>
+             * </complexType>
+             * 
+ * + * + */ + @XmlAccessorType(XmlAccessType.FIELD) + @XmlType(name = "", propOrder = { + "variable" + }) + public static class Variables { + + protected List variable; + + /** + * Gets the value of the variable property. + * + *

+ * This accessor method returns a reference to the live list, + * not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. + * This is why there is not a set method for the variable property. + * + *

+ * For example, to add a new item, do as follows: + *

+                 *    getVariable().add(newItem);
+                 * 
+ * + * + *

+ * Objects of the following type(s) are allowed in the list + * {@link String } + * + * @return the variable + */ + public List getVariable() { + if (variable == null) { + variable = new ArrayList(); + } + return this.variable; + } + + } + + } + + } + +} 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 new file mode 100644 index 00000000..6aef298c --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/domain/restServiceException/ObjectFactory.java @@ -0,0 +1,96 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// 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. + *

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 + * + */ + public ObjectFactory() { + } + + /** + * Create an instance of {@link Fault }. + * + * @return the fault + */ + public Fault createFault() { + return new Fault(); + } + + /** + * Create an instance of {@link Fault.RequestError } + * + * @return the request error + */ + public Fault.RequestError createFaultRequestError() { + return new Fault.RequestError(); + } + + /** + * Create an instance of {@link Fault.RequestError.ServiceException } + * + * @return the service exception + */ + public Fault.RequestError.ServiceException createFaultRequestErrorServiceException() { + return new Fault.RequestError.ServiceException(); + } + + /** + * Create an instance of {@link Fault.RequestError.ServiceException.Variables } + * + * @return the variables + */ + public Fault.RequestError.ServiceException.Variables createFaultRequestErrorServiceExceptionVariables() { + return new Fault.RequestError.ServiceException.Variables(); + } + +} 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 new file mode 100644 index 00000000..c571fd1c --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/domain/restServiceException/RESTResponse.java @@ -0,0 +1,87 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.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; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@Generated("org.jsonschema2pojo") +@JsonPropertyOrder({ + "requestError" +}) +public class RESTResponse { + + @JsonProperty("requestError") + private RequestError requestError; + @JsonIgnore + private Map additionalProperties = new HashMap(); + + /** + * Gets the request error. + * + * @return The requestError + */ + @JsonProperty("requestError") + public RequestError getRequestError() { + return requestError; + } + + /** + * Sets the request error. + * + * @param requestError The requestError + */ + @JsonProperty("requestError") + public void setRequestError(RequestError requestError) { + this.requestError = requestError; + } + + /** + * Gets the additional properties. + * + * @return the additional properties + */ + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + /** + * Sets the additional property. + * + * @param name the name + * @param value the value + */ + @JsonAnySetter + public void setAdditionalProperty(String name, Object value) { + this.additionalProperties.put(name, value); + } + +} 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 new file mode 100644 index 00000000..00b59839 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/domain/restServiceException/RequestError.java @@ -0,0 +1,87 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.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; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@Generated("org.jsonschema2pojo") +@JsonPropertyOrder({ + "serviceException" +}) +public class RequestError { + + @JsonProperty("serviceException") + private ServiceException serviceException; + @JsonIgnore + private Map additionalProperties = new HashMap(); + + /** + * Gets the service exception. + * + * @return The serviceException + */ + @JsonProperty("serviceException") + public ServiceException getServiceException() { + return serviceException; + } + + /** + * Sets the service exception. + * + * @param serviceException The serviceException + */ + @JsonProperty("serviceException") + public void setServiceException(ServiceException serviceException) { + this.serviceException = serviceException; + } + + /** + * Gets the additional properties. + * + * @return the additional properties + */ + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + /** + * Sets the additional property. + * + * @param name the name + * @param value the value + */ + @JsonAnySetter + public void setAdditionalProperty(String name, Object value) { + this.additionalProperties.put(name, value); + } + +} 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 new file mode 100644 index 00000000..0b392a03 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/domain/restServiceException/ServiceException.java @@ -0,0 +1,135 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.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; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@Generated("org.jsonschema2pojo") +@JsonPropertyOrder({ + "messageId", + "text", + "variables" +}) +public class ServiceException { + + @JsonProperty("messageId") + private String messageId; + @JsonProperty("text") + private String text; + @JsonProperty("variables") + private List variables = new ArrayList(); + @JsonIgnore + private Map additionalProperties = new HashMap(); + + /** + * Gets the message id. + * + * @return The messageId + */ + @JsonProperty("messageId") + public String getMessageId() { + return messageId; + } + + /** + * Sets the message id. + * + * @param messageId The messageId + */ + @JsonProperty("messageId") + public void setMessageId(String messageId) { + this.messageId = messageId; + } + + /** + * Gets the text. + * + * @return The text + */ + @JsonProperty("text") + public String getText() { + return text; + } + + /** + * Sets the text. + * + * @param text The text + */ + @JsonProperty("text") + public void setText(String text) { + this.text = text; + } + + /** + * Gets the variables. + * + * @return The variables + */ + @JsonProperty("variables") + public List getVariables() { + return variables; + } + + /** + * Sets the variables. + * + * @param variables The variables + */ + @JsonProperty("variables") + public void setVariables(List variables) { + this.variables = variables; + } + + /** + * Gets the additional properties. + * + * @return the additional properties + */ + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + /** + * Sets the additional property. + * + * @param name the name + * @param value the value + */ + @JsonAnySetter + public void setAdditionalProperty(String name, Object value) { + this.additionalProperties.put(name, value); + } + +} 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 new file mode 100644 index 00000000..cbd39c3f --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/domain/translog/TransactionLogEntries.java @@ -0,0 +1,132 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2015.03.20 at 09:46:47 AM CDT +// + + +package org.onap.aai.domain.translog; + +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.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + + +/** + *

Java class for anonymous complex type. + * + *

The following schema fragment specifies the expected content contained within this class. + * + *

+ * <complexType>
+ *   <complexContent>
+ *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *       <sequence>
+ *         <element name="update" minOccurs="0">
+ *           <complexType>
+ *             <complexContent>
+ *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *                 <sequence>
+ *                   <element name="update-node-type" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *                   <element name="update-node-key" maxOccurs="unbounded" minOccurs="0">
+ *                     <complexType>
+ *                       <complexContent>
+ *                         <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *                           <sequence>
+ *                             <element name="key-name" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *                             <element name="key-value" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *                             <any processContents='lax' namespace='##other' maxOccurs="unbounded" minOccurs="0"/>
+ *                           </sequence>
+ *                         </restriction>
+ *                       </complexContent>
+ *                     </complexType>
+ *                   </element>
+ *                   <element name="action" maxOccurs="unbounded" minOccurs="0">
+ *                     <complexType>
+ *                       <complexContent>
+ *                         <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *                           <sequence>
+ *                             <element name="action-type" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *                             <element name="action-data" maxOccurs="unbounded" minOccurs="0">
+ *                               <complexType>
+ *                                 <complexContent>
+ *                                   <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *                                     <sequence>
+ *                                       <element name="property-name" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *                                       <element name="property-value" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *                                       <any processContents='lax' namespace='##other' maxOccurs="unbounded" minOccurs="0"/>
+ *                                     </sequence>
+ *                                   </restriction>
+ *                                 </complexContent>
+ *                               </complexType>
+ *                             </element>
+ *                             <any processContents='lax' namespace='##other' maxOccurs="unbounded" minOccurs="0"/>
+ *                           </sequence>
+ *                         </restriction>
+ *                       </complexContent>
+ *                     </complexType>
+ *                   </element>
+ *                   <any processContents='lax' namespace='##other' maxOccurs="unbounded" minOccurs="0"/>
+ *                 </sequence>
+ *               </restriction>
+ *             </complexContent>
+ *           </complexType>
+ *         </element>
+ *         <any processContents='lax' namespace='##other' maxOccurs="unbounded" minOccurs="0"/>
+ *       </sequence>
+ *     </restriction>
+ *   </complexContent>
+ * </complexType>
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "", propOrder = { + "transactionLogEntries" +}) +@XmlRootElement(name = "transaction-log-entries", namespace = "http://org.onap.aai.inventory") +public class TransactionLogEntries { + + protected List transactionLogEntries; + + /** + * Gets the transaction log entries. + * + * @return the transaction log entries + */ + public List getTransactionLogEntries() { + if (transactionLogEntries == null) { + transactionLogEntries = new ArrayList(); + } + 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 new file mode 100644 index 00000000..37905a4e --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/domain/translog/TransactionLogEntry.java @@ -0,0 +1,439 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.domain.translog; + +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; + +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" +}) +@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; + } + + +} 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 new file mode 100644 index 00000000..349013b7 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/exceptions/AAIException.java @@ -0,0 +1,147 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.exceptions; + +import java.util.Collection; +import java.util.LinkedList; + +import org.onap.aai.logging.ErrorLogHelper; +import org.onap.aai.logging.ErrorObject; +import org.onap.aai.logging.ErrorObjectNotFoundException; + +public class AAIException extends Exception { + + public static final String DEFAULT_EXCEPTION_CODE = "AAI_4000"; + private static final long serialVersionUID = 1L; + + private final String code; + private final ErrorObject errorObject; + private final Collection templateVars; + + /** + * Instantiates a new AAI exception. + */ + public AAIException() { + super(); + this.code = DEFAULT_EXCEPTION_CODE; + this.templateVars = new LinkedList (); + + try { + this.errorObject = ErrorLogHelper.getErrorObject(getCode()); + } catch (ErrorObjectNotFoundException e) { + throw new RuntimeException("Failed to instantiate AAIException with code=" + getCode() + + " - update error.properties before using this exception code"); + } + } + + /** + * Instantiates a new AAI exception. + * + * @param code the code + */ + public AAIException(String code) { + super(); + + this.code = code; + this.templateVars = new LinkedList (); + + try { + this.errorObject = ErrorLogHelper.getErrorObject(getCode()); + } catch (ErrorObjectNotFoundException e) { + throw new RuntimeException("Failed to instantiate AAIException with code=" + getCode() + + " - update error.properties before using this exception code"); + } + } + + /** + * Instantiates a new AAI exception. + * + * @param code the code + * @param details the details + */ + public AAIException(String code, String details) { + super(details); + + this.code = code; + this.templateVars = new LinkedList (); + + try { + this.errorObject = ErrorLogHelper.getErrorObject(getCode()); + } catch (ErrorObjectNotFoundException e) { + throw new RuntimeException("Failed to instantiate AAIException with code=" + getCode() + + " - update error.properties before using this exception code"); + } + } + + /** + * Instantiates a new AAI exception. + * + * @param code the code + * @param cause the cause + */ + public AAIException(String code, Throwable cause) { + super(cause); + + this.code = code; + this.templateVars = new LinkedList (); + + try { + this.errorObject = ErrorLogHelper.getErrorObject(getCode()); + } catch (ErrorObjectNotFoundException e) { + throw new RuntimeException("Failed to instantiate AAIException with code=" + getCode() + + " - update error.properties before using this exception code"); + } + } + + /** + * Instantiates a new AAI exception. + * + * @param code the code + * @param cause the cause + * @param details the details + */ + public AAIException(String code, Throwable cause, String details) { + super(details, cause); + + this.code = code; + this.templateVars = new LinkedList (); + + try { + this.errorObject = ErrorLogHelper.getErrorObject(getCode()); + } catch (ErrorObjectNotFoundException e) { + throw new RuntimeException("Failed to instantiate AAIException with code=" + getCode() + + " - update error.properties before using this exception code"); + } + } + + public String getCode() { + return code; + } + + public ErrorObject getErrorObject() { + return errorObject; + } + + public Collection getTemplateVars() { + return templateVars; + } +} 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 new file mode 100644 index 00000000..992c6983 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/exceptions/AAIExceptionWithInfo.java @@ -0,0 +1,135 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.exceptions; + +import java.util.HashMap; + +public class AAIExceptionWithInfo extends AAIException { + + HashMap infoHash; + String info; + + /** + * Instantiates a new AAI exception with info. + * + * @param infoHash the info hash + * @param info the info + */ + public AAIExceptionWithInfo(HashMap 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 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 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 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 infoHash, String info) { + super(code, cause, details); + setInfoHash(infoHash); + setInfo(info); + } + + /** + * Gets the info hash. + * + * @return the info hash + */ + public HashMap getInfoHash() { + return infoHash; + } + + /** + * Sets the info hash. + * + * @param infoHash the info hash + */ + public void setInfoHash(HashMap infoHash) { + this.infoHash = infoHash; + } + + /** + * 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; + } + +} 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 new file mode 100644 index 00000000..3d7969ed --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/extensions/AAIExtensionMap.java @@ -0,0 +1,826 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.extensions; + +import org.apache.tinkerpop.gremlin.structure.Graph; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext; +import org.onap.aai.domain.responseMessage.AAIResponseMessages; +import org.onap.aai.introspection.Loader; +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 (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 | com.thinkaurelius.titan.core.TitanGraph (RW) + // ----------------------------------------------------------------------- + // objectFromResponse | Object + // ----------------------------------------------------------------------- + // precheckAddedList | java.util.HashMap + // ----------------------------------------------------------------------- + // precheckResponseMessages | org.onap.aai.extensions.AAIResponseMessages + // ======================================================================= + + private String message; + private ArrayList 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 lookupHashMap; + private HashMap> precheckAddedList; + private AAIResponseMessages precheckResponseMessages; + private HashMap topology; + private HashMap 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 _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 getTemplateVars() { + if (this.templateVars == null) { + this.templateVars = new ArrayList(); + } + 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 getLookupHashMap() { + if (this.lookupHashMap == null) { + this.lookupHashMap = new HashMap(); + } + return this.lookupHashMap; + } + + /** + * Sets the lookup hash map. + * + * @param lookupHashMap the lookup hash map + */ + public void setLookupHashMap(HashMap lookupHashMap) { + this.lookupHashMap = lookupHashMap; + } + + /** + * Gets the precheck added list. + * + * @return the precheck added list + */ + public HashMap> getPrecheckAddedList() { + if (this.precheckAddedList == null) { + this.precheckAddedList = new HashMap>(); + } + return precheckAddedList; + } + + /** + * Sets the precheck added list. + * + * @param precheckAddedList the precheck added list + */ + public void setPrecheckAddedList(HashMap> 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 getTopology() { + if (this.topology == null) { + this.topology = new HashMap(); + } + return topology; + } + + /** + * Gets the vertex cache. + * + * @return the vertex cache + */ + public HashMap getVertexCache() { + if (this.vertexCache == null) { + this.vertexCache = new HashMap(); + } + 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 new file mode 100644 index 00000000..2ec30561 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/extensions/ExtensionController.java @@ -0,0 +1,146 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.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; + +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); + } + } +} 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 new file mode 100644 index 00000000..98b0dc44 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/ingestModel/CreateWidgetModels.java @@ -0,0 +1,145 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.ingestModel; + +import java.io.File; +import java.io.PrintWriter; +import java.util.ArrayList; +import java.util.List; +import java.util.Map.Entry; +import java.util.UUID; + +import javax.xml.transform.stream.StreamSource; + +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.introspection.Version; +import org.onap.aai.util.AAIConfig; +import org.onap.aai.util.AAIConstants; + +/** + * 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); + } + + + Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.valueOf(_apiVersion)); + + // iterate the collection of resources + + ArrayList processedWidgets = new ArrayList(); + for (Entry 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; + } + 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 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 new file mode 100644 index 00000000..f6609bff --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/introspection/Introspector.java @@ -0,0 +1,618 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.introspection; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.google.common.base.CaseFormat; +import org.apache.commons.lang.ClassUtils; +import org.eclipse.persistence.exceptions.DynamicException; +import org.onap.aai.introspection.exceptions.AAIUnknownObjectException; +import org.onap.aai.logging.ErrorLogHelper; +import org.onap.aai.restcore.MediaType; +import org.onap.aai.schema.enums.ObjectMetadata; +import org.onap.aai.schema.enums.PropertyMetadata; +import org.onap.aai.workarounds.NamingExceptions; + +import java.io.UnsupportedEncodingException; +import java.lang.reflect.InvocationTargetException; +import java.util.*; + +public abstract class Introspector implements Cloneable { + + 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 uniqueProperties = null; + private Set indexedProperties = null; + private Set allKeys = null; + protected Introspector(Object obj) { + } + + public abstract boolean hasProperty(String name); + + protected String convertPropertyName (String name) { + return CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, 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 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) { + + } + } + + 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) { + + } + } + if (value != null) { + return IntrospectorFactory.newInstance(this.getModelType(), value); + } else { + //no value + return null; + } + + } + + public List getWrappedListValue(String name) { + String convertedName = convertPropertyName(name); + Object value = null; + List 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) { + + } + } + + List valueList = (List)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 castValueAccordingToSchema(String name, List objs) { + List 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) throws IllegalArgumentException { + 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 getProperties(); + + public Set getProperties(PropertyPredicate p) { + final Set temp = new LinkedHashSet<>(); + this.getProperties().stream().filter(item -> { + return p.test(this, item); + }).forEach(item -> { + temp.add(item); + }); + final Set result = Collections.unmodifiableSet(temp); + + return result; + + } + /** + * + * @return a list of the required properties on the object + */ + public abstract Set getRequiredProperties(); + /** + * + * @return a list of the properties that can be used to query the object in the db + */ + public abstract Set getKeys(); + /** + * + * @return a list of the all key properties for this object + */ + public Set getAllKeys() { + Set result = null; + if (this.allKeys == null) { + Set 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 getIndexedProperties() { + Set result = null; + + if (this.indexedProperties == null) { + result = new LinkedHashSet<>(); + Set 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 getUniqueProperties() { + Set 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 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 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)", 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 clone(); + + 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 getPropertyMetadata(String propName); + public Optional getPropertyMetadata(String propName, PropertyMetadata metadataName) { + final String resultValue = this.getPropertyMetadata(propName).getOrDefault(metadataName, ""); + Optional result = Optional.empty(); + + if (!resultValue.isEmpty()) { + result = Optional.of(resultValue); + } + return result; + + } + + public abstract Version 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 new file mode 100644 index 00000000..801905dd --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/introspection/IntrospectorFactory.java @@ -0,0 +1,66 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.introspection; + +public class IntrospectorFactory { + + /** + * New instance. + * + * @param type the type + * @param o the o + * @param llBuilder the ll builder + * @return the introspector + */ + public static Introspector newInstance(ModelType type, Object o) { + + if (type.equals(ModelType.MOXY)) { + return new MoxyStrategy(o); + } else if (type.equals(ModelType.POJO)) { + return new PojoStrategy(o); + } else if (type.equals(ModelType.JSON)) { + return new JSONStrategy(o); + } else { + throw new IllegalArgumentException("Unknown class type: " + type); + } + + } + + /** + * New instance. + * + * @param type the type + * @param o the o + * @param namedType the named type + * @param llBuilder the ll builder + * @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 new file mode 100644 index 00000000..09dcec64 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/introspection/IntrospectorWalker.java @@ -0,0 +1,194 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.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 java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; + +public class IntrospectorWalker { + + private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(IntrospectorWalker.class); + + private Wanderer w = null; + private Set blacklist = null; + private boolean preventCycles = false; + private final PropertyPredicate 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 p) { + this.w = w; + this.blacklist = new HashSet<>(); + this.propVisibility = p; + } + + + /** + * Sets the blacklist. + * + * @param list the new blacklist + */ + public void setBlacklist(List 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 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 visited) throws AAIException { + boolean stopRecursion = false; + Set 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 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 listReference = obj.getValue(prop); + boolean isComplexType = obj.isComplexGenericType(prop); + if (isComplexType) { + List 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)", 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)", 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)", 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 new file mode 100644 index 00000000..db8a7d06 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/introspection/JSONStrategy.java @@ -0,0 +1,360 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.introspection; + +import org.json.simple.JSONObject; +import org.onap.aai.schema.enums.ObjectMetadata; +import org.onap.aai.schema.enums.PropertyMetadata; + +import java.io.UnsupportedEncodingException; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; + +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 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 getProperties() { + Set result = json.keySet(); + return result; + } + + @Override + public Set getRequiredProperties() { + //unknowable + + return this.getProperties(); + } + + @Override + public Set getKeys() { + //unknowable + return this.getProperties(); + } + + @Override + public Set 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 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 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 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 Version 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 new file mode 100644 index 00000000..579a4644 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/introspection/Loader.java @@ -0,0 +1,113 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.introspection; + +import org.onap.aai.introspection.exceptions.AAIUnknownObjectException; +import org.onap.aai.introspection.exceptions.AAIUnmarshallingException; +import org.onap.aai.restcore.MediaType; + +import java.util.Map; + +public abstract class Loader { + + private final Version version; + private final ModelType modelType; + + /** + * Instantiates a new loader. + * + * @param version the version + * @param modelType the model type + * @param llBuilder the ll builder + */ + public Loader (Version version, ModelType modelType) { + this.version = version; + this.modelType = modelType; + } + + /** + * Process. + * + * @param version the version + */ + protected abstract void process(Version version); + + /** + * Object from name. + * + * @param name the name + * @return the object + * @throws AAIUnknownObjectException + */ + public abstract Object objectFromName(String name) throws AAIUnknownObjectException; + + /** + * 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 + * @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 version. + * + * @return the version + */ + public Version getVersion() { + return this.version; + } + + public abstract Map getAllObjects(); +} 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 new file mode 100644 index 00000000..63f95539 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/introspection/LoaderFactory.java @@ -0,0 +1,45 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.introspection; + +public class LoaderFactory { + + /** + * Creates a new Loader object. + * + * @param type the type + * @param version the version + * @param llBuilder the ll builder + * @return the loader + */ + public static Loader createLoaderForVersion(ModelType type, Version version) { + + if (type.equals(ModelType.MOXY)) { + return new MoxyLoader(version); + } else if (type.equals(ModelType.POJO)) { + return new PojoLoader(version); + } + + return null; + + } +} 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 new file mode 100644 index 00000000..7f0251f4 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/introspection/MarshallerProperties.java @@ -0,0 +1,140 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.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); + } + } +} diff --git a/aai-core/src/main/java/org/onap/aai/introspection/ModelInjestor.java b/aai-core/src/main/java/org/onap/aai/introspection/ModelInjestor.java new file mode 100644 index 00000000..4cdfc634 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/introspection/ModelInjestor.java @@ -0,0 +1,174 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.introspection; + +import org.eclipse.persistence.dynamic.DynamicType; +import org.eclipse.persistence.jaxb.JAXBContextProperties; +import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext; +import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContextFactory; +import org.onap.aai.util.AAIConstants; + +import javax.xml.bind.JAXBException; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.InputStream; +import java.util.HashMap; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class ModelInjestor { + + private Map versionContextMap = new HashMap<>(); + private static final Pattern classNamePattern = Pattern.compile("\\.(v\\d+)\\."); + private static final Pattern uriPattern = Pattern.compile("(v\\d+)\\/"); + + + /** + * Instantiates a new model injestor. + */ + private ModelInjestor() { + try { + injestModels(); + } catch (FileNotFoundException | JAXBException e) { + throw new RuntimeException(e); + } + } + + private static class Helper { + private static final ModelInjestor INSTANCE = new ModelInjestor(); + } + + /** + * Gets the single instance of ModelInjestor. + * + * @return single instance of ModelInjestor + */ + public synchronized static ModelInjestor getInstance() { + return Helper.INSTANCE; + } + + /** + * Injest models. + * + * @throws FileNotFoundException the file not found exception + * @throws JAXBException the JAXB exception + */ + private void injestModels() throws FileNotFoundException, JAXBException { + + for (Version version : Version.values()) { + this.injestModel(version); + } + } + + /** + * Injest model. + * + * @param version the version + * @throws JAXBException the JAXB exception + * @throws FileNotFoundException the file not found exception + */ + private void injestModel (Version version) throws JAXBException, FileNotFoundException { + String fileName = this.getOXMFileName(version); + InputStream iStream = new FileInputStream(new File(fileName)); + Map properties = new HashMap(); + properties.put(JAXBContextProperties.OXM_METADATA_SOURCE, iStream); + final DynamicJAXBContext jaxbContext = DynamicJAXBContextFactory.createContextFromOXM(this.getClass().getClassLoader(), properties); + versionContextMap.put(version, jaxbContext); + } + + /** + * Gets the version from class name. + * + * @param classname the classname + * @return the version from class name + */ + public Version getVersionFromClassName (String classname) { + Matcher m = classNamePattern.matcher(classname); + String version = "v2"; //for the OXM, only the v2 ones don't include a model name, hence this default + if (m.find()) { + version = m.group(1); + } + + return Version.valueOf(version); + } + + /** + * Gets the context for URI. + * + * @param uri the uri + * @return the context for URI + */ + public DynamicJAXBContext getContextForURI(String uri) { + DynamicJAXBContext result = null; + Matcher m = uriPattern.matcher(uri); + Version version = null; + if (m.find()) { + version = Version.valueOf(m.group(1)); + result = versionContextMap.get(version); + } + + return result; + } + + /** + * Gets the context for version. + * + * @param version the version + * @return the context for version + */ + public DynamicJAXBContext getContextForVersion(Version version) { + DynamicJAXBContext result = null; + + result = versionContextMap.get(version); + + + return result; + } + + /** + * Gets the dynamic type for class name. + * + * @param classname the classname + * @return the dynamic type for class name + */ + public DynamicType getDynamicTypeForClassName(String classname) { + DynamicType result = null; + DynamicJAXBContext context = null; + + Version version = this.getVersionFromClassName(classname); + + context = versionContextMap.get(version); + + if (context != null) { + result = context.getDynamicType(classname); + } + + return result; + } + + public String getOXMFileName(Version v) { + return AAIConstants.AAI_HOME_ETC_OXM + "aai_oxm_" + v.toString() + ".xml"; + } + +} 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 new file mode 100644 index 00000000..49d2c90e --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/introspection/ModelType.java @@ -0,0 +1,26 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.introspection; + +public enum ModelType { + 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 new file mode 100644 index 00000000..cf81349c --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/introspection/MoxyLoader.java @@ -0,0 +1,196 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.introspection; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.google.common.base.CaseFormat; +import com.google.common.collect.ImmutableMap; +import org.eclipse.persistence.dynamic.DynamicEntity; +import org.eclipse.persistence.jaxb.UnmarshallerProperties; +import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext; +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.exceptions.AAIUnknownObjectException; +import org.onap.aai.introspection.exceptions.AAIUnmarshallingException; +import org.onap.aai.logging.ErrorLogHelper; +import org.onap.aai.restcore.MediaType; +import org.onap.aai.workarounds.NamingExceptions; +import org.w3c.dom.Document; +import org.w3c.dom.NodeList; +import org.xml.sax.SAXException; + +import javax.xml.XMLConstants; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Unmarshaller; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.stream.StreamSource; +import java.io.IOException; +import java.io.StringReader; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +public class MoxyLoader extends Loader { + + private DynamicJAXBContext jaxbContext = null; + private EELFLogger LOGGER = EELFManager.getInstance().getLogger(MoxyLoader.class); + private Map allObjs = null; + + /** + * Instantiates a new moxy loader. + * + * @param version the version + * @param llBuilder the ll builder + */ + protected MoxyLoader(Version version) { + super(version, ModelType.MOXY); + process(version); + } + + /** + * {@inheritDoc} + * @throws AAIUnknownObjectException + */ + @Override + public Introspector introspectorFromName(String name) throws AAIUnknownObjectException { + + return IntrospectorFactory.newInstance(ModelType.MOXY, objectFromName(name)); + } + + /** + * {@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 (name.matches(".*[A-Z].*")) { + upperCamel = sanitizedName; + } else { + upperCamel = 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(Version version) { + ModelInjestor injestor = ModelInjestor.getInstance(); + jaxbContext = injestor.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 getAllObjects() { + if (this.allObjs != null) { + return allObjs; + } else { + ImmutableMap.Builder map = new ImmutableMap.Builder(); + Set 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()", e); + } + } + allObjs = map.build(); + return allObjs; + } + } + + private Set objectsInVersion() { + final Set result = new HashSet<>(); + + try { + final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); + final String fileName = ModelInjestor.getInstance().getOXMFileName(getVersion()); + + docFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); + + final DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); + final Document doc = docBuilder.parse(fileName); + final NodeList list = doc.getElementsByTagName("java-type"); + + for (int i = 0; i < list.getLength(); i++) { + result.add(list.item(i).getAttributes().getNamedItem("name").getNodeValue()); + } + } catch (ParserConfigurationException | SAXException | IOException e) { + LOGGER.warn("Exception while enumerating objects for API version " + getVersion() + " (returning partial results)", e); + } + + //result.remove("EdgePropNames"); + return result; + } + + 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 new file mode 100644 index 00000000..ce04fb7f --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/introspection/MoxyStrategy.java @@ -0,0 +1,386 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.introspection; + +import com.google.common.base.CaseFormat; +import com.google.common.base.Joiner; +import org.eclipse.persistence.descriptors.ClassDescriptor; +import org.eclipse.persistence.dynamic.DynamicEntity; +import org.eclipse.persistence.dynamic.DynamicType; +import org.eclipse.persistence.exceptions.DynamicException; +import org.eclipse.persistence.jaxb.UnmarshallerProperties; +import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext; +import org.eclipse.persistence.mappings.DatabaseMapping; +import org.eclipse.persistence.oxm.XMLField; +import org.eclipse.persistence.oxm.mappings.XMLCompositeCollectionMapping; +import org.eclipse.persistence.oxm.mappings.XMLCompositeDirectCollectionMapping; +import org.onap.aai.restcore.MediaType; +import org.onap.aai.schema.enums.ObjectMetadata; +import org.onap.aai.schema.enums.PropertyMetadata; +import org.springframework.web.util.UriUtils; + +import javax.xml.bind.JAXBException; +import javax.xml.bind.Marshaller; +import javax.xml.bind.Unmarshaller; +import javax.xml.transform.stream.StreamSource; +import java.io.StringReader; +import java.io.StringWriter; +import java.io.UnsupportedEncodingException; +import java.util.*; +import java.util.Map.Entry; + +public class MoxyStrategy extends Introspector { + + private DynamicEntity internalObject = null; + private DynamicType internalType = null; + private DynamicJAXBContext jaxbContext = null; + private ClassDescriptor cd = null; + private Marshaller marshaller = null; + private Unmarshaller unmarshaller = null; + private Version version = null; + private Set properties = null; + private Set keys = null; + private Set 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; + ModelInjestor injestor = ModelInjestor.getInstance(); + version = injestor.getVersionFromClassName(internalObject.getClass().getName()); + jaxbContext = injestor.getContextForVersion(version); + super.loader = LoaderFactory.createLoaderForVersion(getModelType(), version); + String simpleName = internalObject.getClass().getName(); + internalType = jaxbContext.getDynamicType(simpleName); + cd = internalType.getDescriptor(); + try { + marshaller = jaxbContext.createMarshaller(); + unmarshaller = jaxbContext.createUnmarshaller(); + } catch (JAXBException e) { + + } + + } + + private void init() { + isInitialized = true; + + Set props = new LinkedHashSet<>(); + for (String s : internalType.getPropertiesNames()) { + props.add(CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_HYPHEN, s)); + + } + props = Collections.unmodifiableSet(props); + this.properties = props; + + Set requiredProps = new LinkedHashSet<>(); + requiredProps = new LinkedHashSet<>(); + for (DatabaseMapping dm : cd.getMappings()) { + if (dm.getField() instanceof XMLField) { + XMLField x = (XMLField)dm.getField(); + if (x != null) { + if (x.isRequired()) { + requiredProps.add(this.removeXPathDescriptor(x.getName())); + } + } + } + } + requiredProps = Collections.unmodifiableSet(requiredProps); + this.requiredProperties = requiredProps; + + Set 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) throws IllegalArgumentException { + + internalObject.set(name, obj); + } + + @Override + public Set getProperties() { + + if(!isInitialized){ + init(); + } + + return this.properties; + + } + + @Override + public Set getRequiredProperties() { + + if(!isInitialized){ + init(); + } + + return this.requiredProperties; + } + + @Override + public Set getKeys() { + + if(!isInitialized){ + init(); + } + + return this.keys; + } + + @Override + public Map getPropertyMetadata(String prop) { + String propName = this.convertPropertyName(prop); + DatabaseMapping mapping = cd.getMappingForAttributeName(propName); + Map result = new HashMap<>(); + if (mapping != null) { + Set 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 = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, className); + + if (this.isContainer()) { + lowerHyphen = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN,this.getGenericTypeClass(this.getProperties().iterator().next()).getSimpleName()); + } + + return lowerHyphen; + } + + @Override + public String getName() { + String className = internalObject.getClass().getSimpleName(); + String lowerHyphen = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, className); + /* + if (this.isContainer()) { + lowerHyphen = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN,this.getGenericTypeClass(this.getProperties().get(0)).getSimpleName()); + }*/ + + + return lowerHyphen; + } + + @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 keys = null; + keys = this.getKeys(); + List results = new ArrayList<>(); + for (String key : keys) { + if (this.getType(key).toLowerCase().contains("long")) { + key = ((Long)this.getValue(key)).toString(); + } else { + key = (String)this.getValue(key); + } + key = UriUtils.encode(key, "UTF-8"); + + results.add(key); + } + + return Joiner.on("/").join(results); + } + + @Override + public String preProcessKey (String key) { + String result = ""; + //String trimmedRestURI = restURI.replaceAll("/[\\w\\-]+?/[\\w\\-]+?$", ""); + 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 { + 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) { + //e.printStackTrace(); + } + + return result.toString(); + } + + @Override + public Object clone() { + Object result = null; + try { + unmarshaller = jaxbContext.createUnmarshaller(); + + unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); + unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); + unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); + + result = unmarshaller.unmarshal(new StreamSource(new StringReader(this.marshal(true))), this.internalObject.getClass()).getValue(); + } catch (JAXBException e) { + // TODO Auto-generated catch block + //e.printStackTrace(); + } + result = IntrospectorFactory.newInstance(getModelType(), result); + return result; + } + @Override + public ModelType getModelType() { + return ModelType.MOXY; + } + + private String removeXPathDescriptor(String name) { + + return name.replaceAll("/text\\(\\)", ""); + } + + @Override + public String getMetadata(ObjectMetadata name) { + + return (String)cd.getProperty(name.toString()); + } + + @Override + public Version getVersion() { + + return this.version; + } +} diff --git a/aai-core/src/main/java/org/onap/aai/introspection/PojoInjestor.java b/aai-core/src/main/java/org/onap/aai/introspection/PojoInjestor.java new file mode 100644 index 00000000..5de9c748 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/introspection/PojoInjestor.java @@ -0,0 +1,68 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.introspection; + +import org.eclipse.persistence.jaxb.JAXBContextFactory; +import org.onap.aai.db.props.AAIProperties; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class PojoInjestor { + + private String POJO_CLASSPATH = "org.onap.aai.domain.yang"; + private final Pattern classNamePattern = Pattern.compile("\\.(v\\d+)\\."); + + public PojoInjestor() { + } + + public JAXBContext getContextForVersion(Version v) { + JAXBContext context = null; + try { + if (!v.equals(AAIProperties.LATEST)) { + POJO_CLASSPATH += "." + v; + } + context = JAXBContextFactory.createContext(POJO_CLASSPATH, this.getClass().getClassLoader()); + } catch (JAXBException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + return context; + } + public Version getVersion (String classname) { + Matcher m = classNamePattern.matcher(classname); + String version; + if (m.find()) { + version = m.group(1); + } else { + //only POJOs of old versions have the version number in their classnames + //so if we can't find a version, default to the latest + version = AAIProperties.LATEST.toString(); + } + + return Version.valueOf(version); + } + +} diff --git a/aai-core/src/main/java/org/onap/aai/introspection/PojoLoader.java b/aai-core/src/main/java/org/onap/aai/introspection/PojoLoader.java new file mode 100644 index 00000000..62a7dc0e --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/introspection/PojoLoader.java @@ -0,0 +1,138 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.introspection; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.google.common.base.CaseFormat; +import org.eclipse.persistence.jaxb.JAXBContextFactory; +import org.eclipse.persistence.jaxb.UnmarshallerProperties; +import org.onap.aai.db.props.AAIProperties; +import org.onap.aai.introspection.exceptions.AAIUnknownObjectException; +import org.onap.aai.introspection.exceptions.AAIUnmarshallingException; +import org.onap.aai.logging.ErrorLogHelper; +import org.onap.aai.restcore.MediaType; +import org.onap.aai.workarounds.NamingExceptions; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Unmarshaller; +import javax.xml.transform.stream.StreamSource; +import java.io.StringReader; +import java.util.Map; + +public class PojoLoader extends Loader { + + private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(PojoLoader.class); + private static final String POJO_BASE_PACKAGE_NAME = "org.onap.aai.domain.yang"; + + protected JAXBContext context; + private final String pojoPackageName; + + protected PojoLoader(Version version) { + super(version, ModelType.POJO); + + if (!version.equals(AAIProperties.LATEST)) { + pojoPackageName = POJO_BASE_PACKAGE_NAME + "." + version; + } else { + pojoPackageName = POJO_BASE_PACKAGE_NAME; + } + + try { + context = JAXBContextFactory.createContext(pojoPackageName, this.getClass().getClassLoader()); + } catch (JAXBException e) { + LOGGER.error("JAXBException while instantiation contect for PojoLoader", e); + } + } + + @Override + public Introspector introspectorFromName(String name) throws AAIUnknownObjectException { + return IntrospectorFactory.newInstance(ModelType.POJO, objectFromName(name)); + } + + @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 (sanitizedName.matches(".*[A-Z].*")) { + upperCamel = sanitizedName; + } else { + upperCamel = CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, sanitizedName); + } + + final String objectClassName; + + if (!upperCamel.contains(pojoPackageName)) { + objectClassName = pojoPackageName + "." + upperCamel; + } else { + objectClassName = upperCamel; + } + + try { + return Class.forName(objectClassName).newInstance(); + } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) { + throw new AAIUnknownObjectException("Unrecognized AAI object " + name); + } + } + + @Override + protected void process(Version version) { + LOGGER.warn("PojoLoader.process(Version) has not been implemented"); + } + + @Override + public Introspector unmarshal(String type, String json, MediaType mediaType) throws AAIUnmarshallingException { + + try { + final Unmarshaller unmarshaller = context.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 Object clazz = objectFromName(type); + final Object obj = unmarshaller.unmarshal(new StreamSource(new StringReader(json)), clazz.getClass()).getValue(); + + return IntrospectorFactory.newInstance(ModelType.POJO, obj); + } catch (JAXBException e) { + ErrorLogHelper.logError("AAI_4007", "Could not unmarshall: " + e.getMessage()); + throw new AAIUnmarshallingException("Could not unmarshall: " + e.getMessage()); + } catch (AAIUnknownObjectException e) { + throw new AAIUnmarshallingException("Could not unmarshall: " + e.getMessage(), e); + } + } + + @Override + public Map getAllObjects() { + //TODO + return null; + } + +} diff --git a/aai-core/src/main/java/org/onap/aai/introspection/PojoStrategy.java b/aai-core/src/main/java/org/onap/aai/introspection/PojoStrategy.java new file mode 100644 index 00000000..6e29729d --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/introspection/PojoStrategy.java @@ -0,0 +1,377 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.introspection; + +import com.google.common.base.CaseFormat; +import com.google.common.base.Joiner; +import com.google.common.collect.Multimap; +import org.eclipse.persistence.jaxb.UnmarshallerProperties; +import org.onap.aai.annotations.Metadata; +import org.onap.aai.logging.ErrorLogHelper; +import org.onap.aai.restcore.MediaType; +import org.onap.aai.schema.enums.ObjectMetadata; +import org.onap.aai.schema.enums.PropertyMetadata; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Marshaller; +import javax.xml.bind.Unmarshaller; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.transform.stream.StreamSource; +import java.io.StringReader; +import java.io.StringWriter; +import java.lang.reflect.*; +import java.util.*; + +public class PojoStrategy extends Introspector { + + private Object internalObject = null; + private PojoInjestor injestor = null; + private Multimap keyProps = null; + private Metadata classLevelMetadata = null; + private Version version; + private JAXBContext jaxbContext; + private Marshaller marshaller; + private Unmarshaller unmarshaller; + private Set properties = null; + private Set keys = null; + private Set requiredProperties = null; + + private boolean isInitialized = false; + + protected PojoStrategy(Object obj) { + super(obj); + className = PojoStrategy.class.getSimpleName(); + this.internalObject = obj; + injestor = new PojoInjestor(); + classLevelMetadata = obj.getClass().getAnnotation(Metadata.class); + + version = injestor.getVersion(obj.getClass().getName()); + jaxbContext = injestor.getContextForVersion(version); + super.loader = LoaderFactory.createLoaderForVersion(getModelType(), version); + try { + marshaller = jaxbContext.createMarshaller(); + unmarshaller = jaxbContext.createUnmarshaller(); + } catch (JAXBException e) { + + } + + } + + private void init() { + + isInitialized = true; + + Set properties = new LinkedHashSet<>(); + Set keys = new LinkedHashSet<>(); + Set required = new LinkedHashSet<>(); + + Field[] fields = this.internalObject.getClass().getDeclaredFields(); + + for (Field field : fields) { + if (!field.getName().equals("any")) { + properties.add(covertFieldToOutputFormat(field.getName())); + Metadata annotation = field.getAnnotation(Metadata.class); + XmlElement xmlAnnotation = field.getAnnotation(XmlElement.class); + if (annotation != null) { + if (annotation.isKey()) { + keys.add(covertFieldToOutputFormat(field.getName())); + } + } + if (xmlAnnotation != null) { + if (xmlAnnotation.required()) { + required.add(covertFieldToOutputFormat(field.getName())); + } + } + } + } + properties = Collections.unmodifiableSet(properties); + this.properties = properties; + + keys = Collections.unmodifiableSet(keys); + this.keys = keys; + + required = Collections.unmodifiableSet(required); + this.requiredProperties = required; + + } + private String covertFieldToOutputFormat(String propName) { + return CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_HYPHEN, propName); + } + + @Override + public boolean hasProperty(String name) { + //TODO + return true; + } + + @Override + /** + * Gets the value of the property via reflection + */ + public Object get(String name) { + String getMethodName = "get" + CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, name); + try { + return this.internalObject.getClass().getDeclaredMethod(getMethodName).invoke(this.internalObject); + } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { + return null; + } + } + + @Override + public void set(String name, Object value) { + String setMethodName = "set" + CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, name); + try { + this.internalObject.getClass().getDeclaredMethod(setMethodName, value.getClass()).invoke(this.internalObject, value); + } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { + ErrorLogHelper.logError("AAI_4017", "Error setting name/value pair on POJO: " + e.getMessage()); + } + } + + @Override + public Set getProperties() { + + if(!isInitialized){ + this.init(); + } + return this.properties; + } + + + @Override + public Set getRequiredProperties() { + + if(!isInitialized) { + this.init(); + } + return this.requiredProperties; + } + + @Override + public Set getKeys() { + + if(!isInitialized){ + this.init(); + } + return this.keys; + } + + public Class getClass(String name) { + + Field field = null; + try { + field = this.internalObject.getClass().getDeclaredField(CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, name)); + } catch (NoSuchFieldException | SecurityException e) { + + return null; + } + + return field.getType(); + } + + public Class getGenericTypeClass(String name) { + + try { + String getMethodName = "get" + CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, name); + Method method = internalObject.getClass().getDeclaredMethod(getMethodName); + Type t = method.getGenericReturnType(); + if(t instanceof ParameterizedType) { + ParameterizedType pt = (ParameterizedType)t; + return ((Class)pt.getActualTypeArguments()[0]); + } else { + return null; + } + + } catch (Exception e) { + return null; + } + } + + @Override + public String getJavaClassName() { + return internalObject.getClass().getName(); + } + + @Override + public Object getUnderlyingObject() { + return this.internalObject; + } + + @Override + public String getName() { + String className = internalObject.getClass().getSimpleName(); + + return CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, className); + } + + @Override + protected String findKey() { + Set keys = null; + keys = this.getKeys(); + List results = new ArrayList<>(); + for (String key : keys) { + if (this.getType(key).toLowerCase().contains("long")) { + key = ((Long)this.getValue(key)).toString(); + } else { + key = (String)this.getValue(key); + } + results.add(key); + } + + return Joiner.on("/").join(results); + } + + @Override + public String marshal(MarshallerProperties properties) { + StringWriter result = new StringWriter(); + try { + 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(Marshaller.JAXB_FORMATTED_OUTPUT, properties.getFormatted()); + marshaller.marshal(this.internalObject, result); + } catch (JAXBException e) { + //e.printStackTrace(); + } + + return result.toString(); + } + + @Override + public Object clone() { + Object result = null; + try { + unmarshaller = jaxbContext.createUnmarshaller(); + + unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); + unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); + unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); + + result = unmarshaller.unmarshal(new StreamSource(new StringReader(this.marshal(true))), this.internalObject.getClass()).getValue(); + } catch (JAXBException e) { + // TODO Auto-generated catch block + //e.printStackTrace(); + } + result = IntrospectorFactory.newInstance(getModelType(), result); + return result; + } + + @Override + public String preProcessKey (String key) { + String result = ""; + //String trimmedRestURI = restURI.replaceAll("/[\\w\\-]+?/[\\w\\-]+?$", ""); + String[] split = key.split("/"); + int i = 0; + for (i = split.length-1; i >= 0; i--) { + + if (keyProps.containsKey(split[i])) { + break; + + } + + } + result = Joiner.on("/").join(Arrays.copyOfRange(split, 0, i)); + + return result; + + } + + @Override + public ModelType getModelType() { + return ModelType.POJO; + } + + @Override + public String getChildName() { + String className = internalObject.getClass().getSimpleName(); + String lowerHyphen = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, className); + + if (this.isContainer()) { + lowerHyphen = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN,this.getGenericTypeClass(this.getProperties().iterator().next()).getSimpleName()); + } + + return lowerHyphen; + } + + @Override + public Map getPropertyMetadata(String prop) { + Field f; + Map result = new HashMap<>(); + try { + f = internalObject.getClass().getField(prop); + Metadata m = f.getAnnotation(Metadata.class); + if (m != null) { + Field[] fields = m.getClass().getFields(); + String fieldName; + for (Field field : fields) { + fieldName = field.getName(); + if (fieldName.equals("isAbstract")) { + fieldName = "abstract"; + } else if (fieldName.equals("extendsFrom")) { + fieldName = "extends"; + } + fieldName = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, fieldName); + result.put(PropertyMetadata.valueOf(fieldName), (String)field.get(m)); + } + } + } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) { + // TODO Auto-generated catch block + } + + return result; + } + + @Override + public String getObjectId() { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getMetadata(ObjectMetadata metadataName) { + String value = null; + String methodName; + if (ObjectMetadata.ABSTRACT.equals(metadataName)) { + methodName = "isAbstract"; + } else if (ObjectMetadata.EXTENDS.equals(metadataName)) { + methodName = "extendsFrom"; + } else { + methodName = metadataName.toString(); + } + + try { + value = (String)this.classLevelMetadata.getClass().getMethod(methodName).invoke(classLevelMetadata); + } catch (IllegalArgumentException | IllegalAccessException | SecurityException | InvocationTargetException | NoSuchMethodException e) { + //TODO + } + + return value; + } + + @Override + public Version getVersion() { + // TODO Auto-generated method stub + return null; + } +} 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 new file mode 100644 index 00000000..f4f666d9 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/introspection/PropertyPredicate.java @@ -0,0 +1,28 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.introspection; + +import java.util.function.BiPredicate; + +public interface PropertyPredicate extends 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 new file mode 100644 index 00000000..90edd5e9 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/introspection/PropertyPredicates.java @@ -0,0 +1,78 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.introspection; + +import org.onap.aai.schema.enums.PropertyMetadata; + +import java.util.Map; +import java.util.Set; + +public final class PropertyPredicates { + + private PropertyPredicates() { + + } + + public static PropertyPredicate includeInTestGeneration() { + return (obj, prop) -> { + final Map 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 isVisible() { + return (obj, prop) -> { + final Map map = obj.getPropertyMetadata(prop); + if (map.containsKey(PropertyMetadata.VISIBILITY)) { + return !Visibility.internal.equals(Visibility.valueOf(map.get(PropertyMetadata.VISIBILITY))); + } + return true; + }; + } + + public static PropertyPredicate includeInExamples() { + return (obj, prop) -> { + final Map 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 isIndexed() { + return (obj, prop) -> { + Set indexed = obj.getIndexedProperties(); + return indexed.contains(prop); + }; + } +} diff --git a/aai-core/src/main/java/org/onap/aai/introspection/Version.java b/aai-core/src/main/java/org/onap/aai/introspection/Version.java new file mode 100644 index 00000000..e51231a4 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/introspection/Version.java @@ -0,0 +1,37 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.introspection; + +public enum Version { + v8, + v9, + v10, + v11; + + public static boolean isLatest(Version v) { + return (Version.v11.equals(v)); //TODO update when we increment the version, or find a better way of doing this + } + + public static Version getLatest(){ + return Version.v11; //TODO update when we increment the version, or find a better way of doing this + } +} 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 new file mode 100644 index 00000000..4e5b6b76 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/introspection/Visibility.java @@ -0,0 +1,30 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.introspection; + +public enum Visibility { + + 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 new file mode 100644 index 00000000..156de4fd --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/introspection/Wanderer.java @@ -0,0 +1,84 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.introspection; + +import org.onap.aai.exceptions.AAIException; + +import java.util.List; + +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 list, List 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 new file mode 100644 index 00000000..6bc53553 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/introspection/exceptions/AAIUnknownObjectException.java @@ -0,0 +1,43 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.introspection.exceptions; + +import org.onap.aai.exceptions.AAIException; + +public class AAIUnknownObjectException extends AAIException { + + private static final long serialVersionUID = -504200228742133774L; + + public AAIUnknownObjectException() {} + + public AAIUnknownObjectException(String message) { + super("AAI_3000", message); + } + + public AAIUnknownObjectException(Throwable cause) { + super("AAI_3000", cause); + } + + 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 new file mode 100644 index 00000000..bf9c7a36 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/introspection/exceptions/AAIUnmarshallingException.java @@ -0,0 +1,43 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.introspection.exceptions; + +import org.onap.aai.exceptions.AAIException; + +public class AAIUnmarshallingException extends AAIException { + + private static final long serialVersionUID = -5615651557821878103L; + + public AAIUnmarshallingException() {} + + public AAIUnmarshallingException(String message) { + super("AAI_3000", message); + } + + public AAIUnmarshallingException(Throwable cause) { + super("AAI_3000",cause); + } + + 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 new file mode 100644 index 00000000..4d11c9ad --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/introspection/generator/CreateExample.java @@ -0,0 +1,167 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.introspection.generator; + +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.*; + +import java.security.SecureRandom; +import java.util.ArrayList; +import java.util.List; + +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 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 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 list, List 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 new file mode 100644 index 00000000..d002f068 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/introspection/sideeffect/DataCopy.java @@ -0,0 +1,90 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.introspection.sideeffect; + +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.Introspector; +import org.onap.aai.introspection.sideeffect.exceptions.AAIMissingRequiredPropertyException; +import org.onap.aai.introspection.sideeffect.exceptions.AAIMultiplePropertiesException; +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.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); + } + + @Override + protected void processURI(Optional completeUri, Entry entry) throws URISyntaxException, UnsupportedEncodingException, AAIException { + if (completeUri.isPresent()) { + URI uri = new URI(completeUri.get()); + MultivaluedMap map = URITools.getQueryMap(uri); + QueryParser uriQuery = dbEngine.getQueryBuilder(this.latestLoader).createQueryFromURI(uri, map); + List 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 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 new file mode 100644 index 00000000..20387205 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/introspection/sideeffect/DataLinkReader.java @@ -0,0 +1,98 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.introspection.sideeffect; + +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.onap.aai.db.props.AAIProperties; +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.Introspector; +import org.onap.aai.introspection.sideeffect.exceptions.AAIMissingRequiredPropertyException; +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.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; + } + + @Override + protected void processURI(Optional completeUri, Entry entry) + throws URISyntaxException, UnsupportedEncodingException, AAIException { + + if (completeUri.isPresent()) { + URI uri = new URI(completeUri.get()); + MultivaluedMap map = URITools.getQueryMap(uri); + QueryParser uriQuery = dbEngine.getQueryBuilder(this.latestLoader).createQueryFromURI(uri, map); + List results = uriQuery.getQueryBuilder().getVerticesByProperty(AAIProperties.LINKED, true).toList(); + if (results.size() == 1) { + if (results.get(0).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 findProperties(Introspector obj, String uriString) throws AAIMissingRequiredPropertyException { + + final Map 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 new file mode 100644 index 00000000..f98e07c4 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/introspection/sideeffect/DataLinkWriter.java @@ -0,0 +1,110 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.introspection.sideeffect; + +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.onap.aai.db.props.AAIProperties; +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.Introspector; +import org.onap.aai.introspection.sideeffect.exceptions.AAIMultiplePropertiesException; +import org.onap.aai.parsers.query.QueryParser; +import org.onap.aai.parsers.uri.URIToObject; +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.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); + } + + @Override + protected PropertyMetadata getPropertyMetadata() { + return PropertyMetadata.DATA_LINK; + } + + @Override + protected void processURI(Optional completeUri, Entry entry) + throws URISyntaxException, UnsupportedEncodingException, AAIException { + if (completeUri.isPresent()) { + URI uri = new URI(completeUri.get()); + MultivaluedMap map = URITools.getQueryMap(uri); + QueryParser uriQuery = dbEngine.getQueryBuilder(this.latestLoader).createQueryFromURI(uri, map); + List results = uriQuery.getQueryBuilder().toList(); + if (results.size() == 1) { + if (results.get(0).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 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); + } + + +} 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 new file mode 100644 index 00000000..08520608 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/introspection/sideeffect/SideEffect.java @@ -0,0 +1,129 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.introspection.sideeffect; + +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.onap.aai.db.props.AAIProperties; +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.introspection.ModelType; +import org.onap.aai.introspection.sideeffect.exceptions.AAIMissingRequiredPropertyException; +import org.onap.aai.schema.enums.PropertyMetadata; +import org.onap.aai.serialization.db.DBSerializer; +import org.onap.aai.serialization.engines.TransactionalGraphEngine; + +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("\\{(.*?)\\}"); + protected final Introspector obj; + protected final TransactionalGraphEngine dbEngine; + protected final DBSerializer serializer; + protected final Loader latestLoader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, AAIProperties.LATEST); + protected final Vertex self; + public SideEffect (Introspector obj, Vertex self, TransactionalGraphEngine dbEngine, DBSerializer serializer) { + this.obj = obj; + this.dbEngine = dbEngine; + this.serializer = serializer; + this.self = self; + } + + protected void execute() throws UnsupportedEncodingException, URISyntaxException, AAIException { + final Map properties = this.findPopertiesWithMetadata(obj, this.getPropertyMetadata()); + for (Entry entry : properties.entrySet()) { + Optional populatedUri = this.replaceTemplates(obj, entry.getValue()); + Optional completeUri = this.resolveRelativePath(populatedUri); + this.processURI(completeUri, entry); + } + } + + protected Map findPopertiesWithMetadata(Introspector obj, PropertyMetadata metadata) { + final Map result = new HashMap<>(); + for (String prop : obj.getProperties()) { + final Map map = obj.getPropertyMetadata(prop); + if (map.containsKey(metadata)) { + result.put(prop, map.get(metadata)); + } + } + return result; + } + + protected Map findProperties(Introspector obj, String uriString) throws AAIMissingRequiredPropertyException { + + final Map result = new HashMap<>(); + final Set 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; + } + + private Optional replaceTemplates(Introspector obj, String uriString) throws AAIMissingRequiredPropertyException { + String result = uriString; + final Map propMap = this.findProperties(obj, uriString); + if (propMap.isEmpty()) { + return Optional.empty(); + } + for (Entry entry : propMap.entrySet()) { + result = result.replaceAll("\\{" + entry.getKey() + "\\}", entry.getValue()); + } + //drop out wildcards if they exist + result = result.replaceFirst("/[^/]+?(?:/\\*)+", ""); + return Optional.of(result); + } + + private Optional resolveRelativePath(Optional 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 completeUri, Entry entry) throws URISyntaxException, UnsupportedEncodingException, AAIException; +} 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 new file mode 100644 index 00000000..0129b991 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/introspection/sideeffect/SideEffectRunner.java @@ -0,0 +1,100 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.introspection.sideeffect; + +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; +import java.net.URISyntaxException; +import java.util.LinkedHashSet; +import java.util.Set; + +public class SideEffectRunner { + + protected final TransactionalGraphEngine dbEngine; + protected final DBSerializer serializer; + protected final Set> 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 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> sideEffects; + + public Builder(final TransactionalGraphEngine dbEngine, final DBSerializer serializer) { + this.dbEngine = dbEngine; + this.serializer = serializer; + this.sideEffects = new LinkedHashSet<>(); + } + + public Builder addSideEffect(Class se) { + sideEffects.add(se); + return this; + } + + public Builder addSideEffects(Class... sideEffects) { + for (Class 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> 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 new file mode 100644 index 00000000..f73216c8 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/introspection/sideeffect/SideEffectRunnerHelper.java @@ -0,0 +1,86 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.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; + +import java.io.UnsupportedEncodingException; +import java.lang.reflect.InvocationTargetException; +import java.net.URISyntaxException; +import java.util.List; +import java.util.Set; + +class SideEffectRunnerHelper implements Wanderer { + + + protected final TransactionalGraphEngine dbEngine; + protected final DBSerializer serializer; + protected final Set> sideEffects; + protected SideEffectRunnerHelper(final TransactionalGraphEngine dbEngine, final DBSerializer serializer, final Set> sideEffects) { + this.dbEngine = dbEngine; + this.serializer = serializer; + this.sideEffects = sideEffects; + } + + private void runSideEffects(Introspector obj) throws AAIException { + for (Class 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 list, List 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 new file mode 100644 index 00000000..c159c808 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/introspection/sideeffect/exceptions/AAIMissingRequiredPropertyException.java @@ -0,0 +1,46 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.introspection.sideeffect.exceptions; + +import org.onap.aai.exceptions.AAIException; + +public class AAIMissingRequiredPropertyException extends AAIException { + + + private static final long serialVersionUID = -8907079650472014019L; + + public AAIMissingRequiredPropertyException() {} + + public AAIMissingRequiredPropertyException(String message) { + super("AAI_5107", message); + } + + public AAIMissingRequiredPropertyException(Throwable cause) { + super("AAI_5107",cause); + } + + 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 new file mode 100644 index 00000000..d9be4d5f --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/introspection/sideeffect/exceptions/AAIMultiplePropertiesException.java @@ -0,0 +1,45 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.introspection.sideeffect.exceptions; + +import org.onap.aai.exceptions.AAIException; + +public class AAIMultiplePropertiesException extends AAIException { + + private static final long serialVersionUID = 2098371383166008345L; + + public AAIMultiplePropertiesException() {} + + public AAIMultiplePropertiesException(String message) { + super("AAI_6136", message); + } + + public AAIMultiplePropertiesException(Throwable cause) { + super("AAI_6136",cause); + } + + 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 new file mode 100644 index 00000000..b049c5c5 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/introspection/tools/CreateUUID.java @@ -0,0 +1,50 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.introspection.tools; + +import org.onap.aai.introspection.Introspector; +import org.onap.aai.schema.enums.PropertyMetadata; + +import java.util.Map; +import java.util.UUID; + +public class CreateUUID implements IssueResolver { + + /** + * {@inheritDoc} + */ + @Override + public boolean resolveIssue(Issue issue) { + + Introspector obj = issue.getIntrospector(); + if (issue.getType().equals(IssueType.MISSING_KEY_PROP)) { + Map 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; + } + +} 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 new file mode 100644 index 00000000..fdf45a1f --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/introspection/tools/DefaultFields.java @@ -0,0 +1,49 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.introspection.tools; + +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 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 new file mode 100644 index 00000000..e7d86273 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/introspection/tools/InjectKeysFromURI.java @@ -0,0 +1,70 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.introspection.tools; + +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; + } + + /** + * {@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; + } + +} 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 new file mode 100644 index 00000000..b4878e38 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/introspection/tools/IntrospectorValidator.java @@ -0,0 +1,319 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.introspection.tools; + +import org.onap.aai.db.props.AAIProperties; +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.Introspector; +import org.onap.aai.introspection.IntrospectorWalker; +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 issues = null; + private List issueResolvers = null; + private boolean validateRequired = true; + private final int maximumDepth; + private int currentDepth = 0; + + private final Set 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 getIssues() { + return this.issues; + } + + /** + * Sets the issue resolvers. + * + * @param resolvers the new issue resolvers + */ + public void setIssueResolvers(List 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 requiredProps = obj.getRequiredProperties(); + Set keys = obj.getKeys(); + Set 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 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 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 list, List 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 issueResolvers = null; + private int maximumDepth = AAIProperties.MAXIMUM_DEPTH; + /** + * Instantiates a new builder. + * + * @param llBuilder the ll builder + */ + public Builder() { + issueResolvers = new ArrayList(); + } + + /** + * 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 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 new file mode 100644 index 00000000..54bc393b --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/introspection/tools/Issue.java @@ -0,0 +1,145 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.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; + } + + +} 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 new file mode 100644 index 00000000..c5a6bc28 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/introspection/tools/IssueResolver.java @@ -0,0 +1,34 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.introspection.tools; + +public interface IssueResolver { + + + /** + * 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 new file mode 100644 index 00000000..c532c5f7 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/introspection/tools/IssueType.java @@ -0,0 +1,26 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.introspection.tools; + +public enum IssueType { + 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 new file mode 100644 index 00000000..f15df84e --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/introspection/tools/RemoveNonVisibleProperty.java @@ -0,0 +1,37 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.introspection.tools; + +public class RemoveNonVisibleProperty implements IssueResolver { + + @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; + } + +} 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 new file mode 100644 index 00000000..ab3d1aa3 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/introspection/tools/Severity.java @@ -0,0 +1,28 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.introspection.tools; + +public enum Severity { + 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 new file mode 100644 index 00000000..7adbe87a --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/logging/CNName.java @@ -0,0 +1,94 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.logging; + +import ch.qos.logback.access.pattern.AccessConverter; +import ch.qos.logback.access.spi.IAccessEvent; + +import javax.security.auth.x500.X500Principal; +import javax.servlet.http.HttpServletRequest; +import java.security.cert.X509Certificate; + +import static java.util.Base64.getDecoder; + +public class CNName extends AccessConverter { + + /** + * 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){ + + HttpServletRequest request = accessEvent.getRequest(); + + 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 ":" + // 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 ", ""); + byte[] userCredentials = getDecoder().decode(credentials.getBytes("utf-8")); + credentials = new String(userCredentials); + + int codePoint = credentials.indexOf(':'); + + 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 ex){ + 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 new file mode 100644 index 00000000..a0b265ba --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/logging/CustomLogPatternLayout.java @@ -0,0 +1,29 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.logging; + +public class CustomLogPatternLayout extends ch.qos.logback.access.PatternLayout { + 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 new file mode 100644 index 00000000..57f7347d --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/logging/CustomLogPatternLayoutEncoder.java @@ -0,0 +1,41 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.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(); + } + +} 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 new file mode 100644 index 00000000..16633d5c --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/logging/DME2RestFlag.java @@ -0,0 +1,56 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.logging; + +import ch.qos.logback.access.pattern.AccessConverter; +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"; + } + + 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"; + } + + 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 new file mode 100644 index 00000000..6025ba9d --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/logging/EcompElapsedTime.java @@ -0,0 +1,68 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.logging; + +import org.onap.aai.logging.LoggingContext.LoggingField; + +import ch.qos.logback.classic.pattern.ClassicConverter; +import ch.qos.logback.classic.spi.ILoggingEvent; + +public class EcompElapsedTime extends ClassicConverter { + + private static final String DEFAULT_ELAPSED_TIME_FORMAT = "%d"; + + private String ELAPSED_TIME_FORMAT; + + @Override + public void start() { + ELAPSED_TIME_FORMAT = getFirstOption(); + } + + @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())) + ); + } + + final long start = LogFormatTools.toTimestamp(event.getMDCPropertyMap().get(LoggingField.START_TIME.toString())); + + return format(end - start); + } + + private String format(long elapsedTime) { + if (ELAPSED_TIME_FORMAT == null) { + return format(DEFAULT_ELAPSED_TIME_FORMAT, elapsedTime); + } + + return format (ELAPSED_TIME_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 new file mode 100644 index 00000000..e10ad4d0 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/logging/EcompEncoder.java @@ -0,0 +1,39 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.logging; + +import ch.qos.logback.classic.PatternLayout; +import ch.qos.logback.classic.encoder.PatternLayoutEncoder; + +public class EcompEncoder extends PatternLayoutEncoder { + + @Override + public void start() { + PatternLayout patternLayout = new EcompPatternLayout(); + patternLayout.setContext(context); + patternLayout.setPattern(getPattern()); + patternLayout.setOutputPatternAsHeader(outputPatternAsHeader); + patternLayout.start(); + this.layout = patternLayout; + super.start(); + } +} 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 new file mode 100644 index 00000000..a08c021f --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/logging/EcompPatternLayout.java @@ -0,0 +1,32 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.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()); + } +} 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 new file mode 100644 index 00000000..e0594cf0 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/logging/EcompStartTime.java @@ -0,0 +1,40 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.logging; + +import org.onap.aai.logging.LoggingContext.LoggingField; + +import ch.qos.logback.classic.pattern.ClassicConverter; +import ch.qos.logback.classic.spi.ILoggingEvent; + +public class EcompStartTime extends ClassicConverter { + + @Override + public String convert(ILoggingEvent event) { + + if (!event.getMDCPropertyMap().containsKey(LoggingField.START_TIME.toString())) { + return LogFormatTools.toDate(event.getTimeStamp()); + } + + return event.getMDCPropertyMap().get(LoggingField.START_TIME.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 new file mode 100644 index 00000000..4450be34 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/logging/EelfClassOfCaller.java @@ -0,0 +1,44 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.logging; + +import ch.qos.logback.classic.pattern.NamedConverter; +import ch.qos.logback.classic.spi.CallerData; +import ch.qos.logback.classic.spi.ILoggingEvent; + +public class EelfClassOfCaller extends NamedConverter { + protected String getFullyQualifiedName(ILoggingEvent event) { + + 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 "com.att.eelf.configuration.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(); + } 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 new file mode 100644 index 00000000..1c3ab853 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/logging/ErrorLogHelper.java @@ -0,0 +1,606 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.logging; + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Properties; + +import javax.ws.rs.core.MediaType; +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; + +/** + * + * This classes loads the application error properties file + * 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 ERROR_OBJECTS = new HashMap (); + + 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 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 variables) { + List acceptHeaders = new ArrayList(); + 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 acceptHeadersOrig, AAIException are, ArrayList variables) { + + + StringBuilder text = new StringBuilder(); + String response = null; + + List acceptHeaders = new ArrayList(); + // 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(); + } + + 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 acceptHeadersOrig, AAIException are, ArrayList variables) { + String response = ErrorLogHelper.getRESTAPIErrorResponse(acceptHeadersOrig, are, variables); + + LOGGER.error(are.getMessage(), 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 acceptHeaders, HashMap> 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>> it = areList.entrySet().iterator(); + + while (it.hasNext()) { + Map.Entry> pair = (Map.Entry>)it.next(); + AAIException are = pair.getKey(); + ArrayList 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(); + } + + 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) { + + 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(); + } + + 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 0 && sevCode <= 3 ) + { + LoggingContext.severity(sevCode); + } + } + + final String errorMessage = new StringBuilder() + .append(errorObject.getErrorText()) + .append(":") + .append(errorObject.getRESTErrorCode()) + .append(":") + .append(errorObject.getHTTPResponseCode()) + .append(":") + .append(e.getMessage()) + .toString(); + + LoggingContext.responseCode(Integer.toString(errorObject.getHTTPResponseCode().getStatusCode())); + LoggingContext.responseDescription(errorMessage); + LoggingContext.statusCode(StatusCode.ERROR); + + if (errorObject.getSeverity().equalsIgnoreCase("WARN")) + LOGGER.warn(errorMessage, e); + else if (errorObject.getSeverity().equalsIgnoreCase("ERROR")) + LOGGER.error(errorMessage, e); + else if (errorObject.getSeverity().equalsIgnoreCase("FATAL")) + LOGGER.error(errorMessage, e); + else if (errorObject.getSeverity().equals("INFO")) + LOGGER.info(errorMessage + ", " + e.getMessage()); + } + + 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 new file mode 100644 index 00000000..a1bca90e --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/logging/ErrorObject.java @@ -0,0 +1,332 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.logging; + +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; + + /** + * 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 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 new file mode 100644 index 00000000..2d346634 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/logging/ErrorObjectFormatException.java @@ -0,0 +1,31 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.logging; + +public class ErrorObjectFormatException extends Exception { + + private static final long serialVersionUID = 3732705544448553685L; + + 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 new file mode 100644 index 00000000..524ee183 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/logging/ErrorObjectNotFoundException.java @@ -0,0 +1,52 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.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 + } +} 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 new file mode 100644 index 00000000..702741b1 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/logging/LogFormatTools.java @@ -0,0 +1,46 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.logging; + +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; + +public class LogFormatTools { + + private static final String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; + private static final DateTimeFormatter DTF = DateTimeFormatter.ofPattern(DATE_FORMAT) + .withZone(ZoneOffset.UTC); + + public static String getCurrentDateTime() { + return DTF.format(ZonedDateTime.now()); + } + + 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(); + } +} 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 new file mode 100644 index 00000000..ed332281 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/logging/LoggingContext.java @@ -0,0 +1,375 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.logging; + +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +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"; + + //ECOMP 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"), + + //ECOMP Specific Metric Log Event Fields + TARGET_ENTITY("targetEntity"), + + //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(); + } + + private 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()); + LOGGER.warn("Unable to use UUID " + requestId + " (Not formatted properly). Using generated UUID=" + generatedRequestUuid); + } + } + + 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(LoggingContext.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)); + } + + 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 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 keys = previousContext.keys(); + + while (keys.hasNext()) { + final String key = keys.next(); + + 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) + } + } + + MDC.put(PREVIOUS_CONTEXTS_KEY, removeLast(previousContexts).toString()); + } catch (JSONException e) { + //Ignore, the previousContext is serialized from a JSONObject + } + } + + /** + * 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 . Had they put it into the 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 getCopy() { + final Map copy = new HashMap (); + + 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 new file mode 100644 index 00000000..1944b064 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/logging/LoggingContextNotExistsException.java @@ -0,0 +1,27 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.logging; + +public class LoggingContextNotExistsException extends RuntimeException { + + 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 new file mode 100644 index 00000000..b57387d5 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/logging/StopWatch.java @@ -0,0 +1,42 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.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 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 new file mode 100644 index 00000000..d063ef64 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/logging/StopWatchNotStartedException.java @@ -0,0 +1,43 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.logging; + +public class StopWatchNotStartedException extends RuntimeException { + + private static final long serialVersionUID = -4540164295822859408L; + + public StopWatchNotStartedException() { + super(); + } + + public StopWatchNotStartedException(String message) { + super(message); + } + + public StopWatchNotStartedException(Throwable cause) { + super(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 new file mode 100644 index 00000000..03b5695c --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/parsers/exceptions/AAIIdentityMapParseException.java @@ -0,0 +1,42 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.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); + } + + public AAIIdentityMapParseException(Throwable cause) { + super("AAI_3000",cause); + } + + 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 new file mode 100644 index 00000000..f388aaac --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/parsers/exceptions/AmbiguousMapAAIException.java @@ -0,0 +1,42 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.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); + } + +} 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 new file mode 100644 index 00000000..adf28f3e --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/parsers/exceptions/DoesNotStartWithValidNamespaceException.java @@ -0,0 +1,43 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.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); + } + + 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 new file mode 100644 index 00000000..9251be6b --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/parsers/query/LegacyQueryParser.java @@ -0,0 +1,228 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.parsers.query; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.Introspector; +import org.onap.aai.introspection.Loader; +import org.onap.aai.introspection.exceptions.AAIUnknownObjectException; +import org.onap.aai.parsers.uri.Parsable; +import org.onap.aai.parsers.uri.URIParser; +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.serialization.db.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 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 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 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)", e); + } + } + + this.resultResource = obj.getChildDBName(); + this.containerResource = obj.getName(); + } + } + private void handleUriKeys(Introspector obj, MultivaluedMap 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 values = uriKeys.get(key); + String dbPropertyName = key; + Map linkedProperties = new HashMap<>(); + final Map 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 uriKeys, Map linkedProperties) throws AAIException { + + QueryBuilder[] builders = new QueryBuilder[linkedProperties.keySet().size()]; + Set> entrySet = linkedProperties.entrySet(); + int i = 0; + Iterator> itr = entrySet.iterator(); + + while (itr.hasNext()) { + Entry 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 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 new file mode 100644 index 00000000..ce85325f --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/parsers/query/ObjectNameQueryParser.java @@ -0,0 +1,37 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +/** + * + */ +package org.onap.aai.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; + } + +} 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 new file mode 100644 index 00000000..845b49cf --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/parsers/query/QueryParser.java @@ -0,0 +1,147 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.parsers.query; + +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.onap.aai.db.props.AAIProperties; +import org.onap.aai.introspection.Loader; +import org.onap.aai.introspection.LoaderFactory; +import org.onap.aai.query.builder.QueryBuilder; + +import java.net.URI; + +/** + * The Class QueryParser. + */ +public abstract class QueryParser { + + protected Loader loader = null; + protected Loader latestLoader = null; + protected QueryBuilder queryBuilder = null; + + protected QueryBuilder 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 queryBuilder, URI uri) { + this.uri = uri; + this.queryBuilder = queryBuilder; + this.loader = loader; + this.latestLoader = LoaderFactory.createLoaderForVersion(loader.getModelType(), AAIProperties.LATEST); + } + + /** + * Instantiates a new query parser. + * + * @param loader the loader + * @param queryBuilder the query builder + */ + protected QueryParser(Loader loader, QueryBuilder queryBuilder) { + this.queryBuilder = queryBuilder; + this.loader = loader; + this.latestLoader = LoaderFactory.createLoaderForVersion(loader.getModelType(), AAIProperties.LATEST); + } + + /** + * 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 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 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 new file mode 100644 index 00000000..e8ee099a --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/parsers/query/QueryParserStrategy.java @@ -0,0 +1,92 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.parsers.query; + +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 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 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 new file mode 100644 index 00000000..5943f3cf --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/parsers/query/RelationshipQueryParser.java @@ -0,0 +1,66 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.parsers.query; + +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.Introspector; +import org.onap.aai.introspection.Loader; +import org.onap.aai.introspection.ModelType; +import org.onap.aai.parsers.relationship.RelationshipToURI; +import org.onap.aai.parsers.uri.URIParser; +import org.onap.aai.query.builder.QueryBuilder; +import org.onap.aai.serialization.db.EdgeRules; + +import java.io.UnsupportedEncodingException; + +/** + * The Class RelationshipQueryParser. + */ +public class RelationshipQueryParser extends LegacyQueryParser { + + private Introspector relationship = null; + + private ModelType modelType = null; + + private EdgeRules 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(); + this.edgeRules = EdgeRules.getInstance(); + RelationshipToURI rToUri = new RelationshipToURI(loader, obj); + this.uri = rToUri.getUri(); + URIParser parser = new URIParser(loader, uri); + parser.parse(this); + } + +} 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 new file mode 100644 index 00000000..09f3cb85 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/parsers/query/TraversalStrategy.java @@ -0,0 +1,83 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.parsers.query; + +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); + } + + /** + * @{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, MultivaluedMap 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 new file mode 100644 index 00000000..10566ccb --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/parsers/query/UniqueRelationshipQueryParser.java @@ -0,0 +1,58 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.parsers.query; + +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(); + } + +} 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 new file mode 100644 index 00000000..cc300fbc --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/parsers/query/UniqueStrategy.java @@ -0,0 +1,82 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.parsers.query; + +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); + } + + /** + * @{inheritDoc} + */ + @Override + public QueryParser buildRelationshipParser(Introspector obj) throws UnsupportedEncodingException, AAIException { + return new UniqueRelationshipQueryParser(loader, builder, obj); + } + + /** + * @{inheritDoc} + */ + @Override + public QueryParser buildURIParser(URI uri, MultivaluedMap 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/UniqueURIQueryParser.java b/aai-core/src/main/java/org/onap/aai/parsers/query/UniqueURIQueryParser.java new file mode 100644 index 00000000..1d63f6e4 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/parsers/query/UniqueURIQueryParser.java @@ -0,0 +1,165 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.parsers.query; + +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.Introspector; +import org.onap.aai.introspection.Loader; +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.serialization.db.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 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 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 new file mode 100644 index 00000000..69e44a97 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/parsers/relationship/RelationshipToURI.java @@ -0,0 +1,282 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.parsers.relationship; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.apache.tinkerpop.gremlin.structure.Direction; +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.*; +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.serialization.db.AAIDirection; +import org.onap.aai.serialization.db.EdgeRule; +import org.onap.aai.serialization.db.EdgeRules; +import org.onap.aai.serialization.db.EdgeType; +import org.onap.aai.workarounds.LegacyURITransformer; + +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 EdgeRules edgeRules = null; + + private URI uri = null; + + private LegacyURITransformer urlTransform = null; + + /** + * 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.edgeRules = EdgeRules.getInstance(); + this.loader = loader; + this.urlTransform = LegacyURITransformer.getInstance(); + + this.parse(); + + } + + /** + * 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 result; + try { + if (loader.getVersion().compareTo(Version.v10) >= 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 processRelationshipData() throws AAIException, UnsupportedEncodingException { + Optional result = Optional.empty(); + StringBuilder uriBuilder = new StringBuilder(); + List data = (List)relationship.getValue("relationship-data"); + Introspector wrapper; + String key; + String value; + String objectType; + String propertyName; + String topLevelType = null; + String[] split; + HashMap 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); + } + + 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 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 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; + } + + private Optional processRelatedLink(String relatedLink) throws URISyntaxException, UnsupportedEncodingException, AAIIdentityMapParseException { + Optional 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 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.getEdgeRule(EdgeType.TREE, startType, objectType); + 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 e) { + //ignore exceptions generated + continue; + } + } + + + 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 new file mode 100644 index 00000000..3c8697e9 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/parsers/uri/Parsable.java @@ -0,0 +1,73 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.parsers.uri; + +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.Introspector; +import org.onap.aai.serialization.db.EdgeType; + +import javax.ws.rs.core.MultivaluedMap; + +/** + * The Interface Parsable. + */ +public interface Parsable { + + /** + * + * @param obj + * @param type + * @param uriKeys + * @throws AAIException + */ + public void processObject(Introspector obj, EdgeType type, MultivaluedMap 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 + */ + public void processContainer(Introspector obj, EdgeType type, MultivaluedMap uriKeys, boolean isFinalContainer) throws AAIException; + + /** + * Process namespace. + * + * @param obj the obj + */ + public void processNamespace(Introspector obj); + + /** + * Gets the cloud region transform. + * + * @return the cloud region transform + */ + public String getCloudRegionTransform(); + + /** + * Use original loader. + * + * @return true, if successful + */ + public 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 new file mode 100644 index 00000000..5480b49f --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/parsers/uri/URIParser.java @@ -0,0 +1,279 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.parsers.uri; + +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.introspection.Version; +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.serialization.db.EdgeType; +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 queryParams = null; + + + /** + * Instantiates a new URI parser. + * + * @param loader the loader + * @param uri the uri + */ + public URIParser(Loader loader, URI uri) { + this.uri = uri; + + String currentVersion = "v7"; + this.originalLoader = loader; + try { + currentVersion = AAIConfig.get("aai.default.api.version"); + } catch (AAIException e) { + ErrorLogHelper.logException(e); + } + + //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 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 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 uriKeys = new MultivaluedHashMap<>(); + if (i == parts.length-2 && queryParams != null) { + Set queryKeys = queryParams.keySet(); + for (String key : queryKeys) { + uriKeys.put(key, queryParams.get(key)); + + } + } + if (introspector.isContainer()) { + boolean isFinalContainer = i == parts.length-2; + p.processContainer(introspector, EdgeType.COUSIN, uriKeys, isFinalContainer); + } + previousObj = introspector; + type = EdgeType.COUSIN; + 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 uriKeys = new MultivaluedHashMap<>(); + i++; + if (i == parts.length && queryParams != null) { + Set 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 uriKeys = new MultivaluedHashMap<>(); + + if (isFinalContainer && queryParams != null) { + Set 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); + } + + result = result.replaceFirst("aai/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 new file mode 100644 index 00000000..1df39b30 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/parsers/uri/URIToDBKey.java @@ -0,0 +1,123 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.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.serialization.db.EdgeType; + +import javax.ws.rs.core.MultivaluedMap; +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.util.ArrayList; +import java.util.List; + +/** + * Creates a Unique database key from a URI + * + * The key is of the form node-type/key(s). + */ +public class URIToDBKey implements Parsable { + + + private List 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); + } + /* + public URIToDBKey(Version version, String uri) throws IllegalArgumentException { + + super(version, uri); + try { + context = ModelInjestor.getInstance().getContextForVersion(version); + if (context == null) { + throw new IllegalArgumentException("could not find a context for version: " + version); + } + this.parse(); + } catch (Exception e) { + throw new IllegalArgumentException("uri not valid against our model: " + uri); + } + }*/ + + /** + * @{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 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 uriKeys, + boolean isFinalContainer) throws AAIException { + } +} 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 new file mode 100644 index 00000000..0b34a45f --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/parsers/uri/URIToExtensionInformation.java @@ -0,0 +1,165 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.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.serialization.db.EdgeType; + +import javax.ws.rs.core.MultivaluedMap; +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.util.ArrayList; +import java.util.List; + +/** + * The Class URIToExtensionInformation. + */ +public class URIToExtensionInformation implements Parsable { + + private String namespace = ""; + + private String methodName = ""; + + private String topObject = ""; + + private List 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)) { + result += "Add"; + } 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 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 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 new file mode 100644 index 00000000..cae5c2e8 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/parsers/uri/URIToObject.java @@ -0,0 +1,221 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.parsers.uri; + +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.Introspector; +import org.onap.aai.introspection.Loader; +import org.onap.aai.introspection.Version; +import org.onap.aai.schema.enums.ObjectMetadata; +import org.onap.aai.serialization.db.EdgeType; + +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. + * + * It populates the keys in the order they are listed in the model. + * + + * + */ +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 parentList = null; + + private Version version = null; + private Loader loader = null; + private final HashMap 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 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 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 Version getObjectVersion() { + return this.loader.getVersion(); + } + public Loader getLoader() { + return this.loader; + } + @Override + public void processObject(Introspector obj, EdgeType type, MultivaluedMap uriKeys) + throws AAIException { + + if (this.entityName == null) { + this.topEntityName = obj.getDbName(); + this.topEntity = obj; + } + this.entityName = obj.getDbName(); + this.entity = obj; + this.parentList = (List)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 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 new file mode 100644 index 00000000..cec55bc3 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/parsers/uri/URIToRelationshipObject.java @@ -0,0 +1,170 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.parsers.uri; + +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.Introspector; +import org.onap.aai.introspection.Loader; +import org.onap.aai.introspection.Version; +import org.onap.aai.introspection.exceptions.AAIUnknownObjectException; +import org.onap.aai.serialization.db.EdgeType; +import org.onap.aai.util.AAIApiServerURLBase; +import org.onap.aai.workarounds.LegacyURITransformer; + +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 LegacyURITransformer uriTransformer = null; + + private Version 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; + uriTransformer = LegacyURITransformer.getInstance(); + originalVersion = loader.getVersion(); + + try { + relationship = loader.introspectorFromName("relationship"); + } catch (AAIUnknownObjectException e1) { + throw new RuntimeException("Fatal error - could not load relationship object!", e1); + } + + this.baseURL = AAIApiServerURLBase.get(originalVersion); + 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); + this.relationship.setValue("related-link", relatedLink); + if (this.originalVersion.compareTo(Version.v10) >= 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 uriKeys) + throws AAIException { + 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)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 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 new file mode 100644 index 00000000..8371fc83 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/parsers/uri/URIValidate.java @@ -0,0 +1,64 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.parsers.uri; + +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.Introspector; +import org.onap.aai.serialization.db.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 uriKeys) + throws AAIException { + //NO-OP + //just want to make sure this URI has valid tokens + } + + @Override + public void processContainer(Introspector obj, EdgeType type, MultivaluedMap 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 new file mode 100644 index 00000000..8a585dae --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/query/builder/GraphTraversalBuilder.java @@ -0,0 +1,656 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.query.builder; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Optional; +import java.util.Set; + +import org.apache.tinkerpop.gremlin.process.traversal.P; +import org.apache.tinkerpop.gremlin.process.traversal.Traversal; +import org.apache.tinkerpop.gremlin.process.traversal.Traversal.Admin; +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__; +import org.apache.tinkerpop.gremlin.process.traversal.util.TraversalHelper; +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.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.serialization.db.EdgeRule; +import org.onap.aai.serialization.db.EdgeRules; +import org.onap.aai.serialization.db.EdgeType; +import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException; + +/** + * The Class GraphTraversalBuilder. + */ +public abstract class GraphTraversalBuilder extends QueryBuilder { + + protected GraphTraversal traversal = null; + protected Admin completeTraversal = null; + private EdgeRules edgeRules = EdgeRules.getInstance(); + + protected int parentStepIndex = 0; + protected int containerStepIndex = 0; + protected int stepIndex = 0; + + /** + * Instantiates a new graph traversal builder. + * + * @param loader the loader + */ + public GraphTraversalBuilder(Loader loader, GraphTraversalSource source) { + super(loader, source); + + traversal = (GraphTraversal) __.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) __.__(start); + + } + + /** + * @{inheritDoc} + */ + @Override + public QueryBuilder getVerticesByIndexedProperty(String key, Object value) { + + return this.getVerticesByProperty(key, value); + } + + /** + * @{inheritDoc} + */ + @Override + public QueryBuilder getVerticesByIndexedProperty(String key, List values) { + return this.getVerticesByProperty(key, values); + } + + /** + * @{inheritDoc} + */ + @Override + public QueryBuilder getVerticesByProperty(String key, Object value) { + + //this is because the index is registered as an Integer + value = this.correctObjectType(value); + + traversal.has(key, value); + + stepIndex++; + return (QueryBuilder) this; + } + + /** + * @{inheritDoc} + */ + @Override + public QueryBuilder getVerticesByProperty(final String key, final List values) { + + //this is because the index is registered as an Integer + List correctedValues = new ArrayList<>(); + for (Object item : values) { + correctedValues.add(this.correctObjectType(item)); + } + + traversal.has(key, P.within(correctedValues)); + + stepIndex++; + return (QueryBuilder) this; + } + + /** + * @{inheritDoc} + */ + @Override + public QueryBuilder getChildVerticesFromParent(String parentKey, String parentValue, String childType) { + traversal.has(parentKey, parentValue).has(AAIProperties.NODE_TYPE, childType); + stepIndex++; + return (QueryBuilder) this; + } + + /** + * @{inheritDoc} + */ + @Override + public QueryBuilder getTypedVerticesByMap(String type, LinkedHashMap map) { + + for (String key : map.keySet()) { + traversal.has(key, map.get(key)); + stepIndex++; + } + traversal.has(AAIProperties.NODE_TYPE, type); + stepIndex++; + return (QueryBuilder) this; + } + + /** + * @{inheritDoc} + */ + @Override + public QueryBuilder createDBQuery(Introspector obj) { + this.createKeyQuery(obj); + this.createContainerQuery(obj); + return (QueryBuilder) this; + } + + /** + * @{inheritDoc} + */ + @Override + public QueryBuilder createKeyQuery(Introspector obj) { + Set keys = obj.getKeys(); + Object val; + for (String key : keys) { + val = obj.getValue(key); + Optional 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) this; + } + + @Override + public QueryBuilder exactMatchQuery(Introspector obj) { + this.createKeyQuery(obj); + allPropertiesQuery(obj); + this.createContainerQuery(obj); + return (QueryBuilder) this; + } + + private void allPropertiesQuery(Introspector obj) { + Set props = obj.getProperties(); + Set keys = obj.getKeys(); + Object val; + for (String prop : props) { + if (obj.isSimpleType(prop) && !keys.contains(prop)) { + val = obj.getValue(prop); + if (val != null) { + Optional 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 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) this; + } + + /** + * @throws NoEdgeRuleFoundException + * @throws AAIException + * @{inheritDoc} + */ + @Override + public QueryBuilder createEdgeTraversal(EdgeType type, Introspector parent, Introspector child) throws AAIException, NoEdgeRuleFoundException { + String isAbstractType = parent.getMetadata(ObjectMetadata.ABSTRACT); + if ("true".equals(isAbstractType)) { + markParentBoundary(); + traversal.union(handleAbstractEdge(type, parent, child)); + stepIndex += 1; + } else { + this.edgeQueryToVertex(type, parent, child); + } + return (QueryBuilder) this; + + } + + private Traversal[] handleAbstractEdge(EdgeType type, Introspector abstractParent, Introspector child) throws AAIException, NoEdgeRuleFoundException { + String childName = child.getDbName(); + String inheritorMetadata = abstractParent.getMetadata(ObjectMetadata.INHERITORS); + String[] inheritors = inheritorMetadata.split(","); + Traversal[] unionTraversals = new Traversal[inheritors.length]; + int traversalIndex = 0; + for (int i = 0; i < inheritors.length; i++) { + String inheritor = inheritors[i]; + if (edgeRules.hasEdgeRule(inheritor, childName) || edgeRules.hasEdgeRule(childName, inheritor)) { + EdgeRule rule = edgeRules.getEdgeRule(type, inheritor, childName); + GraphTraversal innerTraversal = __.start(); + if (rule.getDirection().equals(Direction.OUT)) { + innerTraversal.out(rule.getLabel()); + } else { + innerTraversal.in(rule.getLabel()); + } + innerTraversal.has(AAIProperties.NODE_TYPE, childName); + unionTraversals[traversalIndex] = innerTraversal; + traversalIndex++; + } + } + if (traversalIndex < inheritors.length) { + Traversal[] temp = Arrays.copyOfRange(unionTraversals, 0, traversalIndex); + unionTraversals = temp; + } + return unionTraversals; + } + /** + * @throws NoEdgeRuleFoundException + * @throws AAIException + * @{inheritDoc} + */ + @Override + public QueryBuilder createEdgeTraversal(EdgeType type, Vertex parent, Introspector child) throws AAIException, NoEdgeRuleFoundException { + + String nodeType = parent.property(AAIProperties.NODE_TYPE).orElse(null); + Introspector parentObj = loader.introspectorFromName(nodeType); + this.edgeQueryToVertex(type, parentObj, child); + return (QueryBuilder) this; + + } + + @Override + public QueryBuilder getEdgesBetween(EdgeType type, String outNodeType, String inNodeType) throws AAIException { + Introspector outObj = loader.introspectorFromName(outNodeType); + Introspector inObj = loader.introspectorFromName(inNodeType); + this.edgeQuery(type, outObj, inObj); + + return (QueryBuilder)this; + + } + /** + * @{inheritDoc} + */ + @Override + public QueryBuilder union(QueryBuilder... builder) { + GraphTraversal[] traversals = new GraphTraversal[builder.length]; + for (int i = 0; i < builder.length; i++) { + traversals[i] = (GraphTraversal)builder[i].getQuery(); + } + this.traversal.union(traversals); + stepIndex++; + + return this; + } + + /** + * @{inheritDoc} + */ + @Override + public QueryBuilder where(QueryBuilder... builder) { + GraphTraversal[] traversals = new GraphTraversal[builder.length]; + for (int i = 0; i < builder.length; i++) { + this.traversal.where((GraphTraversal)builder[i].getQuery()); + stepIndex++; + } + + return this; + } + + @Override + public QueryBuilder store(String name) { + + this.traversal.store(name); + stepIndex++; + + return this; + } + + @Override + public QueryBuilder cap(String name) { + this.traversal.cap(name); + stepIndex++; + + return this; + } + + @Override + public QueryBuilder unfold() { + this.traversal.unfold(); + stepIndex++; + + return this; + } + + @Override + public QueryBuilder dedup() { + + this.traversal.dedup(); + stepIndex++; + + return this; + } + + @Override + public QueryBuilder emit() { + + this.traversal.emit(); + stepIndex++; + + return this; + + } + + @Override + public QueryBuilder repeat(QueryBuilder builder) { + + this.traversal.repeat((GraphTraversal)builder.getQuery()); + stepIndex++; + + return this; + } + + @Override + public QueryBuilder until(QueryBuilder builder) { + this.traversal.until((GraphTraversal)builder.getQuery()); + stepIndex++; + + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public QueryBuilder simplePath(){ + this.traversal.simplePath(); + stepIndex++; + return this; + } + + @Override + public QueryBuilder outE() { + this.traversal.outE(); + stepIndex++; + return (QueryBuilder)this; + } + + @Override + public QueryBuilder inE() { + this.traversal.inE(); + stepIndex++; + return (QueryBuilder)this; + } + + @Override + public QueryBuilder outV() { + this.traversal.outV(); + stepIndex++; + return (QueryBuilder)this; + } + + @Override + public QueryBuilder inV() { + this.traversal.inV(); + stepIndex++; + return (QueryBuilder)this; + } + + @Override + public QueryBuilder as(String name) { + this.traversal.as(name); + + stepIndex++; + return this; + } + + @Override + public QueryBuilder not(QueryBuilder builder) { + this.traversal.not(builder.getQuery()); + + stepIndex++; + return this; + } + + @Override + public QueryBuilder select(String name) { + this.traversal.select(name); + + stepIndex++; + + return this; + } + + /** + * Edge query. + * + * @param outType the out type + * @param inType the in type + * @throws NoEdgeRuleFoundException + * @throws AAIException + */ + private void edgeQueryToVertex(EdgeType type, Introspector outObj, Introspector inObj) throws AAIException, NoEdgeRuleFoundException { + String outType = outObj.getDbName(); + String inType = inObj.getDbName(); + + if (outObj.isContainer()) { + outType = outObj.getChildDBName(); + } + if (inObj.isContainer()) { + inType = inObj.getChildDBName(); + } + markParentBoundary(); + EdgeRule rule = edgeRules.getEdgeRule(type, outType, inType); + if (rule.getDirection().equals(Direction.OUT)) { + traversal.out(rule.getLabel()); + } else { + traversal.in(rule.getLabel()); + } + stepIndex++; + this.createContainerQuery(inObj); + + } + + /** + * Edge query. + * + * @param outType the out type + * @param inType the in type + * @throws NoEdgeRuleFoundException + * @throws AAIException + */ + private void edgeQuery(EdgeType type, Introspector outObj, Introspector inObj) throws AAIException, NoEdgeRuleFoundException { + String outType = outObj.getDbName(); + String inType = inObj.getDbName(); + + if (outObj.isContainer()) { + outType = outObj.getChildDBName(); + } + if (inObj.isContainer()) { + inType = inObj.getChildDBName(); + } + markParentBoundary(); + EdgeRule rule = edgeRules.getEdgeRule(type, outType, inType); + if (rule.getDirection().equals(Direction.OUT)) { + traversal.outE(rule.getLabel()); + } else { + traversal.inE(rule.getLabel()); + } + stepIndex++; + + } + + @Override + public QueryBuilder limit(long amount) { + traversal.limit(amount); + return this; + } + + /** + * @{inheritDoc} + */ + @Override + public E2 getQuery() { + return (E2)this.traversal; + } + + /** + * @{inheritDoc} + */ + @Override + public QueryBuilder getParentQuery() { + + return cloneQueryAtStep(parentStepIndex); + } + + @Override + public QueryBuilder 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; + } + + protected abstract QueryBuilder cloneQueryAtStep(int index); + /** + * end is exclusive + * + * @param start + * @param end + * @return + */ + protected abstract QueryBuilder removeQueryStepsBetween(int start, int end); + + private 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) 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 toList() { + if (this.completeTraversal == null) { + executeQuery(); + } + + return this.completeTraversal.toList(); + } + +} 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 new file mode 100644 index 00000000..62ba5392 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/query/builder/GremlinQueryBuilder.java @@ -0,0 +1,568 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.query.builder; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; +import org.apache.tinkerpop.gremlin.structure.Direction; +import org.apache.tinkerpop.gremlin.structure.Edge; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.onap.aai.db.props.AAIProperties; +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.Introspector; +import org.onap.aai.introspection.Loader; +import org.onap.aai.restcore.search.GremlinGroovyShellSingleton; +import org.onap.aai.schema.enums.ObjectMetadata; +import org.onap.aai.serialization.db.EdgeRule; +import org.onap.aai.serialization.db.EdgeRules; +import org.onap.aai.serialization.db.EdgeType; +import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException; + +import com.google.common.base.Joiner; + +/** + * The Class GremlinQueryBuilder. + */ +public abstract class GremlinQueryBuilder extends QueryBuilder { + + private EdgeRules edgeRules = EdgeRules.getInstance(); + private GremlinGroovyShellSingleton gremlinGroovy = GremlinGroovyShellSingleton.getInstance(); + private GraphTraversal completeTraversal = null; + protected List list = null; + + protected int parentStepIndex = 0; + protected int containerStepIndex = 0; + protected int stepIndex = 0; + + /** + * Instantiates a new gremlin query builder. + * + * @param loader the loader + */ + public GremlinQueryBuilder(Loader loader, GraphTraversalSource source) { + super(loader, source); + list = new ArrayList(); + } + + /** + * Instantiates a new gremlin query builder. + * + * @param loader the loader + * @param start the start + */ + public GremlinQueryBuilder(Loader loader, GraphTraversalSource source, Vertex start) { + super(loader, source, start); + list = new ArrayList(); + } + + /** + * @{inheritDoc} + */ + @Override + public QueryBuilder createDBQuery(Introspector obj) { + this.createKeyQuery(obj); + this.createContainerQuery(obj); + return (QueryBuilder) this; + } + + @Override + public QueryBuilder exactMatchQuery(Introspector obj) { + // TODO not implemented because this is implementation is no longer used + this.createKeyQuery(obj); + //allPropertiesQuery(obj); + this.createContainerQuery(obj); + return (QueryBuilder) this; + } + + /** + * @{inheritDoc} + */ + @Override + public QueryBuilder getVerticesByIndexedProperty(String key, Object value) { + return this.getVerticesByProperty(key, value); + } + + /** + * @{inheritDoc} + */ + @Override + public QueryBuilder getVerticesByIndexedProperty(String key, List values) { + return this.getVerticesByProperty(key, values); + } + + /** + * @{inheritDoc} + */ + @Override + public QueryBuilder getVerticesByProperty(String key, Object value) { + + String term = ""; + if (value != null && !value.getClass().getName().equals("java.lang.String")) { + term = value.toString(); + } else { + term = "'" + value + "'"; + } + list.add(".has('" + key + "', " + term + ")"); + stepIndex++; + return (QueryBuilder) this; + } + + /** + * @{inheritDoc} + */ + @Override + public QueryBuilder getVerticesByProperty(String key, List values) { + + String term = ""; + String predicate = "P.within(#!#argument#!#)"; + List arguments = new ArrayList<>(); + for (Object item : values) { + if (item != null && !item.getClass().getName().equals("java.lang.String")) { + arguments.add(item.toString()); + } else { + arguments.add("'" + item + "'"); + } + } + String argument = Joiner.on(",").join(arguments); + predicate = predicate.replace("#!#argument#!#", argument); + list.add(".has('" + key + "', " + predicate + ")"); + stepIndex++; + return (QueryBuilder) this; + } + + + /** + * @{inheritDoc} + */ + @Override + public QueryBuilder getChildVerticesFromParent(String parentKey, String parentValue, String childType) { + /* + String query = ".has('aai-node-type', '" + childType + "')"; + + return this.processGremlinQuery(parentKey, parentValue, query); + */ + //TODO + return (QueryBuilder) this; + } + + /** + * @{inheritDoc} + */ + @Override + public QueryBuilder getTypedVerticesByMap(String type, LinkedHashMap map) { + + for (String key : map.keySet()) { + list.add(".has('" + key + "', '" + map.get(key) + "')"); + stepIndex++; + } + list.add(".has('aai-node-type', '" + type + "')"); + stepIndex++; + return (QueryBuilder) this; + } + + /** + * @{inheritDoc} + */ + @Override + public QueryBuilder createKeyQuery(Introspector obj) { + Set keys = obj.getKeys(); + + for (String key : keys) { + + this.getVerticesByProperty(key, obj.getValue(key)); + + } + return (QueryBuilder) this; + } + + /** + * @throws NoEdgeRuleFoundException + * @throws AAIException + * @{inheritDoc} + */ + @Override + public QueryBuilder createEdgeTraversal(EdgeType type, Introspector parent, Introspector child) throws AAIException, NoEdgeRuleFoundException { + String parentName = parent.getDbName(); + String childName = child.getDbName(); + if (parent.isContainer()) { + parentName = parent.getChildDBName(); + } + if (child.isContainer()) { + childName = child.getChildDBName(); + } + this.edgeQueryToVertex(type, parentName, childName); + return this; + + } + + /** + * @throws NoEdgeRuleFoundException + * @throws AAIException + * @{inheritDoc} + */ + @Override + public QueryBuilder createEdgeTraversal(EdgeType type, Vertex parent, Introspector child) throws AAIException, NoEdgeRuleFoundException { + String nodeType = parent.property(AAIProperties.NODE_TYPE).orElse(null); + this.edgeQueryToVertex(type, nodeType, child.getDbName()); + + return (QueryBuilder) this; + + } + + @Override + public QueryBuilder getEdgesBetween(EdgeType type, String outNodeType, String inNodeType) throws AAIException { + this.edgeQuery(type, outNodeType, inNodeType); + + return (QueryBuilder)this; + + } + /** + * Edge query. + * + * @param outType the out type + * @param inType the in type + * @throws NoEdgeRuleFoundException + * @throws AAIException + */ + private void edgeQueryToVertex(EdgeType type, String outType, String inType) throws AAIException, NoEdgeRuleFoundException { + markParentBoundary(); + EdgeRule rule = edgeRules.getEdgeRule(type, outType, inType); + if (rule.getDirection().equals(Direction.OUT)) { + list.add(".out('" + rule.getLabel() + "')"); + } else { + list.add(".in('" + rule.getLabel() + "')"); + } + stepIndex++; + list.add(".has('" + AAIProperties.NODE_TYPE + "', '" + inType + "')"); + stepIndex++; + + } + + /** + * Edge query. + * + * @param outType the out type + * @param inType the in type + * @throws NoEdgeRuleFoundException + * @throws AAIException + */ + private void edgeQuery(EdgeType type, String outType, String inType) throws AAIException, NoEdgeRuleFoundException { + markParentBoundary(); + EdgeRule rule = edgeRules.getEdgeRule(type, outType, inType); + if (rule.getDirection().equals(Direction.OUT)) { + list.add(".outE('" + rule.getLabel() + "')"); + } else { + list.add(".inV('" + rule.getLabel() + "')"); + } + stepIndex++; + + } + @Override + public QueryBuilder limit(long amount) { + list.add(".limit(" + amount + ")"); + return this; + } + /** + * @{inheritDoc} + */ + @Override + public QueryBuilder createContainerQuery(Introspector obj) { + String type = obj.getChildDBName(); + String abstractType = obj.getMetadata(ObjectMetadata.ABSTRACT); + if (abstractType != null) { + String[] inheritors = obj.getMetadata(ObjectMetadata.INHERITORS).split(","); + String[] wrapped = new String[inheritors.length]; + StringBuilder command = new StringBuilder(); + command.append("P.within("); + for (int i = 0; i < inheritors.length; i++) { + wrapped[i] = "'" + inheritors[i] + "'"; + } + command.append(Joiner.on(",").join(wrapped)); + command.append(")"); + list.add(".has('aai-node-type', " + command + ")"); + + } else { + list.add(".has('aai-node-type', '" + type + "')"); + } + stepIndex++; + this.markContainer(); + return (QueryBuilder) this; + } + + @Override + public QueryBuilder union(QueryBuilder... builder) { + markParentBoundary(); + String[] traversals = new String[builder.length]; + StringBuilder command = new StringBuilder(); + for (int i = 0; i < builder.length; i++) { + traversals[i] = "__" + (String)builder[i].getQuery(); + } + command.append(".union("); + command.append(Joiner.on(",").join(traversals)); + command.append(")"); + list.add(command.toString()); + stepIndex++; + + return this; + } + + @Override + public QueryBuilder where(QueryBuilder... builder) { + markParentBoundary(); + List traversals = new ArrayList<>(); + for (int i = 0; i < builder.length; i++) { + traversals.add(".where(__" + (String)builder[i].getQuery() + ")"); + stepIndex++; + } + list.addAll(traversals); + + + return this; + } + + @Override + public QueryBuilder store(String name) { + this.list.add(".store('"+ name + "')"); + stepIndex++; + + return this; + } + + @Override + public QueryBuilder cap(String name) { + this.list.add(".cap('"+ name + "')"); + stepIndex++; + + return this; + } + + @Override + public QueryBuilder unfold() { + this.list.add(".unfold()"); + stepIndex++; + + return this; + } + + @Override + public QueryBuilder dedup() { + this.list.add(".dedup()"); + stepIndex++; + + return this; + } + + @Override + public QueryBuilder emit() { + this.list.add(".emit()"); + stepIndex++; + + return this; + } + + @Override + public QueryBuilder repeat(QueryBuilder builder) { + this.list.add(".repeat(__" + builder.getQuery() + ")"); + stepIndex++; + + return this; + } + + @Override + public QueryBuilder until(QueryBuilder builder) { + this.list.add(".until(__" + builder.getQuery() + ")"); + stepIndex++; + + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public QueryBuilder simplePath(){ + this.list.add(".simplePath()"); + stepIndex++; + return this; + } + + @Override + public QueryBuilder outE() { + this.list.add(".outE()"); + stepIndex++; + + return (QueryBuilder)this; + } + + @Override + public QueryBuilder inE() { + this.list.add(".inE()"); + stepIndex++; + + return (QueryBuilder)this; + } + + @Override + public QueryBuilder outV() { + this.list.add(".outV()"); + stepIndex++; + + return (QueryBuilder)this; + } + + @Override + public QueryBuilder inV() { + this.list.add(".inV()"); + stepIndex++; + + return (QueryBuilder)this; + } + + @Override + public QueryBuilder not(QueryBuilder builder) { + this.list.add(".not(" + "__" + builder.getQuery() + ")"); + stepIndex++; + + return this; + } + + @Override + public QueryBuilder as(String name) { + this.list.add(".as('" + name + "')"); + stepIndex++; + + return this; + } + + @Override + public QueryBuilder select(String name) { + this.list.add(".select('" + name + "')"); + stepIndex++; + + return this; + } + /** + * @{inheritDoc} + */ + @Override + public QueryBuilder getParentQuery() { + return cloneQueryAtStep(parentStepIndex); + } + + @Override + public QueryBuilder getContainerQuery() { + return cloneQueryAtStep(containerStepIndex); + } + + /** + * @{inheritDoc} + */ + @Override + public T2 getQuery() { + StringBuilder sb = new StringBuilder(); + + for (String piece : this.list) { + sb.append(piece); + } + + return (T2)sb.toString(); + } + + /** + * @{inheritDoc} + */ + @Override + public void markParentBoundary() { + parentStepIndex = stepIndex; + } + + @Override + public void markContainer() { + this.containerStepIndex = stepIndex; + } + + protected abstract QueryBuilder cloneQueryAtStep(int index); + /** + * @{inheritDoc} + */ + @Override + public Vertex getStart() { + return this.start; + } + + protected int getParentStepIndex() { + return parentStepIndex; + } + + protected int getContainerStepIndex() { + return containerStepIndex; + } + + protected int getStepIndex() { + return stepIndex; + } + + private void executeQuery() { + String queryString = "g" + Joiner.on("").join(list); + Map params = new HashMap<>(); + if (this.start == null) { + params.put("g", source.V()); + } else { + params.put("g", source.V(this.start)); + } + this.completeTraversal = this.gremlinGroovy.executeTraversal(queryString, params); + } + @Override + public boolean hasNext() { + if (this.completeTraversal == null) { + executeQuery(); + } + + return this.completeTraversal.hasNext(); + } + + @Override + public E next() { + if (this.completeTraversal == null) { + executeQuery(); + } + + return (E)this.completeTraversal.next(); + } + + @Override + public List toList() { + if (this.completeTraversal == null) { + executeQuery(); + } + + return (List)this.completeTraversal.toList(); + } + +} 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 new file mode 100644 index 00000000..801ac339 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/query/builder/GremlinTraversal.java @@ -0,0 +1,137 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.query.builder; + +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.util.ArrayList; +import java.util.List; + +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; +import org.onap.aai.parsers.query.QueryParser; +import org.onap.aai.parsers.query.TraversalStrategy; + +/** + * The Class GremlinTraversal. + */ +public class GremlinTraversal extends GremlinQueryBuilder { + + /** + * 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 traversal, Loader loader, GraphTraversalSource source, GremlinQueryBuilder 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 queryParams) + throws UnsupportedEncodingException, AAIException { + return factory.buildURIParser(uri, queryParams); + } + + /** + * @{inheritDoc} + */ + @Override + public QueryParser createQueryFromObjectName(String objName) { + return factory.buildObjectNameParser(objName); + } + + /** + * @{inheritDoc} + */ + @Override + public QueryBuilder newInstance(Vertex start) { + return new GremlinTraversal<>(loader, source, start); + } + + /** + * @{inheritDoc} + */ + @Override + public QueryBuilder newInstance() { + return new GremlinTraversal<>(loader, source); + } + + @Override + protected QueryBuilder cloneQueryAtStep(int index) { + if (index == 0) { + index = stepIndex; + } + List newList = new ArrayList<>(); + for (int i = 0; i < index; 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 new file mode 100644 index 00000000..284f8847 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/query/builder/GremlinUnique.java @@ -0,0 +1,138 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.query.builder; + +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.util.ArrayList; +import java.util.List; + +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; +import org.onap.aai.parsers.query.QueryParser; +import org.onap.aai.parsers.query.TraversalStrategy; +import org.onap.aai.parsers.query.UniqueStrategy; + +/** + * The Class GremlinUnique. + */ +public class GremlinUnique extends GremlinQueryBuilder { + + /** + * 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 traversal, Loader loader, GraphTraversalSource source, GremlinQueryBuilder 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 queryParams) + throws UnsupportedEncodingException, AAIException { + return factory.buildURIParser(uri, queryParams); + } + + /** + * @{inheritDoc} + */ + @Override + public QueryParser createQueryFromObjectName(String objName) { + return factory.buildObjectNameParser(objName); + } + + /** + * @{inheritDoc} + */ + @Override + public QueryBuilder newInstance() { + return new GremlinUnique<>(loader, source); + } + + /** + * @{inheritDoc} + */ + @Override + public QueryBuilder newInstance(Vertex start) { + return new GremlinUnique<>(loader, source, start); + } + + @Override + protected QueryBuilder cloneQueryAtStep(int index) { + if (index == 0) { + index = stepIndex; + } + List newList = new ArrayList<>(); + for (int i = 0; i < index; 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/QueryBuilder.java b/aai-core/src/main/java/org/onap/aai/query/builder/QueryBuilder.java new file mode 100644 index 00000000..3a3feafb --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/query/builder/QueryBuilder.java @@ -0,0 +1,319 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.query.builder; + +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; + +import javax.ws.rs.core.MultivaluedMap; + +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; +import org.apache.tinkerpop.gremlin.structure.Edge; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.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.QueryParserStrategy; +import org.onap.aai.serialization.db.EdgeType; +import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException; + +/** + * The Class QueryBuilder. + */ +public abstract class QueryBuilder implements Iterator { + + protected QueryParserStrategy factory = null; + + protected Loader loader = null; + + protected boolean optimize = false; + + protected Vertex start = null; + protected final GraphTraversalSource source; + + /** + * Instantiates a new query builder. + * + * @param loader the loader + */ + public QueryBuilder(Loader loader, GraphTraversalSource source) { + this.loader = loader; + this.source = source; + } + + /** + * 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; + } + + /** + * Gets the vertices by indexed property. + * + * @param key the key + * @param value the value + * @return the vertices by indexed property + */ + public abstract QueryBuilder getVerticesByIndexedProperty(String key, Object value); + + /** + * Gets the vertices by property. + * + * @param key the key + * @param value the value + * @return the vertices by property + */ + public abstract QueryBuilder getVerticesByProperty(String key, Object value); + + /** + * filters by all the values for this property + * @param key + * @param values + * @return vertices that match these values + */ + public abstract QueryBuilder getVerticesByIndexedProperty(String key, List values); + + /** + * filters by all the values for this property + * @param key + * @param values + * @return vertices that match these values + */ + public abstract QueryBuilder getVerticesByProperty(String key, List values); + + /** + * 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 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 getTypedVerticesByMap(String type, LinkedHashMap map); + + /** + * Creates the DB query. + * + * @param obj the obj + * @return the query builder + */ + public abstract QueryBuilder createDBQuery(Introspector obj); + + /** + * Creates the key query. + * + * @param obj the obj + * @return the query builder + */ + public abstract QueryBuilder createKeyQuery(Introspector obj); + + /** + * Creates the container query. + * + * @param obj the obj + * @return the query builder + */ + public abstract QueryBuilder createContainerQuery(Introspector obj); + + /** + * Creates the edge traversal. + * + * @param parent the parent + * @param child the child + * @return the query builder + */ + public abstract QueryBuilder createEdgeTraversal(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 abstract QueryBuilder createEdgeTraversal(EdgeType type, Vertex parent, Introspector child) throws AAIException; + + public QueryBuilder createEdgeTraversal(EdgeType type, String outNodeType, String inNodeType) throws NoEdgeRuleFoundException, AAIException { + Introspector out = loader.introspectorFromName(outNodeType); + Introspector in = loader.introspectorFromName(inNodeType); + + return createEdgeTraversal(type, out, in); + } + + public abstract QueryBuilder getEdgesBetween(EdgeType type, String outNodeType, String inNodeType) 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 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 getParentQuery(); + + /** + * Gets the query. + * + * @return the query + */ + public abstract E2 getQuery(); + + /** + * Form boundary. + */ + public abstract void markParentBoundary(); + + public abstract QueryBuilder limit(long amount); + /** + * New instance. + * + * @param start the start + * @return the query builder + */ + public abstract QueryBuilder newInstance(Vertex start); + + /** + * New instance. + * + * @return the query builder + */ + public abstract QueryBuilder 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 exactMatchQuery(Introspector obj); + + /** + * lets you join any number of QueryBuilders + * be careful about starting with a union it will not use indexes + * @param builder + * @return + */ + public abstract QueryBuilder union(QueryBuilder... builder); + + public abstract QueryBuilder where(QueryBuilder... builder); + + public abstract QueryBuilder store(String name); + public abstract QueryBuilder cap(String name); + public abstract QueryBuilder unfold(); + public abstract QueryBuilder dedup(); + public abstract QueryBuilder emit(); + public abstract QueryBuilder repeat(QueryBuilder builder); + public abstract QueryBuilder outE(); + public abstract QueryBuilder inE(); + public abstract QueryBuilder inV(); + public abstract QueryBuilder outV(); + public abstract QueryBuilder not(QueryBuilder builder); + public abstract QueryBuilder as(String name); + public abstract QueryBuilder select(String name); + public abstract QueryBuilder until(QueryBuilder builder); + + /** + * 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 simplePath(); + + public abstract void markContainer(); + + public abstract QueryBuilder getContainerQuery(); + + public abstract List toList(); + + +} 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 new file mode 100644 index 00000000..60e72aa5 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/query/builder/TraversalQuery.java @@ -0,0 +1,151 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.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.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; + +/** + * The Class TraversalQuery. + */ +public class TraversalQuery extends GraphTraversalBuilder { + + /** + * 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 traversal, Loader loader, GraphTraversalSource source, GraphTraversalBuilder 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 queryParams) + throws UnsupportedEncodingException, AAIException { + return factory.buildURIParser(uri, queryParams); + } + + /** + * @{inheritDoc} + */ + @Override + public QueryParser createQueryFromObjectName(String objName) { + return factory.buildObjectNameParser(objName); + } + + /** + * @{inheritDoc} + */ + @Override + public QueryBuilder newInstance(Vertex start) { + return new TraversalQuery<>(loader, source, start); + } + + /** + * @{inheritDoc} + */ + @Override + public QueryBuilder newInstance() { + return new TraversalQuery<>(loader, source); + } + + @Override + protected QueryBuilder cloneQueryAtStep(int index) { + if (index == 0) { + index = stepIndex; + } + GraphTraversal clone = this.traversal.asAdmin().clone(); + GraphTraversal.Admin cloneAdmin = clone.asAdmin(); + List steps = cloneAdmin.getSteps(); + + for (int i = steps.size()-1; i >= index; i--) { + cloneAdmin.removeStep(i); + } + return new TraversalQuery<>(cloneAdmin, loader, source, this); + } + + @Override + protected QueryBuilder removeQueryStepsBetween(int start, int end) { + GraphTraversal clone = this.traversal.asAdmin().clone(); + GraphTraversal.Admin 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/rest/RestTokens.java b/aai-core/src/main/java/org/onap/aai/rest/RestTokens.java new file mode 100644 index 00000000..d6e18027 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/rest/RestTokens.java @@ -0,0 +1,37 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.rest; + +public enum RestTokens { + + COUSIN("related-to"); + private final String name; + + private RestTokens(String name) { + this.name = 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 new file mode 100644 index 00000000..66edf15e --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/rest/db/DBRequest.java @@ -0,0 +1,252 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.rest.db; + +import java.net.URI; +import java.util.Optional; + +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.UriInfo; + +import org.onap.aai.introspection.Introspector; +import org.onap.aai.introspection.MarshallerProperties; +import org.onap.aai.parsers.query.QueryParser; +import org.onap.aai.restcore.HttpMethod; + +/** + * The Class DBRequest. + */ +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 rawRequestContent; + + private final Optional 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 getRawRequestContent() { + return rawRequestContent; + } + + public Optional 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 = Optional.empty(); + + private Optional 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 getMarshallerProperties() { + return marshallerProperties; + } + protected Optional 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 new file mode 100644 index 00000000..634e44e9 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/rest/db/HttpEntry.java @@ -0,0 +1,567 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.rest.db; + +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.lang.reflect.InvocationTargetException; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Set; + +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; +import javax.ws.rs.core.UriBuilder; + +import org.apache.commons.lang.StringUtils; +import org.apache.tinkerpop.gremlin.structure.Graph; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.javatuples.Pair; +import org.onap.aai.db.props.AAIProperties; +import org.onap.aai.dbmap.DBConnectionType; +import org.onap.aai.domain.responseMessage.AAIResponseMessage; +import org.onap.aai.domain.responseMessage.AAIResponseMessageDatum; +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.introspection.MarshallerProperties; +import org.onap.aai.introspection.ModelInjestor; +import org.onap.aai.introspection.ModelType; +import org.onap.aai.introspection.Version; +import org.onap.aai.introspection.exceptions.AAIUnknownObjectException; +import org.onap.aai.logging.ErrorLogHelper; +import org.onap.aai.parsers.query.QueryParser; +import org.onap.aai.parsers.uri.URIToExtensionInformation; +import org.onap.aai.rest.ueb.UEBNotification; +import org.onap.aai.restcore.HttpMethod; +import org.onap.aai.schema.enums.ObjectMetadata; +import org.onap.aai.serialization.db.DBSerializer; +import org.onap.aai.serialization.engines.QueryStyle; +import org.onap.aai.serialization.engines.TitanDBEngine; +import org.onap.aai.serialization.engines.TransactionalGraphEngine; +import org.onap.aai.serialization.engines.query.QueryEngine; + +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 com.thinkaurelius.titan.core.TitanException; + +/** + * The Class HttpEntry. + */ +public class HttpEntry { + + private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(HttpEntry.class); + + private final ModelType introspectorFactoryType; + + private final QueryStyle queryStyle; + + private final Version version; + + private final Loader loader; + + private final TransactionalGraphEngine dbEngine; + + private boolean processSingle = true; + + /** + * Instantiates a new http entry. + * + * @param version the version + * @param modelType the model type + * @param queryStyle the query style + * @param llBuilder the ll builder + */ + public HttpEntry(Version version, ModelType modelType, QueryStyle queryStyle, DBConnectionType connectionType) { + this.introspectorFactoryType = modelType; + this.queryStyle = queryStyle; + this.version = version; + this.loader = LoaderFactory.createLoaderForVersion(introspectorFactoryType, version); + this.dbEngine = new TitanDBEngine( + queryStyle, + connectionType, + loader); + //start transaction on creation + dbEngine.startTransaction(); + + } + + /** + * 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 Version 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>> process (List requests, String sourceOfTruth) throws AAIException { + return this.process(requests, sourceOfTruth, true); + } + /** + * Process. + * @param requests the requests + * @param sourceOfTruth the source of truth + * + * @return the pair + * @throws AAIException the AAI exception + */ + public Pair>> process (List requests, String sourceOfTruth, boolean enableResourceVersion) throws AAIException { + DBSerializer serializer = new DBSerializer(version, dbEngine, introspectorFactoryType, sourceOfTruth); + Response response = null; + Status status = Status.NOT_FOUND; + Introspector obj = null; + QueryParser query = null; + URI uri = null; + String transactionId = null; + UEBNotification notification = new UEBNotification(loader); + int depth = AAIProperties.MAXIMUM_DEPTH; + List> responses = new ArrayList<>(); + MultivaluedMap params = null; + HttpMethod method = null; + String uriTemp = ""; + Boolean success = true; + QueryEngine queryEngine = dbEngine.getQueryEngine(); + int maxRetries = 10; + int retry = 0; + for (DBRequest request : requests) { + try { + for (retry = 0; retry < maxRetries; ++retry) { + try { + method = request.getMethod(); + obj = request.getIntrospector(); + query = request.getParser(); + transactionId = request.getTransactionId(); + uriTemp = request.getUri().getRawPath().replaceFirst("^v\\d+/", ""); + uri = UriBuilder.fromPath(uriTemp).build(); + List 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")); + String cleanUp = params.getFirst("cleanup"); + String requestContext = ""; + List 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)) { + if (method.equals(HttpMethod.DELETE)) { + throw new AAIException("AAI_6138"); + } else { + 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(), (String)vertices.get(0).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 relatedObjects = new HashMap<>(); + switch (method) { + case GET: + String nodeOnly = params.getFirst("nodes-only"); + boolean isNodeOnly = nodeOnly != null; + + obj = this.getObjectFromDb(vertices, serializer, query, obj, request.getUri(), depth, isNodeOnly, cleanUp); + 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); + } + + break; + case PUT: + if (isNewVertex) { + v = serializer.createNewVertex(obj); + } + serializer.serializeToDb(obj, v, query, uri.getRawPath(), requestContext); + status = Status.OK; + if (isNewVertex) { + status = Status.CREATED; + } + obj = serializer.getLatestVersionView(v); + if (query.isDependent()) { + relatedObjects = this.getRelatedObjects(serializer, queryEngine, v); + } + notification.createNotificationEvent(transactionId, sourceOfTruth, status, uri, obj, relatedObjects); + break; + case PUT_EDGE: + serializer.touchStandardVertexProperties(v, false); + serializer.createEdge(obj, v); + status = Status.OK; + break; + case MERGE_PATCH: + Introspector existingObj = (Introspector) obj.clone(); + 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); + } + notification.createNotificationEvent(transactionId, sourceOfTruth, status, uri, patchedObj, relatedObjects); + } catch (IOException | JsonPatchException e) { + 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); + } + serializer.delete(v, resourceVersion, enableResourceVersion); + status = Status.NO_CONTENT; + notification.createNotificationEvent(transactionId, sourceOfTruth, status, uri, obj, relatedObjects); + break; + case DELETE_EDGE: + serializer.touchStandardVertexProperties(v, false); + serializer.deleteEdge(obj, v); + status = Status.NO_CONTENT; + 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)) + ) { + String myvertid = v.id().toString(); + 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 pairedResp = Pair.with(request.getUri(), response); + responses.add(pairedResp); + //break out of retry loop + break; + } catch (TitanException e) { + this.dbEngine.rollback(); + AAIException ex = new AAIException("AAI_6142", e); + ErrorLogHelper.logException(ex); + Thread.sleep((retry + 1) * 20); + 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 templateVars = new ArrayList(); + templateVars.add(request.getMethod().toString()); //GET, PUT, etc + templateVars.add(request.getUri().getPath().toString()); + templateVars.addAll(e.getTemplateVars()); + + response = Response + .status(e.getErrorObject().getHTTPResponseCode()) + .entity(ErrorLogHelper.getRESTAPIErrorResponse(request.getHeaders().getAcceptableMediaTypes(), e, templateVars)) + .build(); + Pair 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 templateVars = new ArrayList(); + templateVars.add(request.getMethod().toString()); //GET, PUT, etc + templateVars.add(request.getUri().getPath().toString()); + + response = Response + .status(ex.getErrorObject().getHTTPResponseCode()) + .entity(ErrorLogHelper.getRESTAPIErrorResponse(request.getHeaders().getAcceptableMediaTypes(), ex, templateVars)) + .build(); + Pair pairedResp = Pair.with(request.getUri(), response); + responses.add(pairedResp); + continue; + } + } + + notification.triggerEvents(); + Pair>> tuple = Pair.with(success, responses); + return tuple; + } + + /** + * Gets the media type. + * + * @param mediaTypeList the media type list + * @return the media type + */ + private String getMediaType(List 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 g the g + * @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 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.size() == 0) { + String msg = createNotFoundMessage(query.getResultType(), uri); + throw new AAIException("AAI_6114", msg); + } + + obj = serializer.dbToObject(results, obj, depth, nodeOnly, cleanUp); + + return obj; + } + + + /** + * 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; + } + + /** + * 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; + + if(depthParam == null){ + if(this.version.compareTo(Version.v9) >= 0){ + depth = 0; + } else { + depth = AAIProperties.MAXIMUM_DEPTH; + } + } else { + if (depthParam.length() > 0 && !depthParam.equals("all")){ + try { + depth = Integer.valueOf(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; + + } + + private HashMap getRelatedObjects(DBSerializer serializer, QueryEngine queryEngine, Vertex v) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException, InstantiationException, NoSuchMethodException, UnsupportedEncodingException, AAIException, URISyntaxException { + HashMap relatedVertices = new HashMap<>(); + List vertexChain = queryEngine.findParents(v); + 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"); + } + + } + + return relatedVertices; + } + +} 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 new file mode 100644 index 00000000..00678fb9 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/rest/ueb/NotificationEvent.java @@ -0,0 +1,100 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.rest.ueb; + +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.Introspector; +import org.onap.aai.introspection.Loader; +import org.onap.aai.introspection.Version; +import org.onap.aai.util.StoreNotificationEvent; + +/** + * The Class NotificationEvent. + */ +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 version the version + * @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 Version 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 new file mode 100644 index 00000000..1ada5036 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/rest/ueb/UEBNotification.java @@ -0,0 +1,177 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.rest.ueb; + +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +import javax.ws.rs.core.Response.Status; + +import org.onap.aai.db.props.AAIProperties; +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.introspection.Version; +import org.onap.aai.introspection.exceptions.AAIUnknownObjectException; +import org.onap.aai.introspection.exceptions.AAIUnmarshallingException; +import org.onap.aai.parsers.uri.URIToObject; +import org.onap.aai.util.AAIConfig; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +/** + * The Class UEBNotification. + */ +public class UEBNotification { + + private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(UEBNotification.class); + + private Loader currentVersionLoader = null; + protected List events = null; + private Version notificationVersion = null; + + /** + * Instantiates a new UEB notification. + * + * @param loader the loader + */ + public UEBNotification(Loader loader) { + events = new ArrayList<>(); + currentVersionLoader = LoaderFactory.createLoaderForVersion(loader.getModelType(), AAIProperties.LATEST); + notificationVersion = Version.valueOf(AAIConfig.get("aai.notification.current.version","v11")); + } + + + /** + * Creates the notification event. + * + * @param transactionId the X-TransactionId + * @param sourceOfTruth + * @param status the status + * @param uri the uri + * @param obj the obj + * @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 relatedObjects) 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 (uri.toString().startsWith("/")) { + entityLink = "/aai/" + notificationVersion + uri; + } else { + entityLink = "/aai/" + 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 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", e); + } + } + + /** + * Trigger events. + * + * @throws AAIException the AAI exception + */ + public void triggerEvents() throws AAIException { + for (NotificationEvent event : events) { + event.trigger(); + } + events.clear(); + } + + public List 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 new file mode 100644 index 00000000..9072323c --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/restcore/CustomJacksonJaxBJsonProvider.java @@ -0,0 +1,72 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.restcore; + +import javax.ws.rs.ext.Provider; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider; +import com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule; + +/** + * The Class CustomJacksonJaxBJsonProvider. + */ +@Provider +public class CustomJacksonJaxBJsonProvider extends JacksonJaxbJsonProvider { + + 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); + + 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.registerModule(new JaxbAnnotationModule()); + + commonMapper = mapper; + } + super.setMapper(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 new file mode 100644 index 00000000..e7c8d215 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/restcore/HttpMethod.java @@ -0,0 +1,34 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.restcore; + +/** + * The Enum HttpMethod. + */ +public enum HttpMethod { + PUT, + MERGE_PATCH, + DELETE, + PUT_EDGE, + DELETE_EDGE, + GET; +} 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 new file mode 100644 index 00000000..920a85ae --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/restcore/JettyObfuscationConversionCommandLineUtil.java @@ -0,0 +1,98 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.restcore; + +import org.apache.commons.cli.BasicParser; +import org.apache.commons.cli.CommandLine; +import org.apache.commons.cli.CommandLineParser; +import org.apache.commons.cli.Options; +import org.apache.commons.cli.ParseException; +import org.eclipse.jetty.util.security.Password; + +/* + * The purpose of this class is to be a tool for + * manually applying jetty obfuscation/deobfuscation + * so that one can obfuscate the various passwords/secrets + * in aaiconfig.properties. + * + * Originally, they were being encrypted by a similar + * command line utility, however the encryption key + * was being hardcoded in the src package + * which is a security violation. + * Since this ultimately just moved the problem of how + * to hide secrets to a different secret in a different file, + * and since that encryption was really just being done to + * obfuscate those values in case someone needed to look at + * properties with others looking at their screen, + * we decided that jetty obfuscation would be adequate + * for that task as well as + * removing the "turtles all the way down" secret-to-hide- + * 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"); + } +} 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 new file mode 100644 index 00000000..89be23e5 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/restcore/MediaType.java @@ -0,0 +1,67 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.restcore; + +/** + * The Enum MediaType. + */ +public enum MediaType { + APPLICATION_JSON_TYPE("application/json"), + APPLICATION_XML_TYPE("application/xml"); + + private final String text; + + /** + * Instantiates a new media type. + * + * @param text the text + */ + private MediaType(final String text) { + this.text = text; + } + + /** + * Gets the enum. + * + * @param value the value + * @return the enum + */ + public static MediaType getEnum(String value) { + + for(MediaType v : values()) { + if(v.toString().equalsIgnoreCase(value)) { + return v; + } + } + + throw new IllegalArgumentException("bad value: " + value); + + } + + /** + * @{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 new file mode 100644 index 00000000..3895f626 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/restcore/RESTAPI.java @@ -0,0 +1,278 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.restcore; + +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.util.ArrayList; +import java.util.List; + +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriInfo; + +import org.onap.aai.db.props.AAIProperties; +import org.onap.aai.dbmap.DBConnectionType; +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.Introspector; +import org.onap.aai.introspection.Loader; +import org.onap.aai.introspection.tools.CreateUUID; +import org.onap.aai.introspection.tools.DefaultFields; +import org.onap.aai.introspection.tools.InjectKeysFromURI; +import org.onap.aai.introspection.tools.IntrospectorValidator; +import org.onap.aai.introspection.tools.Issue; +import org.onap.aai.introspection.tools.RemoveNonVisibleProperty; +import org.onap.aai.logging.ErrorLogHelper; +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 + * @param logline the logline + * @return the from app id + * @throws AAIException the AAI exception + */ + protected String getFromAppId(HttpHeaders headers) throws AAIException { + String fromAppId = null; + if (headers != null) { + List 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 + * @param logline the logline + * @return the trans id + * @throws AAIException the AAI exception + */ + protected String getTransId(HttpHeaders headers) throws AAIException { + String transId = null; + if (headers != null) { + List 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 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 templateVars = new ArrayList(); + templateVars.add(templateAction.toString()); //GET, PUT, etc + templateVars.add(info.getPath().toString()); + templateVars.addAll(e.getTemplateVars()); + + 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 + * @param validateRequired the validate required + * @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 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 + String testURI = "/" + uri.getRawPath(); + if (!testURI.endsWith(objURI)) { + throw new AAIException("AAI_3000", "uri and payload keys don't match"); + } + } + + protected DBConnectionType determineConnectionType(String fromAppId, String realTime) { + 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; + + } + +} diff --git a/aai-core/src/main/java/org/onap/aai/restcore/search/GremlinGroovyShellSingleton.java b/aai-core/src/main/java/org/onap/aai/restcore/search/GremlinGroovyShellSingleton.java new file mode 100644 index 00000000..7eb600d2 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/restcore/search/GremlinGroovyShellSingleton.java @@ -0,0 +1,91 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.restcore.search; + +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; +import org.codehaus.groovy.ast.expr.PropertyExpression; +import org.codehaus.groovy.control.CompilerConfiguration; +import org.codehaus.groovy.control.customizers.ASTTransformationCustomizer; +import org.codehaus.groovy.control.customizers.ImportCustomizer; + +import groovy.lang.Binding; +import groovy.lang.GroovyShell; +import groovy.lang.Script; +import groovy.transform.TimedInterrupt; + +/** + * Creates and returns a groovy shell with the + * configuration to statically import graph classes + * + */ +public class GremlinGroovyShellSingleton { + + private final GroovyShell shell; + private GremlinGroovyShellSingleton() { + Map 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" + ); + imports.addImports( + "org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__", + "org.apache.tinkerpop.gremlin.structure.T", + "org.apache.tinkerpop.gremlin.process.traversal.P", + "java.util.Map.Entry"); + imports.addStarImports("java.util"); + CompilerConfiguration config = new CompilerConfiguration(); + config.addCompilationCustomizers(custom, imports); + + this.shell = new GroovyShell(config); + } + + private static class Helper { + private static final GremlinGroovyShellSingleton INSTANCE = new GremlinGroovyShellSingleton(); + } + + public static GremlinGroovyShellSingleton getInstance() { + + return Helper.INSTANCE; + } + + /** + * @param traversal + * @param params + * @return result of graph traversal + */ + public GraphTraversal executeTraversal (String traversal, Map params) { + Binding binding = new Binding(params); + Script script = shell.parse(traversal); + script.setBinding(binding); + return (GraphTraversal) script.run(); + } +} diff --git a/aai-core/src/main/java/org/onap/aai/restcore/util/GenerateEdgeRules.java b/aai-core/src/main/java/org/onap/aai/restcore/util/GenerateEdgeRules.java new file mode 100644 index 00000000..1b854667 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/restcore/util/GenerateEdgeRules.java @@ -0,0 +1,155 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.restcore.util; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import freemarker.template.Configuration; +import freemarker.template.Template; +import freemarker.template.TemplateException; + +import java.io.*; +import java.util.*; + +public class GenerateEdgeRules { + + private static final EELFLogger LOG = EELFManager.getInstance().getLogger(GenerateEdgeRules.class); + + public static void main(String[] args) throws IOException, TemplateException { + + String filename = "/AAI8032.csv"; + InputStream inputStream = GenerateEdgeRules.class.getResourceAsStream(filename); + Map headers = new HashMap<>(); + Map edgeRulesMap = new TreeMap(); + List> edgeRules = new ArrayList<>(); + + try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) { + + String line = null; + + int rowNum = 0; + + // Retrieve the header line to map the indexes to their column names + + while ((line = reader.readLine()) != null) { + + if (rowNum == 0) { + headers = retrieveHeaderMap(line); + } else { + String[] columns = line.split(","); + + String originalNode = columns[headers.get("Orig NodeA|NodeB")]; + String finalNode = columns[headers.get("Final NodeA|NodeB")]; + String originalEdge = columns[headers.get("Orig EdgeLabel")]; + String finalEdge = columns[headers.get("Final EdgeLabel")]; + + String lineage = columns[headers.get("Final Lineage")]; + String originalParent = columns[headers.get("Orig ParentOf")]; + String usesResource = columns[headers.get("Revised UsesResource")]; + String hasDelTarget = columns[headers.get("Revised hasDelTarget")]; + String svcInfra = columns[headers.get("Final SVC-INFRA")]; + String svcInfraRev = ""; + + if(usesResource.equals("T")) + usesResource = "true"; + else if(usesResource.equals("F")) + usesResource = "false"; + + if (hasDelTarget.equals("T") || hasDelTarget.equals("AB")) { + hasDelTarget = "true"; + } else if (hasDelTarget.equals("F")) { + hasDelTarget = "false"; + } + + if (svcInfra.equals("T")) { + svcInfra = "true"; + } else if (svcInfra.equals("F")) { + svcInfra = "false"; + } else if (svcInfra.equals("R")) { + svcInfra = "reverse"; + } + + if (originalParent.equals("T")) { + if (lineage.trim().equalsIgnoreCase("CHILD")) { + lineage = "true"; + } else if (lineage.trim().equalsIgnoreCase("PARENT")) { + lineage = "reverse"; + } + } else { + lineage = "false"; + } + + Map edgeMap = new HashMap(); + + edgeMap.put("lineage", lineage); + edgeMap.put("usesResource", usesResource); + edgeMap.put("hasDelTarget", hasDelTarget); + edgeMap.put("SVC-INFRA", svcInfra); + edgeMap.put("SVC-INFRA-REV", svcInfraRev); + edgeMap.put("nodes", finalNode); + edgeMap.put("edge", finalEdge); + edgeMap.put("direction", columns[headers.get("Orig Direction")]); + edgeMap.put("multiplicity", columns[headers.get("Revised Multiplicity")]); + + edgeRules.add(edgeMap); + + } + ++rowNum; + } + } catch(Exception ex){ + ex.printStackTrace(); + } + + edgeRulesMap.put("edgeRules", edgeRules); + + Collections.sort(edgeRules, new Comparator>() { + @Override + public int compare(Map o1, Map o2) { + return o1.get("nodes").compareTo(o2.get("nodes")); + } + }); + + Configuration configuration = new Configuration(); + Template template = configuration.getTemplate("ajsc-aai/src/main/resources/EdgeRules.ftl"); + Writer file = new FileWriter(new File("ajsc-aai/src/main/resources" + "/" + "EdgeRules.txt")); + template.process(edgeRulesMap, file); + } + + private static Map retrieveHeaderMap(String line){ + + if(line == null) + throw new NullPointerException(); + + String[] columnNames = line.split(","); + + Map map = new HashMap(); + + int index = 0; + + for(String columnName : columnNames){ + map.put(columnName, index++); + } + + return map; + } + +} 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 new file mode 100644 index 00000000..9889a567 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/restcore/util/URITools.java @@ -0,0 +1,114 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.restcore.util; + +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.util.HashMap; +import java.util.LinkedHashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Optional; +import java.util.Set; +import java.util.regex.Matcher; +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; + +public class URITools { + + protected static final Pattern template = Pattern.compile("\\{(.*?)\\}"); + + public static MultivaluedMap getQueryMap(URI uri) { + MultivaluedMap 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"); + 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 replaceTemplates(Introspector obj, String uriString, PropertyMetadata metadata, boolean replaceWithWildcard) throws AAIMissingRequiredPropertyException { + String result = uriString; + final Map propMap = URITools.findProperties(obj, uriString, metadata, replaceWithWildcard); + if (propMap.isEmpty()) { + return Optional.empty(); + } + for (Entry 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 findProperties(Introspector obj, String uriString, PropertyMetadata metadata, boolean replaceWithWildcard) throws AAIMissingRequiredPropertyException { + + final Map result = new HashMap<>(); + final Set 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/AAIDirection.java b/aai-core/src/main/java/org/onap/aai/serialization/db/AAIDirection.java new file mode 100644 index 00000000..1dce588d --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/serialization/db/AAIDirection.java @@ -0,0 +1,35 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.serialization.db; + +public enum AAIDirection { + IN, OUT, BOTH, NONE; + + public AAIDirection opposite() { + if (this.equals(OUT)) + return IN; + else if (this.equals(IN)) + return OUT; + else + return BOTH; + } +} 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 new file mode 100644 index 00000000..dd073dc7 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/serialization/db/DBSerializer.java @@ -0,0 +1,1444 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.serialization.db; + + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.google.common.base.CaseFormat; +import com.thinkaurelius.titan.core.SchemaViolationException; +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.__; +import org.apache.tinkerpop.gremlin.process.traversal.step.util.Tree; +import org.apache.tinkerpop.gremlin.structure.*; +import org.javatuples.Pair; +import org.onap.aai.db.props.AAIProperties; +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.*; +import org.onap.aai.introspection.exceptions.AAIUnknownObjectException; +import org.onap.aai.introspection.sideeffect.DataCopy; +import org.onap.aai.introspection.sideeffect.DataLinkReader; +import org.onap.aai.introspection.sideeffect.DataLinkWriter; +import org.onap.aai.introspection.sideeffect.SideEffectRunner; +import org.onap.aai.logging.ErrorLogHelper; +import org.onap.aai.parsers.query.QueryParser; +import org.onap.aai.parsers.uri.URIParser; +import org.onap.aai.parsers.uri.URIToRelationshipObject; +import org.onap.aai.query.builder.QueryBuilder; +import org.onap.aai.schema.enums.ObjectMetadata; +import org.onap.aai.schema.enums.PropertyMetadata; +import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException; +import org.onap.aai.serialization.engines.TransactionalGraphEngine; +import org.onap.aai.serialization.tinkerpop.TreeBackedVertex; +import org.onap.aai.util.AAIApiServerURLBase; +import org.onap.aai.util.AAIConfig; +import org.onap.aai.util.AAIConstants; +import org.onap.aai.workarounds.NamingExceptions; + +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.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Future; + +public class DBSerializer { + + private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(DBSerializer.class); + + private final TransactionalGraphEngine engine; + private final String sourceOfTruth; + private final ModelType introspectionType; + private final Version version; + private final Loader latestLoader; + private final EdgeRules edgeRules = EdgeRules.getInstance(); + private final Loader loader; + private final String baseURL; + /** + * Instantiates a new DB serializer. + * + * @param version the version + * @param engine the engine + * @param g the g + * @param introspectionType the introspection type + * @param sourceOfTruth the source of truth + * @param llBuilder the ll builder + * @throws AAIException + */ + public DBSerializer(Version version, TransactionalGraphEngine engine, ModelType introspectionType, String sourceOfTruth) throws AAIException { + this.engine = engine; + this.sourceOfTruth = sourceOfTruth; + this.introspectionType = introspectionType; + this.latestLoader = LoaderFactory.createLoaderForVersion(introspectionType, AAIProperties.LATEST); + this.version = version; + this.loader = LoaderFactory.createLoaderForVersion(introspectionType, version); + this.baseURL = AAIApiServerURLBase.get(version); + } + + /** + * Touch standard vertex properties. + * + * @param v the v + * @param isNewVertex the is new vertex + */ + public void touchStandardVertexProperties(Vertex v, boolean isNewVertex) { + + long unixTimeNow = System.currentTimeMillis(); + String timeNowInSec = "" + unixTimeNow; + if (isNewVertex) { + v.property(AAIProperties.SOURCE_OF_TRUTH, this.sourceOfTruth); + v.property(AAIProperties.CREATED_TS, timeNowInSec); + } + v.property(AAIProperties.RESOURCE_VERSION, timeNowInSec ); + v.property(AAIProperties.LAST_MOD_TS, timeNowInSec); + v.property(AAIProperties.LAST_MOD_SOURCE_OF_TRUTH, this.sourceOfTruth); + + } + + private void touchStandardVertexProperties(String nodeType, Vertex v, boolean isNewVertex) { + + v.property(AAIProperties.NODE_TYPE, nodeType); + touchStandardVertexProperties(v, isNewVertex); + + } + + + + /** + * Creates the new vertex. + * + * @param wrappedObject the wrapped object + * @return the vertex + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + public Vertex createNewVertex(Introspector wrappedObject) { + + + Vertex v = this.engine.tx().addVertex(); + touchStandardVertexProperties(wrappedObject.getDbName(), v, true); + + return v; + } + + /** + * Trim class name. + * + * @param className the class name + * @return the string + */ + /* + * Removes the classpath from a class name + */ + public String trimClassName (String className) { + String returnValue = ""; + + if (className.lastIndexOf('.') == -1) { + return className; + } + returnValue = className.substring(className.lastIndexOf('.') + 1, className.length()); + + return returnValue; + } + + /** + * Serialize to db. + * + * @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 UnsupportedEncodingException the unsupported encoding exception + * @throws AAIUnknownObjectException + */ + public void serializeToDb(Introspector obj, Vertex v, QueryParser uriQuery, String identifier, String requestContext) throws AAIException, UnsupportedEncodingException { + + try { + if (uriQuery.isDependent()) { + //try to find the parent + List vertices = uriQuery.getQueryBuilder().getParentQuery().toList(); + if (!vertices.isEmpty()) { + Vertex parent = vertices.get(0); + this.reflectDependentVertex(parent, v, obj, requestContext); + } else { + throw new AAIException("AAI_6114", "No parent Node of type " + uriQuery.getParentResultType() + " for " + identifier); + } + } else { + serializeSingleVertex(v, obj, requestContext); + } + + } catch (SchemaViolationException e) { + throw new AAIException("AAI_6117", e); + } + + } + + public void serializeSingleVertex(Vertex v, Introspector obj, String requestContext) throws UnsupportedEncodingException, AAIException { + try { + boolean isTopLevel = obj.isTopLevel(); + if (isTopLevel) { + v.property(AAIProperties.AAI_URI, obj.getURI()); + } + processObject(obj, v, requestContext); + if (!isTopLevel) { + URI uri = this.getURIForVertex(v); + URIParser parser = new URIParser(this.loader, uri); + if (parser.validate()) { + VertexProperty uriProp = v.property(AAIProperties.AAI_URI); + if (!uriProp.isPresent() || uriProp.isPresent() && !uriProp.value().equals(uri.toString())) { + v.property(AAIProperties.AAI_URI, uri.toString()); + } + } + } + } catch (SchemaViolationException e) { + throw new AAIException("AAI_6117", e); + } + } + + /** + * Process object. + * + * @param the generic type + * @param obj the obj + * @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 UnsupportedEncodingException the unsupported encoding exception + * @throws AAIUnknownObjectException + */ + /* + * Helper method for reflectToDb + * Handles all the property setting + */ + private List processObject (Introspector obj, Vertex v, String requestContext) throws UnsupportedEncodingException, AAIException { + Set properties = new LinkedHashSet<>(obj.getProperties()); + properties.remove(AAIProperties.RESOURCE_VERSION); + List dependentVertexes = new ArrayList<>(); + List processedVertexes = new ArrayList<>(); + boolean isComplexType = false; + boolean isListType = false; + if (!obj.isContainer()) { + this.touchStandardVertexProperties(obj.getDbName(), v, false); + } + this.executePreSideEffects(obj, v); + for (String property : properties) { + Object value = null; + final String propertyType; + propertyType = obj.getType(property); + isComplexType = obj.isComplexType(property); + isListType = obj.isListType(property); + value = obj.getValue(property); + + if (!(isComplexType || isListType)) { + boolean canModify = this.canModify(obj, property, requestContext); + + if (canModify) { + final Map metadata = obj.getPropertyMetadata(property); + String dbProperty = property; + if (metadata.containsKey(PropertyMetadata.DB_ALIAS)) { + dbProperty = metadata.get(PropertyMetadata.DB_ALIAS); + } + if (metadata.containsKey(PropertyMetadata.DATA_LINK)) { + //data linked properties are ephemeral + //they are populated dynamically on GETs + continue; + } + if (value != null) { + if (!value.equals(v.property(dbProperty).orElse(null))) { + if (propertyType.toLowerCase().contains(".long")) { + v.property(dbProperty, new Integer(((Long)value).toString())); + } else { + v.property(dbProperty, value); + } + } + } else { + v.property(dbProperty).remove(); + } + } + } else if (isListType) { + List list = (List)value; + if (obj.isComplexGenericType(property)) { + if (list != null) { + for (Object o : list) { + Introspector child = IntrospectorFactory.newInstance(this.introspectionType, o); + child.setURIChain(obj.getURI()); + processedVertexes.add(reflectDependentVertex(v, child, requestContext)); + } + } + } else { + //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 + if (value.getClass().isArray()) { + + int length = Array.getLength(value); + for (int i = 0; i < length; i ++) { + Object arrayElement = Array.get(value, i); + Introspector child = IntrospectorFactory.newInstance(this.introspectionType, arrayElement); + child.setURIChain(obj.getURI()); + processedVertexes.add(reflectDependentVertex(v, child, requestContext)); + + } + } else if (!property.equals("relationship-list")) { + // container case + Introspector introspector = IntrospectorFactory.newInstance(this.introspectionType, value); + if (introspector.isContainer()) { + 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())); + processedVertexes.add(reflectDependentVertex(v, introspector, requestContext)); + + } + } else if (property.equals("relationship-list")) { + handleRelationships(obj, v); + } + } + } + } + this.writeThroughDefaults(v, obj); + /* handle those vertexes not touched */ + for (Vertex toBeRemoved : processedVertexes) { + dependentVertexes.remove(toBeRemoved); + } + this.deleteItemsWithTraversal(dependentVertexes); + + this.executePostSideEffects(obj, v); + return processedVertexes; + } + + /** + * Handle relationships. + * + * @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 UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + /* + * Handles the explicit relationships defined for an obj + */ + 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 + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + private void processRelationshipList(Introspector wrapped, Vertex v) throws UnsupportedEncodingException, AAIException { + + List relationships = (List)wrapped.getValue("relationship"); + + List> addEdges = new ArrayList<>(); + List existingEdges = this.engine.getQueryEngine().findEdgesForVersion(v, wrapped.getLoader()); + + for (Object relationship : relationships) { + Edge e = null; + Vertex cousinVertex = null; + Introspector wrappedRel = IntrospectorFactory.newInstance(this.introspectionType, relationship); + QueryParser parser = engine.getQueryBuilder().createQueryFromRelationship(wrappedRel); + + List 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()); + ex.getTemplateVars().add(parser.getResultType()); + ex.getTemplateVars().add(parser.getUri().toString()); + throw ex; + } else { + //still an issue if there's more than one + cousinVertex = results.get(0); + } + + if (cousinVertex != null) { + try { + if (!edgeRules.hasEdgeRule(v, cousinVertex)) { + 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() + "."); + } + e = this.getEdgeBetween(EdgeType.COUSIN, v, cousinVertex); + + if (e == null) { + addEdges.add(new Pair<>(v, cousinVertex)); + } else { + existingEdges.remove(e); + } + } catch (NoEdgeRuleFoundException e1) { + throw new AAIException("AAI_6145"); + } + } + } + + for (Edge edge : existingEdges) { + edge.remove(); + } + for (Pair pair : addEdges) { + try { + edgeRules.addEdge(this.engine.asAdmin().getTraversalSource(), pair.getValue0(), pair.getValue1()); + } catch (NoEdgeRuleFoundException e) { + throw new AAIException("AAI_6129", e); + } + } + + } + + /** + * Write through defaults. + * + * @param v the v + * @param obj the obj + * @throws AAIUnknownObjectException + */ + private void writeThroughDefaults(Vertex v, Introspector obj) throws AAIUnknownObjectException { + Introspector latest = this.latestLoader.introspectorFromName(obj.getName()); + if (latest != null) { + Set required = latest.getRequiredProperties(); + + for (String field : required) { + String defaultValue = null; + Object vertexProp = null; + defaultValue = latest.getPropertyMetadata(field).get(PropertyMetadata.DEFAULT_VALUE); + if (defaultValue != null) { + vertexProp = v.property(field).orElse(null); + if (vertexProp == null) { + v.property(field, defaultValue); + } + } + } + } + + } + + + /** + * Reflect dependent vertex. + * + * @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 UnsupportedEncodingException the unsupported encoding exception + * @throws AAIUnknownObjectException + */ + private Vertex reflectDependentVertex(Vertex v, Introspector dependentObj, String requestContext) throws AAIException, UnsupportedEncodingException { + + //QueryParser p = this.engine.getQueryBuilder().createQueryFromURI(obj.getURI()); + //List items = p.getQuery().toList(); + QueryBuilder query = this.engine.getQueryBuilder(v); + query.createEdgeTraversal(EdgeType.TREE, v, dependentObj); + query.createKeyQuery(dependentObj); + + List items = query.toList(); + + Vertex dependentVertex = null; + if (items.size() == 1) { + dependentVertex = items.get(0); + this.verifyResourceVersion("update", dependentObj.getDbName(), dependentVertex.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()); + dependentVertex = createNewVertex(dependentObj); + } + + return reflectDependentVertex(v, dependentVertex, dependentObj, requestContext); + + } + + /** + * Reflect dependent vertex. + * + * @param parent the parent + * @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 UnsupportedEncodingException the unsupported encoding exception + * @throws AAIUnknownObjectException + */ + private Vertex reflectDependentVertex(Vertex parent, Vertex child, Introspector obj, String requestContext) throws AAIException, UnsupportedEncodingException { + + String parentUri = parent.property(AAIProperties.AAI_URI).orElse(null); + if (parentUri != null) { + String uri; + uri = obj.getURI(); + child.property(AAIProperties.AAI_URI, parentUri + uri); + } + processObject(obj, child, requestContext); + + Edge e; + e = this.getEdgeBetween(EdgeType.TREE, parent, child); + if (e == null) { + String canBeLinked = obj.getMetadata(ObjectMetadata.CAN_BE_LINKED); + if (canBeLinked != null && canBeLinked.equals("true")) { + boolean isFirst = !this.engine.getQueryBuilder(parent).createEdgeTraversal(EdgeType.TREE, parent, obj).hasNext(); + if (isFirst) { + child.property(AAIProperties.LINKED, true); + } + } + edgeRules.addTreeEdge(this.engine.asAdmin().getTraversalSource(), parent, child); + } + return child; + + } + + /** + * Db to object. + * + * @param vertices the vertices + * @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 UnsupportedEncodingException the unsupported encoding exception + * @throws MalformedURLException the malformed URL exception + * @throws AAIUnknownObjectException + * @throws URISyntaxException + */ + public Introspector dbToObject(List vertices, final Introspector obj, int depth, boolean nodeOnly, String cleanUp) throws UnsupportedEncodingException, AAIException { + + final int internalDepth; + if (depth == Integer.MAX_VALUE) { + internalDepth = depth--; + } else { + internalDepth = depth; + } + if (vertices.size() > 1 && !obj.isContainer()) { + 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; + for (String property : obj.getProperties()) { + if (obj.isListType(property) && obj.isComplexGenericType(property)) { + listProperty = property; + break; + } + } + final String propertyName = listProperty; + getList = (List)obj.getValue(listProperty); + + /* This is an experimental multithreading experiment + * on get alls. + */ + ExecutorService pool = GetAllPool.getInstance().getPool(); + + List> futures = new ArrayList<>(); + for (Vertex v : vertices) { + Callable task = () -> { + Set seen = new HashSet<>(); + Introspector childObject = obj.newIntrospectorInstanceOfNestedProperty(propertyName); + Tree tree = this.engine.getQueryEngine().findSubGraph(v, internalDepth, nodeOnly); + TreeBackedVertex treeVertex = new TreeBackedVertex(v, tree); + dbToObject(childObject, treeVertex, seen, internalDepth, nodeOnly, cleanUp); + return childObject.getUnderlyingObject(); + //getList.add(childObject.getUnderlyingObject()); + }; + futures.add(pool.submit(task)); + } + + for (Future future : futures) { + try { + getList.add(future.get()); + } catch (ExecutionException e) { + throw new AAIException("AAI_4000", e); + } catch (InterruptedException e) { + throw new AAIException("AAI_4000", e); + } + } + } else if (vertices.size() == 1) { + Set seen = new HashSet<>(); + Tree tree = this.engine.getQueryEngine().findSubGraph(vertices.get(0), depth, nodeOnly); + TreeBackedVertex treeVertex = new TreeBackedVertex(vertices.get(0), tree); + dbToObject(obj, treeVertex, seen, depth, nodeOnly, cleanUp); + } else { + //obj = null; + } + + + return obj; + } + + /** + * Db to object. + * + * @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 UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + * @throws MalformedURLException the malformed URL exception + * @throws AAIUnknownObjectException + * @throws URISyntaxException + */ + private Introspector dbToObject(Introspector obj, Vertex v, Set seen, int depth, boolean nodeOnly, String cleanUp) throws AAIException, UnsupportedEncodingException { + + if (depth < 0) { + return null; + } + depth--; + seen.add(v); + + boolean modified = false; + for (String property : obj.getProperties(PropertyPredicates.isVisible())) { + List getList = null; + Vertex[] vertices = null; + + if (!(obj.isComplexType(property) || obj.isListType(property))) { + this.copySimpleProperty(property, obj, v); + modified = true; + } else { + if (obj.isComplexType(property)) { + /* container case */ + + if (!property.equals("relationship-list") && depth >= 0) { + Introspector argumentObject = obj.newIntrospectorInstanceOfProperty(property); + Object result = dbToObject(argumentObject, v, seen, depth+1, nodeOnly, cleanUp); + if (result != null) { + obj.setValue(property, argumentObject.getUnderlyingObject()); + modified = true; + } + } else if (property.equals("relationship-list") && !nodeOnly){ + /* relationships need to be handled correctly */ + Introspector relationshipList = obj.newIntrospectorInstanceOfProperty(property); + relationshipList = createRelationshipList(v, relationshipList, cleanUp); + if (relationshipList != null) { + modified = true; + obj.setValue(property, relationshipList.getUnderlyingObject()); + modified = true; + } + + } + } else if (obj.isListType(property)) { + + if (property.equals("any")) { + continue; + } + String genericType = obj.getGenericTypeClass(property).getSimpleName(); + if (obj.isComplexGenericType(property) && depth >= 0) { + final String childDbName = convertFromCamelCase(genericType); + String vType = v.property(AAIProperties.NODE_TYPE).orElse(null); + EdgeRule rule; + + rule = edgeRules.getEdgeRule(EdgeType.TREE, vType, childDbName); + if (!rule.getContains().equals(AAIDirection.NONE.toString())) { + //vertices = this.queryEngine.findRelatedVertices(v, Direction.OUT, rule.getLabel(), childDbName); + Direction ruleDirection = rule.getDirection(); + Iterator itr = v.vertices(ruleDirection, rule.getLabel()); + List verticesList = (List)IteratorUtils.toList(itr); + itr = verticesList.stream().filter(item -> { + return item.property(AAIProperties.NODE_TYPE).orElse("").equals(childDbName); + }).iterator(); + if (itr.hasNext()) { + getList = (List)obj.getValue(property); + } + int processed = 0; + int removed = 0; + while (itr.hasNext()) { + Vertex childVertex = itr.next(); + if (!seen.contains(childVertex)) { + Introspector argumentObject = obj.newIntrospectorInstanceOfNestedProperty(property); + + Object result = dbToObject(argumentObject, childVertex, seen, depth, nodeOnly, cleanUp); + if (result != null && getList != null) { + getList.add(argumentObject.getUnderlyingObject()); + } + + processed++; + } else { + removed++; + LOGGER.warn("Cycle found while serializing vertex id={}", childVertex.id().toString()); + } + } + if (processed == 0) { + //vertices were all seen, reset the list + getList = null; + } + if (processed > 0) { + modified = true; + } + } + } else if (obj.isSimpleGenericType(property)) { + List temp = this.engine.getListProperty(v, property); + if (temp != null) { + getList = (List)obj.getValue(property); + getList.addAll(temp); + modified = true; + } + + } + + } + + } + } + + //no changes were made to this obj, discard the instance + if (!modified) { + return null; + } + this.enrichData(obj, v); + return obj; + + } + + + public Introspector getVertexProperties(Vertex v) throws AAIException, UnsupportedEncodingException { + String nodeType = v.property(AAIProperties.NODE_TYPE).orElse(null); + if (nodeType == null) { + throw new AAIException("AAI_6143"); + } + Introspector obj = this.latestLoader.introspectorFromName(nodeType); + Set seen = new HashSet<>(); + int depth = 0; + String cleanUp = "false"; + boolean nodeOnly = true; + this.dbToObject(obj, v, seen, depth, nodeOnly, cleanUp); + + return obj; + + } + public Introspector getLatestVersionView(Vertex v) throws AAIException, UnsupportedEncodingException { + String nodeType = v.property(AAIProperties.NODE_TYPE).orElse(null); + if (nodeType == null) { + throw new AAIException("AAI_6143"); + } + Introspector obj = this.latestLoader.introspectorFromName(nodeType); + Set seen = new HashSet<>(); + int depth = AAIProperties.MAXIMUM_DEPTH; + String cleanUp = "false"; + boolean nodeOnly = false; + Tree tree = this.engine.getQueryEngine().findSubGraph(v, depth, nodeOnly); + TreeBackedVertex treeVertex = new TreeBackedVertex(v, tree); + this.dbToObject(obj, treeVertex, seen, depth, nodeOnly, cleanUp); + + return obj; + } + /** + * 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 + * @throws InvocationTargetException the invocation target exception + * @throws NoSuchMethodException the no such method exception + * @throws SecurityException the security exception + */ + private void copySimpleProperty(String property, Introspector obj, Vertex v) { + final Map metadata = obj.getPropertyMetadata(property); + String dbPropertyName = property; + if (metadata.containsKey(PropertyMetadata.DB_ALIAS)) { + dbPropertyName = metadata.get(PropertyMetadata.DB_ALIAS); + } + final Object temp = v.property(dbPropertyName).orElse(null); + if (temp != null) { + + obj.setValue(property, temp); + } + } + + /** + * 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 + * @throws InvocationTargetException the invocation target exception + * @throws NoSuchMethodException the no such method exception + * @throws SecurityException the security exception + */ + private void simpleDbToObject (Introspector obj, Vertex v) { + for (String property : obj.getProperties()) { + + + if (!(obj.isComplexType(property) || obj.isListType(property))) { + this.copySimpleProperty(property, obj, v); + } + } + } + + /** + * Creates the relationship list. + * + * @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 UnsupportedEncodingException the unsupported encoding 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 { + + + List cousins = this.engine.getQueryEngine().findCousinVertices(v); + + List relationshipObjList = obj.getValue("relationship"); + + for (Vertex cousin : cousins) { + + Introspector relationshipObj = obj.newIntrospectorInstanceOfNestedProperty("relationship"); + Object result = processEdgeRelationship(relationshipObj, cousin, cleanUp); + if (result != null) { + relationshipObjList.add(result); + } + + } + + if (relationshipObjList.isEmpty()) { + return null; + } else { + return obj; + } + } + + /** + * Process edge relationship. + * + * @param relationshipObj the relationship obj + * @param edge the edge + * @param direction the direction + * @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 UnsupportedEncodingException the unsupported encoding 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) throws UnsupportedEncodingException, AAIUnknownObjectException { + + + //we must look up all parents in this case because we need to compute name-properties + //we cannot used the cached aaiUri to perform this action currently + Optional>> tuple = this.getParents(relationshipObj.getLoader(), cousin, "true".equals(cleanUp)); + //damaged vertex found, ignore + if (!tuple.isPresent()) { + return null; + } + List list = tuple.get().getValue1(); + URI uri = this.getURIFromList(list); + + URIToRelationshipObject uriParser = null; + Introspector result = null; + try { + 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=" + tuple.get().getValue0().id().toString() + ": " + e.getMessage(), e); + if ("true".equals(cleanUp)) { + this.deleteWithTraversal(tuple.get().getValue0()); + } + return null; + } + + if(list.size() > 0 && this.version.compareTo(Version.v8) >= 0){ + this.addRelatedToProperty(result, list.get(0)); + } + + return result.getUnderlyingObject(); + } + + /** + * Gets the URI for vertex. + * + * @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 UnsupportedEncodingException the unsupported encoding exception + * @throws AAIUnknownObjectException + */ + public URI getURIForVertex(Vertex v) throws UnsupportedEncodingException { + + return getURIForVertex(v, false); + } + + public URI getURIForVertex(Vertex v, boolean overwrite) throws UnsupportedEncodingException { + URI uri = UriBuilder.fromPath("/unknown-uri").build(); + + String aaiUri = v.property(AAIProperties.AAI_URI).orElse(null); + + if (aaiUri != null && !overwrite) { + uri = UriBuilder.fromPath(aaiUri).build(); + } else { + Optional>> tuple = this.getParents(this.loader, v, false); + if (tuple.isPresent()) { + List list = tuple.get().getValue1(); + uri = this.getURIFromList(list); + } + } + return uri; + } + /** + * Gets the URI from list. + * + * @param list the list + * @return the URI from list + * @throws UnsupportedEncodingException the unsupported encoding exception + */ + private URI getURIFromList(List list) throws UnsupportedEncodingException { + String uri = ""; + StringBuilder sb = new StringBuilder(); + for (Introspector i : list) { + sb.insert(0, i.getURI()); + } + + uri = sb.toString(); + URI result = UriBuilder.fromPath(uri).build(); + return result; + } + + /** + * Gets the parents. + * + * @param start the start + * @param removeDamaged the remove damaged + * @return the parents + * @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 AAIUnknownObjectException + */ + private Optional>> getParents(Loader loader, Vertex start, boolean removeDamaged) { + + List results = this.engine.getQueryEngine().findParents(start); + List objs = new ArrayList<>(); + boolean shortCircuit = false; + for (Vertex v : results) { + String nodeType = v.property(AAIProperties.NODE_TYPE).orElse(null); + Introspector obj = null; + //vertex on the other end of this edge is bad + if (nodeType == null) { + //log something here about what was found and that it was removed + ErrorLogHelper.logError("AAI-6143", "Found a damaged parent vertex " + v.id().toString()); + if (removeDamaged) { + this.deleteWithTraversal(v); + } + shortCircuit = true; + } else { + try { + obj = loader.introspectorFromName(nodeType); + } catch (AAIUnknownObjectException e) { + LOGGER.info("attempted to create node type " + nodeType + " but we do not understand it for version: " + loader.getVersion()); + obj = null; + } + } + + if (obj == null) { + //can't make a valid path because we don't understand this object + // don't include it + } else { + this.simpleDbToObject(obj, v); + objs.add(obj); + } + } + + //stop processing and don't return anything for this bad vertex + if (shortCircuit) { + return Optional.empty(); + } + + return Optional.of(new Pair<>(results.get(results.size()-1), objs)); + } + /** + * Takes a list of vertices and a list of objs and assumes they are in + * the order you want the URIs to be nested. + * [A,B,C] creates uris [A, AB, ABC] + * @param vertices + * @param objs + * @throws UnsupportedEncodingException + * @throws URISyntaxException + */ + public void setCachedURIs(List vertices, List objs) throws UnsupportedEncodingException, URISyntaxException { + + String uriChain = ""; + for (int i = 0; i < vertices.size(); i++) { + String aaiUri = ""; + Vertex v = null; + v = vertices.get(i); + aaiUri = v.property(AAIProperties.AAI_URI).orElse(null); + if (aaiUri != null) { + uriChain += aaiUri; + } else { + URI uri = UriBuilder.fromPath(objs.get(i).getURI()).build(); + aaiUri = uri.toString(); + uriChain += aaiUri; + v.property(AAIProperties.AAI_URI, uriChain); + } + } + + + + } + + + /** + * Adds the r + * @throws AAIUnknownObjectException + * @throws IllegalArgumentException elated to property. + * + * @param relationship the relationship + * @param child the throws IllegalArgumentException, AAIUnknownObjectException child + */ + public void addRelatedToProperty(Introspector relationship, Introspector child) throws AAIUnknownObjectException { + String nameProps = child.getMetadata(ObjectMetadata.NAME_PROPS); + List relatedToProperties = new ArrayList<>(); + + if (nameProps != null) { + String[] props = nameProps.split(","); + for (String prop : props) { + Introspector relatedTo = relationship.newIntrospectorInstanceOfNestedProperty("related-to-property"); + relatedTo.setValue("property-key", child.getDbName() + "." + prop); + relatedTo.setValue("property-value", child.getValue(prop)); + relatedToProperties.add(relatedTo); + } + } + + if (relatedToProperties.size() > 0) { + List relatedToList = (List)relationship.getValue("related-to-property"); + for (Introspector obj : relatedToProperties) { + relatedToList.add(obj.getUnderlyingObject()); + } + } + + } + + /** + * Creates the edge. + * + * @param relationship the relationship + * @param inputVertex the input vertex + * @return true, if successful + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + public boolean createEdge(Introspector relationship, Vertex inputVertex) throws UnsupportedEncodingException, AAIException { + + Vertex relatedVertex = null; + + QueryParser parser = engine.getQueryBuilder().createQueryFromRelationship(relationship); + + List results = parser.getQueryBuilder().toList(); + if (results.size() == 0) { + 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 + relatedVertex = results.get(0); + } + + if (relatedVertex != null) { + + Edge e; + try { + e = this.getEdgeBetween(EdgeType.COUSIN, inputVertex, relatedVertex); + if (e == null) { + edgeRules.addEdge(this.engine.asAdmin().getTraversalSource(), inputVertex, relatedVertex); + + } else { + //attempted to link two vertexes already linked + } + } catch (NoEdgeRuleFoundException e1) { + throw new AAIException("AAI_6129", e1); + } + + + + + } + + return true; + } + + /** + * Gets the edges between. + * + * @param aVertex the out vertex + * @param bVertex the in vertex + * @return the edges between + * @throws AAIException the AAI exception + * @throws NoEdgeRuleFoundException + */ + private List getEdgesBetween(EdgeType type, Vertex aVertex, Vertex bVertex) throws AAIException, NoEdgeRuleFoundException { + + List result = new ArrayList<>(); + + if (bVertex != null) { + EdgeRule rule = edgeRules.getEdgeRule(type, aVertex, bVertex); + GraphTraversal findEdgesBetween = null; + findEdgesBetween = this.engine.asAdmin().getTraversalSource().V(aVertex).bothE(rule.getLabel()).filter(__.otherV().hasId(bVertex.id())); + List edges = findEdgesBetween.toList(); + for (Edge edge : edges) { + if (edge.label().equals(rule.getLabel())) { + result.add(edge); + } + } + + } + + return result; + } + + /** + * Gets the edge between. + * + * @param aVertex the out vertex + * @param bVertex the in vertex + * @return the edge between + * @throws AAIException the AAI exception + * @throws NoEdgeRuleFoundException + */ + public Edge getEdgeBetween(EdgeType type, Vertex aVertex, Vertex bVertex) throws AAIException { + + + + if (bVertex != null) { + + List edges = this.getEdgesBetween(type, aVertex, bVertex); + + if (edges.size() > 0) { + return edges.get(0); + } + + } + + return null; + } + + + /** + * Delete edge. + * + * @param relationship the relationship + * @param inputVertex the input vertex + * @return true, if successful + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + public boolean deleteEdge(Introspector relationship, Vertex inputVertex) throws UnsupportedEncodingException, AAIException { + + Vertex relatedVertex = null; + + QueryParser parser = engine.getQueryBuilder().createQueryFromRelationship(relationship); + + List results = parser.getQueryBuilder().toList(); + + if (results.size() == 0) { + return false; + } + + relatedVertex = results.get(0); + Edge edge; + try { + edge = this.getEdgeBetween(EdgeType.COUSIN, inputVertex, relatedVertex); + } catch (NoEdgeRuleFoundException e) { + throw new AAIException("AAI_6129", e); + } + if (edge != null) { + edge.remove(); + return true; + } else { + return false; + } + + } + + /** + * Delete items with traversal. + * + * @param vertexes the vertexes + * @throws IllegalStateException the illegal state exception + */ + public void deleteItemsWithTraversal(List vertexes) throws IllegalStateException { + for (Vertex v : vertexes) { + LOGGER.debug("About to delete the vertex with id: " + v.id()); + deleteWithTraversal(v); + } + } + + /** + * Delete with traversal. + * + * @param startVertex the start vertex + */ + public void deleteWithTraversal(Vertex startVertex) { + + List results = this.engine.getQueryEngine().findDeletable(startVertex); + + for (Vertex v : results) { + LOGGER.warn("Removing vertex " + v.id().toString()); + + v.remove(); + } + + } + + /** + * Delete. + * + * @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 + */ + public void delete(Vertex v, String resourceVersion, boolean enableResourceVersion) throws IllegalArgumentException, AAIException { + + boolean result = verifyDeleteSemantics(v, resourceVersion, enableResourceVersion); + if (result) { + try { + deleteWithTraversal(v); + } catch (IllegalStateException e) { + throw new AAIException("AAI_6110", e); + } + + } + + } + + + /** + * Verify delete semantics. + * + * @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 { + boolean result = true; + String nodeType = ""; + String errorDetail = " unknown delete semantic found"; + String aaiExceptionCode = ""; + nodeType = vertex.property(AAIProperties.NODE_TYPE).orElse(null); + if (enableResourceVersion && !this.verifyResourceVersion("delete", nodeType, vertex.property(AAIProperties.RESOURCE_VERSION).orElse(null), resourceVersion, nodeType)) { + } + List preventDeleteVertices = this.engine.asAdmin().getReadOnlyTraversalSource().V(vertex).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(); + + if (preventDeleteVertices.size() > 0) { + 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); + result = false; + } + if (!result) { + throw new AAIException(aaiExceptionCode, errorDetail); + } + return result; + } + + /** + * Verify resource version. + * + * @param action the action + * @param nodeType the node type + * @param currentResourceVersion the current resource version + * @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 { + String enabled = ""; + String errorDetail = ""; + String aaiExceptionCode = ""; + if (currentResourceVersion == null) { + currentResourceVersion = ""; + } + + if (resourceVersion == null) { + resourceVersion = ""; + } + try { + enabled = AAIConfig.get(AAIConstants.AAI_RESVERSION_ENABLEFLAG); + } catch (AAIException e) { + ErrorLogHelper.logException(e); + } + // We're only doing the resource version checks for v5 and later + if (enabled.equals("true") && this.version.compareTo(Version.v8) > 0) { + if (!currentResourceVersion.equals(resourceVersion)) { + if (action.equals("create") && !resourceVersion.equals("")) { + errorDetail = "resource-version passed for " + action + " of " + uri; + aaiExceptionCode = "AAI_6135"; + } else if (resourceVersion.equals("")) { + errorDetail = "resource-version not passed for " + action + " of " + uri; + aaiExceptionCode = "AAI_6130"; + } else { + errorDetail = "resource-version MISMATCH for " + action + " of " + uri; + aaiExceptionCode = "AAI_6131"; + } + + throw new AAIException(aaiExceptionCode, errorDetail); + + } + } + return true; + } + + /** + * Convert from camel case. + * + * @param name the name + * @return the string + */ + private String convertFromCamelCase (String name) { + String result = ""; + result = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, name); + + NamingExceptions exceptions = NamingExceptions.getInstance(); + result = exceptions.getDBName(result); + + return result; + } + + private boolean canModify(Introspector obj, String propName, String requestContext) { + final String readOnly = obj.getPropertyMetadata(propName).get(PropertyMetadata.READ_ONLY); + if (readOnly != null) { + final String[] items = readOnly.split(","); + for (String item : items) { + if (requestContext.equals(item)) { + return false; + } + } + } + return true; + } + + private void executePreSideEffects(Introspector obj, Vertex self) throws AAIException { + + SideEffectRunner runner = new SideEffectRunner + .Builder(this.engine, this).addSideEffect(DataCopy.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(); + + 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(); + + runner.execute(obj, self); + } + +} 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 new file mode 100644 index 00000000..a6fe22b8 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/serialization/db/DeleteSemantic.java @@ -0,0 +1,41 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.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! + */ +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, +} 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 new file mode 100644 index 00000000..73ece7e4 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/serialization/db/EdgeProperties.java @@ -0,0 +1,44 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.serialization.db; + +public class EdgeProperties { + + public static String out(EdgeProperty prop) { + + return out(prop.toString()); + } + + public static String in(EdgeProperty prop) { + return in(prop.toString()); + } + + public static String out(String prop) { + + return prop; + } + + public static String in(String prop) { + return prop + "-REV"; + } + +} diff --git a/aai-core/src/main/java/org/onap/aai/serialization/db/EdgeProperty.java b/aai-core/src/main/java/org/onap/aai/serialization/db/EdgeProperty.java new file mode 100644 index 00000000..29d82298 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/serialization/db/EdgeProperty.java @@ -0,0 +1,45 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.serialization.db; + +public enum EdgeProperty { + FROM("from"), + TO("to"), + LABEL("label"), + DIRECTION("direction"), + MULTIPLICITY("multiplicity"), + CONTAINS("contains-other-v"), + DELETE_OTHER_V("delete-other-v"), + SVC_INFRA("SVC-INFRA"), + PREVENT_DELETE("prevent-delete"); + + private final String name; + + private EdgeProperty(String name) { + this.name = name; + } + + @Override + public String toString() { + return name; + } +} 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 new file mode 100644 index 00000000..92643bcf --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/serialization/db/EdgePropertyMap.java @@ -0,0 +1,60 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.serialization.db; + +import org.apache.tinkerpop.gremlin.structure.Direction; + +import java.util.HashMap; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class EdgePropertyMap extends HashMap { + + 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/EdgeRule.java b/aai-core/src/main/java/org/onap/aai/serialization/db/EdgeRule.java new file mode 100644 index 00000000..309dbffe --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/serialization/db/EdgeRule.java @@ -0,0 +1,211 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.serialization.db; + +import org.apache.tinkerpop.gremlin.structure.Direction; + +import java.util.HashMap; +import java.util.Map; + +public class EdgeRule { + + private String label = ""; + private MultiplicityRule multiplicityRule = null; + private Direction direction = null; + private Map edgeProperties = null; + + /** + * Instantiates a new edge rule. + */ + public EdgeRule() { + edgeProperties = new HashMap<>(); + } + + /** + * Gets the label. + * + * @return the label + */ + public String getLabel() { + return label; + } + + /** + * Sets the label. + * + * @param label the new label + */ + public void setLabel(String label) { + this.label = label; + } + + /** + * Gets the multiplicity rule. + * + * @return the multiplicity rule + */ + public MultiplicityRule getMultiplicityRule() { + return multiplicityRule; + } + + public void setMultiplicityRule(String multiplicity){ + if ("Many2Many".equalsIgnoreCase(multiplicity)) { + this.multiplicityRule = MultiplicityRule.MANY2MANY; + } else if ("One2Many".equalsIgnoreCase(multiplicity)) { + this.multiplicityRule = MultiplicityRule.ONE2MANY; + } else if ("One2One".equalsIgnoreCase(multiplicity)) { + this.multiplicityRule = MultiplicityRule.ONE2ONE; + } else { //should be "Many2One" + this.multiplicityRule = MultiplicityRule.MANY2ONE; + } + } + + /** + * Sets the multiplicity rule. + * + * @param multiplicityRule the new multiplicity rule + */ + public void setMultiplicityRule(MultiplicityRule multiplicityRule) { + this.multiplicityRule = multiplicityRule; + } + + /** + * Gets the direction. + * + * @return the direction + */ + public Direction getDirection() { + return direction; + } + + public void setDirection(String direction){ + if ("OUT".equalsIgnoreCase(direction)) { + this.direction = Direction.OUT; + } else if ("IN".equalsIgnoreCase(direction)) { + this.direction = Direction.IN; + } else { + this.direction = Direction.BOTH; + } + } + + /** + * Sets the direction. + * + * @param direction the new direction + */ + public void setDirection(Direction direction) { + this.direction = direction; + } + + /** + * Gets the checks if is parent. + * + * @return the checks if is parent + */ + public String getContains() { + return this.getProp(EdgeProperty.CONTAINS); + } + + /** + * Sets the checks if is parent. + * + * @param isParent the new checks if is parent + */ + public void setContains(String isParent) { + this.setProp(EdgeProperty.CONTAINS, isParent); + } + + /** + * Gets the checks for del target. + * + * @return the checks for del target + */ + public String getDeleteOtherV() { + return this.getProp(EdgeProperty.DELETE_OTHER_V); + } + + /** + * Sets the checks for del target. + * + * @param hasDelTarget the new checks for del target + */ + public void setDeleteOtherV(String hasDelTarget) { + this.setProp(EdgeProperty.DELETE_OTHER_V, hasDelTarget); + } + + /** + * Gets the service infrastructure. + * + * @return the service infrastructure + */ + public String getServiceInfrastructure() { + return this.getProp(EdgeProperty.SVC_INFRA); + } + + /** + * Sets the service infrastructure. + * + * @param serviceInfrastructure the new service infrastructure + */ + public void setServiceInfrastructure(String serviceInfrastructure) { + this.setProp(EdgeProperty.SVC_INFRA, serviceInfrastructure); + } + + public String getPreventDelete() { + return this.getProp(EdgeProperty.PREVENT_DELETE); + } + + public void setPreventDelete(String preventDelete) { + this.setProp(EdgeProperty.PREVENT_DELETE, preventDelete); + } + + /** + * Gets the edge properties. + * + * @return the edge properties + */ + public Map getEdgeProperties() { + return this.edgeProperties; + } + + /** + * Sets the prop. + * + * @param key the key + * @param value the value + */ + private void setProp(EdgeProperty key, String value) { + this.edgeProperties.put(key, value); + } + + /** + * Gets the prop. + * + * @param key the key + * @return the prop + */ + private String getProp(EdgeProperty key) { + return this.edgeProperties.get(key); + } + + +} diff --git a/aai-core/src/main/java/org/onap/aai/serialization/db/EdgeRules.java b/aai-core/src/main/java/org/onap/aai/serialization/db/EdgeRules.java new file mode 100644 index 00000000..d9dfa457 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/serialization/db/EdgeRules.java @@ -0,0 +1,589 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.serialization.db; + +import static com.jayway.jsonpath.Criteria.where; +import static com.jayway.jsonpath.Filter.filter; + +import java.io.InputStream; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Optional; +import java.util.Scanner; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__; +import org.apache.tinkerpop.gremlin.structure.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.exceptions.AAIException; +import org.onap.aai.introspection.Version; +import org.onap.aai.serialization.db.exceptions.EdgeMultiplicityException; +import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.google.common.collect.ArrayListMultimap; +import com.google.common.collect.Multimap; +import com.jayway.jsonpath.DocumentContext; +import com.jayway.jsonpath.Filter; +import com.jayway.jsonpath.JsonPath; + +public class EdgeRules { + + private EELFLogger logger = EELFManager.getInstance().getLogger(EdgeRules.class); + + private DocumentContext rulesDoc; + + /** + * Loads the most recent DbEdgeRules json file for later parsing. + * Only need most recent version for actual A&AI operations that call this class; + * the old ones are only used in tests. + */ + private EdgeRules() { + + String json = this.getEdgeRuleJson(Version.getLatest()); + rulesDoc = JsonPath.parse(json); + + } + + private EdgeRules(String rulesFilename) { + String json = this.getEdgeRuleJson(rulesFilename); + rulesDoc = JsonPath.parse(json); + } + + private String getEdgeRuleJson(String rulesFilename) { + InputStream is = getClass().getResourceAsStream(rulesFilename); + + Scanner scanner = new Scanner(is); + String json = scanner.useDelimiter("\\Z").next(); + scanner.close(); + + return json; + } + + /** + * Loads the versioned DbEdgeRules json file for later parsing. + */ + @SuppressWarnings("unchecked") + private EdgeRules(Version version) { + String json = this.getEdgeRuleJson(version); + rulesDoc = JsonPath.parse(json); + } + + private String getEdgeRuleJson(Version version) { + InputStream is = getClass().getResourceAsStream("/dbedgerules/DbEdgeRules_" + version.toString() + ".json"); + + Scanner scanner = new Scanner(is); + String json = scanner.useDelimiter("\\Z").next(); + scanner.close(); + + return json; + } + + private static class Helper { + private static final EdgeRules INSTANCE = new EdgeRules(); + private static final Map INSTANCEMAP = new ConcurrentHashMap<>(); + + private static EdgeRules getEdgeRulesByFilename(String rulesFilename) { + return new EdgeRules(rulesFilename); + } + + private static EdgeRules getVersionedEdgeRules(Version v) { + if (Version.isLatest(v)) { + return INSTANCE; + } + if (!INSTANCEMAP.containsKey(v)) { + INSTANCEMAP.put(v, new EdgeRules(v)); + } + return INSTANCEMAP.get(v); + } + } + + /** + * Gets the single instance of EdgeRules. + * + * @return single instance of EdgeRules + */ + public static EdgeRules getInstance() { + return Helper.INSTANCE; + + } + + /** + * Gets the versioned instance of EdgeRules. + * + * @return versioned instance of EdgeRules + */ + public static EdgeRules getInstance(Version v) { + return Helper.getVersionedEdgeRules(v); + + } + + /** + * Loads edge rules from the given file. + * + * @param rulesFilename - name of the file to load rules from + * @return the EdgeRules instance + */ + public static EdgeRules getInstance(String rulesFilename) { + return Helper.getEdgeRulesByFilename(rulesFilename); + } + + /** + * 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); + } + + /** + * 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(EdgeType.COUSIN, traversalSource, aVertex, bVertex, false); + } + + /** + * 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); + } + + /** + * 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.addEdge(EdgeType.COUSIN, traversalSource, aVertex, bVertex, true); + } + + /** + * 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) throws AAIException { + + EdgeRule rule = this.getEdgeRule(type, aVertex, bVertex); + + Edge e = null; + + Optional 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) { + + // In DbEdgeRules.EdgeRules -- What we have as "edgeRule" is a comma-delimited set of strings. + // The first item is the edgeLabel. + // The second in the list is always "direction" which is always OUT for the way we've implemented it. + // Items starting at "firstTagIndex" and up are all assumed to be booleans that map according to + // tags as defined in EdgeInfoMap. + // Note - if they are tagged as 'reverse', that means they get the tag name with "-REV" on it + Map propMap = rule.getEdgeProperties(); + + for (Entry entry : propMap.entrySet()) { + edge.property(entry.getKey().toString(), entry.getValue()); + } + } + + /** + * Checks if any edge rules exist between the two given nodes, in either A|B or B|A order. + * + * @param nodeA - node at one end of the edge + * @param nodeB - node at the other end + * @return true, if any such rules exist + */ + public boolean hasEdgeRule(String nodeA, String nodeB) { + Filter aToB = filter( + where("from").is(nodeA).and("to").is(nodeB) + ); + Filter bToA = filter( + where("from").is(nodeB).and("to").is(nodeA) + ); + + List> results = readRules(aToB); + results.addAll(readRules(bToA)); + + return !results.isEmpty(); + + } + + /** + * Checks if any edge rules exist between the two given nodes, in either A|B or B|A order. + * + * @param aVertex - node at one end of the edge + * @param bVertex - node at the other end + * @return true, if any such rules exist + */ + public boolean hasEdgeRule(Vertex aVertex, Vertex bVertex) { + String outType = aVertex.property("aai-node-type").orElse(null); + String inType = bVertex.property("aai-node-type").orElse(null); + + return this.hasEdgeRule(outType, inType); + + } + + /** + * Gets all the edge rules that exist between the given node types. + * The rules will be phrased in terms of out|in, though this will + * also find rules defined as in|out (it will flip the direction in + * the EdgeRule object returned accordingly to match out|in). + * + * @param outType + * @param inType + * @return Map where edgeLabel is the label name + * @throws AAIException + */ + public Map getEdgeRules(String outType, String inType) throws AAIException { + Map result = new HashMap<>(); + EdgeRule rule = null; + for (EdgeType type : EdgeType.values()) { + try { + rule = this.getEdgeRule(type, outType, inType); + result.put(rule.getLabel(), rule); + } catch (NoEdgeRuleFoundException e) { + continue; + } + } + + return result; + } + + + + /** + * Gets the edge rule of the given type that exists between A and B. + * Will check B|A as well, and flips the direction accordingly if that succeeds + * to match the expected A|B return. + * + * @param type - the type of edge you're looking for + * @param nodeA - first node type + * @param nodeB - second node type + * @return EdgeRule describing the rule in terms of A|B, if there is any such rule + * @throws AAIException if no such edge exists + */ + public EdgeRule getEdgeRule(EdgeType type, String nodeA, String nodeB) throws AAIException { + //try A to B + List> aToBEdges = readRules(buildFilter(type, nodeA, nodeB)); + if (!aToBEdges.isEmpty()) { + //lazily stop iterating if we find a match + //should there be a mismatch between type and isParent, + //the caller will receive something. + //this operates on the assumption that there are at most two rules + //for a given vertex pair + verifyRule(aToBEdges.get(0)); + return buildRule(aToBEdges.get(0)); + } + + //we get here if there was nothing for A to B, so let's try B to A + List> bToAEdges = readRules(buildFilter(type, nodeB, nodeA)); + if (!bToAEdges.isEmpty()) { + verifyRule(bToAEdges.get(0)); + return flipDirection(buildRule(bToAEdges.get(0))); //bc we need to return as A|B, so flip the direction to match + } + + //found none + throw new NoEdgeRuleFoundException("no " + type.toString() + " edge between " + nodeA + " and " + nodeB); + } + + /** + * Builds a JsonPath filter to search for an edge from nodeA to nodeB with the given edge type (cousin or parent/child) + * + * @param type + * @param nodeA - start node + * @param nodeB - end node + * @return + */ + private Filter buildFilter(EdgeType type, String nodeA, String nodeB) { + if (EdgeType.COUSIN.equals(type)) { + return filter( + where("from").is(nodeA).and("to").is(nodeB).and(EdgeProperty.CONTAINS.toString()).is(AAIDirection.NONE.toString()) + ); + } else { + return filter( + where("from").is(nodeA).and("to").is(nodeB).and(EdgeProperty.CONTAINS.toString()).is("${direction}")).or( + where("from").is(nodeA).and("to").is(nodeB).and(EdgeProperty.CONTAINS.toString()).is("!${direction}") + ); + } + } + + /** + * Puts the give edge rule information into an EdgeRule object. + * + * @param edge - the edge information returned from JsonPath + * @return EdgeRule containing that information + */ + private EdgeRule buildRule(Map map) { + Map edge = new EdgePropertyMap<>(); + edge.putAll(map); + + EdgeRule rule = new EdgeRule(); + rule.setLabel(edge.get("label")); + rule.setDirection(edge.get("direction")); + rule.setMultiplicityRule(edge.get("multiplicity")); + rule.setContains(edge.get(EdgeProperty.CONTAINS.toString())); + rule.setDeleteOtherV(edge.get(EdgeProperty.DELETE_OTHER_V.toString())); + rule.setServiceInfrastructure(edge.get(EdgeProperty.SVC_INFRA.toString())); + rule.setPreventDelete(edge.get(EdgeProperty.PREVENT_DELETE.toString())); + + return rule; + } + + /** + * If getEdgeRule gets a request for A|B, and it finds something as B|A, the caller still expects + * the returned EdgeRule to reflect A|B directionality. This helper method flips B|A direction to + * match this expectation. + * + * @param rule whose direction needs flipped + * @return the updated rule + */ + private EdgeRule flipDirection(EdgeRule rule) { + if (Direction.IN.equals(rule.getDirection())) { + rule.setDirection(Direction.OUT); + return rule; + } else if (Direction.OUT.equals(rule.getDirection())) { + rule.setDirection(Direction.IN); + return rule; + } else { //direction is BOTH, flipping both is still both + return rule; + } + } + + /** + * Gets the edge rule of the given type that exists between A and B. + * Will check B|A as well, and flips the direction accordingly if that succeeds + * to match the expected A|B return. + * + * @param type - the type of edge you're looking for + * @param aVertex - first node type + * @param bVertex - second node type + * @return EdgeRule describing the rule in terms of A|B, if there is any such rule + * @throws AAIException if no such edge exists + */ + public EdgeRule getEdgeRule(EdgeType type, Vertex aVertex, Vertex bVertex) throws AAIException { + String outType = aVertex.property(AAIProperties.NODE_TYPE).orElse(null); + String inType = bVertex.property(AAIProperties.NODE_TYPE).orElse(null); + + return this.getEdgeRule(type, outType, inType); + + + } + + /** + * 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 validateMultiplicity(EdgeRule rule, GraphTraversalSource traversalSource, Vertex aVertex, Vertex bVertex) { + + if (rule.getDirection().equals(Direction.OUT)) { + + } else if (rule.getDirection().equals(Direction.IN)) { + Vertex tempV = bVertex; + bVertex = aVertex; + aVertex = tempV; + } + + String aVertexType = aVertex.property(AAIProperties.NODE_TYPE).orElse(null); + String bVertexType = bVertex.property(AAIProperties.NODE_TYPE).orElse(null); + String label = rule.getLabel(); + MultiplicityRule multiplicityRule = rule.getMultiplicityRule(); + List outEdges = traversalSource.V(aVertex).outE(label).where(__.inV().has(AAIProperties.NODE_TYPE, bVertexType)).toList(); + List inEdges = traversalSource.V(bVertex).inE(label).where(__.outV().has(AAIProperties.NODE_TYPE, aVertexType)).toList(); + String detail = ""; + if (multiplicityRule.equals(MultiplicityRule.ONE2ONE)) { + if (inEdges.size() >= 1 || outEdges.size() >= 1 ) { + detail = "multiplicity rule violated: only one edge can exist with label: " + label + " between " + aVertexType + " and " + bVertexType; + } + } else if (multiplicityRule.equals(MultiplicityRule.ONE2MANY)) { + if (inEdges.size() >= 1) { + detail = "multiplicity rule violated: only one edge can exist with label: " + label + " between " + aVertexType + " and " + bVertexType; + } + } else if (multiplicityRule.equals(MultiplicityRule.MANY2ONE)) { + if (outEdges.size() >= 1) { + detail = "multiplicity rule violated: only one edge can exist with label: " + label + " between " + aVertexType + " and " + bVertexType; + } + } else { + + } + + if (!"".equals(detail)) { + return Optional.of(detail); + } else { + return Optional.empty(); + } + + + } + + /** + * Verifies that all required properties are defined in the given edge rule. + * If they are not, throws a RuntimeException. + * + * @param rule - Map representing + * an edge rule + */ + private void verifyRule(Map rule) { + for (EdgeProperty prop : EdgeProperty.values()) { + if (!rule.containsKey(prop.toString())) { + /* Throws RuntimeException as rule definition errors + * cannot be recovered from, and should never happen anyway + * because these are configuration files, so requiring all + * downstream code to check for this exception seems inappropriate. + * It's instantiated with an AAIException to make sure all + * relevant information is present in the error message. + */ + throw new RuntimeException(new AAIException("AAI_4005", + "Rule between " + rule.get("from") + " and " + rule.get("to") + + " is missing property " + prop + ".")); + } + } + } + + /** + * Reads all the edge rules from the loaded json file. + * + * @return List> + * Each map represents a rule read from the json. + */ + private List> readRules() { + return readRules(null); + } + + /** + * Reads the edge rules from the loaded json file, using the given filter + * to get specific rules. If filter is null, will get all rules. + * + * @param filter - may be null to indicate get all + * @return List> + * Each map represents a rule read from the json. + */ + private List> readRules(Filter filter) { + List> results; + if (filter == null) { //no filter means get all + results = rulesDoc.read("$.rules.*"); + } else { + results = rulesDoc.read("$.rules.[?]", filter); + } + for (Map result : results) { + verifyRule(result); + } + return results; + } + + /** + * Gets all the edge rules we define. + * + * @return Multimap + */ + public Multimap getAllRules() { + Multimap result = ArrayListMultimap.create(); + + List> rules = readRules(); + for (Map rule : rules) { + EdgeRule er = buildRule(rule); + String name = rule.get("from") + "|" + rule.get("to"); + result.put(name, er); + } + + return result; + } + + /** + * Gets all edge rules that define a child relationship from + * the given node type. + * + * @param nodeType + * @return + */ + public Set getChildren(String nodeType) { + + final Filter filter = filter( + where("from").is(nodeType).and(EdgeProperty.CONTAINS.toString()).is("${direction}") + ).or(where("to").is(nodeType).and(EdgeProperty.CONTAINS.toString()).is("!${direction}")); + + final List> rules = readRules(filter); + final Set result = new HashSet<>(); + rules.forEach(item -> { + verifyRule(item); + result.add(buildRule(item)); + }); + + return result; + + } +} diff --git a/aai-core/src/main/java/org/onap/aai/serialization/db/EdgeType.java b/aai-core/src/main/java/org/onap/aai/serialization/db/EdgeType.java new file mode 100644 index 00000000..088e13bb --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/serialization/db/EdgeType.java @@ -0,0 +1,27 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.serialization.db; + +public enum EdgeType { + COUSIN, + TREE; +} 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 new file mode 100644 index 00000000..4d38bd38 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/serialization/db/GetAllPool.java @@ -0,0 +1,47 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.serialization.db; + +import java.util.concurrent.ExecutorService; +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; + } +} 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 new file mode 100644 index 00000000..9bb04d6b --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/serialization/db/GraphSingleton.java @@ -0,0 +1,70 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.serialization.db; + +import com.thinkaurelius.titan.core.TitanGraph; +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; + + } + + /** + * Gets the count. + * + * @return the count + */ + public AtomicInteger getCount() { + return totalCount; + } + + /** + * Gets the tx graph. + * + * @return the tx graph + */ + public TitanGraph getTxGraph() { + return AAIGraph.getInstance().getGraph(); + } + + public TitanGraph getTxGraph(DBConnectionType connectionType) { + return AAIGraph.getInstance().getGraph(connectionType); + } +} diff --git a/aai-core/src/main/java/org/onap/aai/serialization/db/LegacyDBSerializer.java b/aai-core/src/main/java/org/onap/aai/serialization/db/LegacyDBSerializer.java new file mode 100644 index 00000000..b9343816 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/serialization/db/LegacyDBSerializer.java @@ -0,0 +1,35 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.serialization.db; + +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.ModelType; +import org.onap.aai.introspection.Version; +import org.onap.aai.serialization.engines.TransactionalGraphEngine; + +public class LegacyDBSerializer extends DBSerializer { + + public LegacyDBSerializer(Version version, TransactionalGraphEngine engine, ModelType introspectionType, String sourceOfTruth) throws AAIException { + super(version, engine, introspectionType, sourceOfTruth); + } + +} diff --git a/aai-core/src/main/java/org/onap/aai/serialization/db/MultiplicityRule.java b/aai-core/src/main/java/org/onap/aai/serialization/db/MultiplicityRule.java new file mode 100644 index 00000000..0451c0d7 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/serialization/db/MultiplicityRule.java @@ -0,0 +1,29 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.serialization.db; + +public enum MultiplicityRule { + MANY2ONE, + ONE2MANY, + ONE2ONE, + MANY2MANY +} diff --git a/aai-core/src/main/java/org/onap/aai/serialization/db/TitanGraphSingleton.java b/aai-core/src/main/java/org/onap/aai/serialization/db/TitanGraphSingleton.java new file mode 100644 index 00000000..e1accb4e --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/serialization/db/TitanGraphSingleton.java @@ -0,0 +1,39 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.serialization.db; + +/* This is class is just a wrapper of its parent */ +public class TitanGraphSingleton extends GraphSingleton { + + private static class Helper { + private static final TitanGraphSingleton INSTANCE = new TitanGraphSingleton(); + } + + /** + * Gets the single instance of TitanGraphSingleton. + * + * @return single instance of TitanGraphSingleton + */ + public static TitanGraphSingleton 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 new file mode 100644 index 00000000..6baa113d --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/serialization/db/exceptions/EdgeMultiplicityException.java @@ -0,0 +1,41 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.serialization.db.exceptions; + +import org.onap.aai.exceptions.AAIException; + +public class EdgeMultiplicityException extends AAIException { + + private static final long serialVersionUID = -5575661036426538012L; + + public EdgeMultiplicityException(String message) { + super("AAI_6140", message); + } + + public EdgeMultiplicityException(Throwable cause) { + super("AAI_6140",cause); + } + + 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/NoEdgeRuleFoundException.java b/aai-core/src/main/java/org/onap/aai/serialization/db/exceptions/NoEdgeRuleFoundException.java new file mode 100644 index 00000000..247379cb --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/serialization/db/exceptions/NoEdgeRuleFoundException.java @@ -0,0 +1,41 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.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_6129", message); + } + + public NoEdgeRuleFoundException(Throwable cause) { + super("AAI_6129",cause); + } + + public NoEdgeRuleFoundException(String message, Throwable cause) { + super("AAI_6129", cause, message); + } +} 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 new file mode 100644 index 00000000..db947bf8 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/serialization/engines/QueryStyle.java @@ -0,0 +1,26 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.serialization.engines; + +public enum QueryStyle { + GREMLIN_TRAVERSAL, GREMLIN_UNIQUE, GREMLINPIPELINE_TRAVERSAL, TRAVERSAL +} diff --git a/aai-core/src/main/java/org/onap/aai/serialization/engines/TitanDBEngine.java b/aai-core/src/main/java/org/onap/aai/serialization/engines/TitanDBEngine.java new file mode 100644 index 00000000..315081e7 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/serialization/engines/TitanDBEngine.java @@ -0,0 +1,102 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.serialization.engines; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.apache.tinkerpop.gremlin.structure.VertexProperty; +import org.onap.aai.dbmap.DBConnectionType; +import org.onap.aai.introspection.Loader; +import org.onap.aai.serialization.db.TitanGraphSingleton; + +public class TitanDBEngine extends TransactionalGraphEngine { + + /** + * Instantiates a new titan DB engine. + * + * @param style the style + * @param loader the loader + */ + public TitanDBEngine(QueryStyle style, DBConnectionType connectionType, Loader loader) { + super(style, loader, connectionType, TitanGraphSingleton.getInstance()); + } + + /** + * Instantiates a new titan DB engine. + * + * @param style the style + * @param loader the loader + * @param connect the connect + */ + public TitanDBEngine(QueryStyle style, Loader loader, boolean connect) { + super(style, loader); + if (connect) { + this.singleton = TitanGraphSingleton.getInstance(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public boolean setListProperty(Vertex v, String name, List objs) { + + //clear out list full replace style + + Iterator> 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 getListProperty(Vertex v, String name) { + + List result = new ArrayList(); + + Iterator> 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/TransactionalGraphEngine.java b/aai-core/src/main/java/org/onap/aai/serialization/engines/TransactionalGraphEngine.java new file mode 100644 index 00000000..11bf5955 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/serialization/engines/TransactionalGraphEngine.java @@ -0,0 +1,246 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.serialization.engines; + +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.onap.aai.dbmap.DBConnectionType; +import org.onap.aai.introspection.Loader; +import org.onap.aai.query.builder.GremlinTraversal; +import org.onap.aai.query.builder.GremlinUnique; +import org.onap.aai.query.builder.QueryBuilder; +import org.onap.aai.query.builder.TraversalQuery; +import org.onap.aai.serialization.db.GraphSingleton; +import org.onap.aai.serialization.engines.query.GraphTraversalQueryEngine; +import org.onap.aai.serialization.engines.query.QueryEngine; + +import com.thinkaurelius.titan.core.TitanGraph; +import com.thinkaurelius.titan.core.schema.TitanManagement; + +public abstract class TransactionalGraphEngine { + + protected GraphSingleton singleton = null; + protected QueryEngine queryEngine = null; + protected QueryBuilder 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 getListProperty(Vertex v, String name); + + /** + * Gets the graph. + * + * @return the graph + */ + private TitanGraph 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)) { + + 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 getQueryBuilder() { + return getQueryBuilder(this.loader); + } + + public QueryBuilder getQueryBuilder(QueryStyle style) { + return getQueryBuilder(style, this.loader); + } + + public QueryBuilder getQueryBuilder(Loader loader) { + return getQueryBuilder(this.style, loader); + } + + public QueryBuilder 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 { + throw new IllegalArgumentException("Query Builder type not recognized"); + } + return queryBuilder; + } + /** + * Gets the query builder. + * + * @param start the start + * @return the query builder + */ + public QueryBuilder getQueryBuilder(Vertex start) { + return getQueryBuilder(this.loader, start); + } + + public QueryBuilder getQueryBuilder(Loader loader, Vertex start) { + return getQueryBuilder(this.style, loader, start); + } + + public QueryBuilder 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 { + 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 TitanManagement 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 new file mode 100644 index 00000000..872b0c5f --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/serialization/engines/query/GraphTraversalQueryEngine.java @@ -0,0 +1,198 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.serialization.engines.query; + + +import static org.onap.aai.serialization.db.AAIDirection.IN; +import static org.onap.aai.serialization.db.AAIDirection.NONE; +import static org.onap.aai.serialization.db.AAIDirection.OUT; +import static org.onap.aai.serialization.db.EdgeProperty.CONTAINS; +import static org.onap.aai.serialization.db.EdgeProperty.DELETE_OTHER_V; + +import java.util.List; +import java.util.Set; + +import org.apache.tinkerpop.gremlin.process.traversal.P; +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__; +import org.apache.tinkerpop.gremlin.process.traversal.step.util.Tree; +import org.apache.tinkerpop.gremlin.structure.Direction; +import org.apache.tinkerpop.gremlin.structure.Edge; +import org.apache.tinkerpop.gremlin.structure.Element; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.onap.aai.db.props.AAIProperties; +import org.onap.aai.introspection.Loader; + +/* + * This class needs some big explanation despite its compact size. + * This controls all the queries performed by the CRUD API in A&AI. + * findParents, findChildren, and findDeletable require special attention + * These methods use 'repeat'. You cannot use 'emit' with repeat currently + * as it is extremely buggy as of tinkerpop-3.0.1-incubating. The way around + * it (for now) is to sideEffect all the vertices we traverse into an ArrayList. + * + */ +public class GraphTraversalQueryEngine extends QueryEngine { + + /** + * Instantiates a new graph traversal query engine. + * + * @param graphEngine the graph engine + */ + public GraphTraversalQueryEngine(GraphTraversalSource g) { + super(g); + } + + /** + * {@inheritDoc} + */ + @Override + public List findParents(Vertex start) { + + final GraphTraversal 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(); + } + + /** + * {@inheritDoc} + */ + @Override + public List findAllChildren(Vertex start) { + + GraphTraversal 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(); + + } + + public List findChildrenOfType(Vertex start, String type) { + GraphTraversal 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(); + } + + public List findChildren(Vertex start) { + GraphTraversal pipe = this.g.V(start).union( + __.outE().has(CONTAINS.toString(), OUT.toString()), + __.inE().has(CONTAINS.toString(), IN.toString()) + ).otherV().dedup(); + + return pipe.toList(); + } + + /** + * {@inheritDoc} + */ + @Override + public List findDeletable(Vertex start) { + GraphTraversal pipe = this.g + .V(start).emit(v -> true).repeat( + __.union( + __.outE().or( + __.has(CONTAINS.toString(), OUT.toString()), + __.has(DELETE_OTHER_V.toString(), OUT.toString()) + ).inV(), + __.inE().or( + __.has(CONTAINS.toString(), IN.toString()), + __.has(DELETE_OTHER_V.toString(), IN.toString()) + ).outV() + ) + ); + + return pipe.toList(); + } + + /** + * {@inheritDoc} + */ + @Override + public List findRelatedVertices(Vertex start, Direction direction, String label, String nodeType) { + GraphTraversal 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 findSubGraph(Vertex start, int iterations, boolean nodeOnly) { + final GraphTraversal 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()) + ); + + 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 findEdgesForVersion(Vertex start, Loader loader) { + final Set objects = loader.getAllObjects().keySet(); + GraphTraversal 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))) + ).dedup(); + + return pipeline.toList(); + } + + + @Override + public List findCousinVertices(Vertex start) { + GraphTraversal pipeline = this.g.V(start).union( + __.inE().has(CONTAINS.toString(), NONE.toString()), + __.outE().has(CONTAINS.toString(), NONE.toString())).otherV().dedup(); + + return pipeline.toList(); + } + +} + 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 new file mode 100644 index 00000000..e8acaecd --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/serialization/engines/query/GremlinPipelineQueryEngine.java @@ -0,0 +1,206 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.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========================================================= + */ + +/* +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 executeQuery(TransactionalGraph g, QueryBuilder query) { + List 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 executeParentQuery(TransactionalGraph g, QueryBuilder query) { + List 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 findParents(Vertex start) { + GremlinPipeline pipe = new GremlinPipeline(start).as("x").inE() + .has("isParent", true).outV().loop("x", new PipeFunction, Boolean>() { + + @Override + public Boolean compute(LoopPipe.LoopBundle argument) { + GremlinPipeline pipe = new GremlinPipeline<>(argument.getObject()); + return pipe.inE().has("isParent", true).count() == 1 || argument.getLoops() < 100; + } + + }, new PipeFunction, Boolean>() { + + @Override + public Boolean compute(LoopPipe.LoopBundle argument) { + return true; + } + + }); + + List results = pipe.toList(); + results.add(0, start); + return results; + } + + @Override + public List findChildren(Vertex start) { + Set seen = new HashSet<>(); + seen.add(start); + GremlinPipeline pipe = new GremlinPipeline(start).as("x").outE().has("isParent", true).inV() + .except(seen).store(seen).loop("x", new PipeFunction, Boolean>() { + + @Override + public Boolean compute(LoopPipe.LoopBundle argument) { + GremlinPipeline pipe = new GremlinPipeline<>(argument.getObject()); + return pipe.outE().has("isParent", true).count() >= 1 || argument.getLoops() < 100; + } + + }, new PipeFunction, Boolean>() { + + @Override + public Boolean compute(LoopPipe.LoopBundle argument) { + return true; + } + + }); + + List results = pipe.toList(); + results.add(0, start); + return results; + } + + @Override + public List findDeletable(Vertex start) { + Set seen = new HashSet<>(); + seen.add(start); + GremlinPipeline pipe = new GremlinPipeline(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, Boolean>() { + + @Override + public Boolean compute(LoopPipe.LoopBundle argument) { + GremlinPipeline 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, Boolean>() { + + @Override + public Boolean compute(LoopPipe.LoopBundle argument) { + return true; + } + + }); + List results = pipe.toList(); + results.add(0, start); + + return results; + } + + private List process(GremlinPipeline start, GremlinPipeline pipe) { + + + return start.add(pipe).cast(Vertex.class).toList(); + } + + @Override + public List findRelatedVertices(Vertex start, Direction direction, String label, String nodeType) { + GremlinPipeline pipe = new GremlinPipeline(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 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 new file mode 100644 index 00000000..ab622963 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/serialization/engines/query/GremlinQueryEngine.java @@ -0,0 +1,196 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.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========================================================= + */ + +// +//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 executeQuery(TransactionalGraph g, QueryBuilder query) { +// List 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 executeParentQuery(TransactionalGraph g, QueryBuilder query) { +// +// List 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 executeQuery(Vertex startVertex, String query) { +// +// return this.processGremlinQuery(startVertex, "_()" + query); +// +// } +// +// @Override +// public List findParents(Vertex start) { +// +// String findAllParents = ".as('x').inE.has('isParent', true).outV" +// + ".loop('x'){it.object.inE.has('isParent',true).count()==1}{true}"; +// +// List results = this.executeQuery(start, findAllParents); +// results.add(0, start); +// return results; +// +// } +// +// @Override +// public List findChildren(Vertex start) { +// String findAllChildren = ".as('x').outE.has('isParent', true).inV" +// + ".loop('x'){it.object.outE.has('isParent', true).count() >= 1}{true}"; +// +// List results = this.executeQuery(start, findAllChildren); +// results.add(0, start); +// return results; +// +// } +// +// @Override +// public List 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 results = this.executeQuery(start, findAllChildren); +// results.add(0, start); +// return results; +// } +// private List processGremlinQuery(String query) { +// +// Pattern firstHasSet = Pattern.compile("^(\\.has\\(.*?\\))(\\.has\\(.*?\\))*(?!\\.has)"); +// Pattern p = Pattern.compile("\\.has\\('(.*?)',\\s?'(.*?)'\\)"); +// Matcher m = firstHasSet.matcher(query); +// List results = null; +// GremlinPipeline 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 processGremlinQuery(Vertex startVertex, String query) { +// +// Pipe pipe = Gremlin.compile(query); +// pipe.setStarts(new SingleIterator(startVertex)); +// +// return (List)IteratorUtils.toList(pipe.iterator()); +// } +// private List processGremlinQuery(List list, String query) { +// +// Pipe pipe = Gremlin.compile(query); +// +// pipe.setStarts(list); +// +// return (List)IteratorUtils.toList(pipe.iterator()); +// } +// +// +// @Override +// public List 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 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 new file mode 100644 index 00000000..01f11b17 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/serialization/engines/query/QueryEngine.java @@ -0,0 +1,94 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.serialization.engines.query; + +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; +import org.apache.tinkerpop.gremlin.process.traversal.step.util.Tree; +import org.apache.tinkerpop.gremlin.structure.Direction; +import org.apache.tinkerpop.gremlin.structure.Edge; +import org.apache.tinkerpop.gremlin.structure.Element; +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; + + /** + * Instantiates a new query engine. + * + * @param graphEngine the graph engine + */ + public QueryEngine (GraphTraversalSource g) { + this.g = g; + } + + /** + * Find parents. + * + * @param start the start + * @return the list + */ + public abstract List findParents(Vertex start); + + /** + * Find children. + * + * @param start the start + * @return the list + */ + public abstract List findAllChildren(Vertex start); + + public abstract List findChildrenOfType(Vertex start, String type); + + public abstract List findChildren(Vertex start); + /** + * Find deletable. + * + * @param start the start + * @return the list + */ + public abstract List findDeletable(Vertex start); + + public Tree findSubGraph(Vertex start) { + return findSubGraph(start, AAIProperties.MAXIMUM_DEPTH, false); + } + public abstract Tree findSubGraph(Vertex start, int iterations, boolean nodeOnly); + /** + * Find related vertices. + * + * @param start the start + * @param direction the direction + * @param label the label + * @param nodeType the node type + * @return the list + */ + public abstract List findRelatedVertices(Vertex start, Direction direction, String label, String nodeType); + + public abstract List findEdgesForVersion(Vertex start, Loader loader); + + public abstract List findCousinVertices(Vertex start); + +} 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 new file mode 100644 index 00000000..f101f890 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/Console.java @@ -0,0 +1,43 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.serialization.queryformats; + +import com.google.gson.JsonObject; +import org.onap.aai.serialization.queryformats.exceptions.AAIFormatVertexException; + +public class Console implements FormatMapper { + + @Override + public JsonObject formatObject(Object v) throws AAIFormatVertexException { + + JsonObject json = new JsonObject(); + json.addProperty("result", v.toString()); + + return json; + } + + @Override + public int parallelThreshold() { + return 100; + } + +} 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 new file mode 100644 index 00000000..2904cce6 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/Format.java @@ -0,0 +1,31 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.serialization.queryformats; + +public enum Format { + graphson, + pathed, id, resource, + simple, + resource_and_url, + console, + raw +} 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 new file mode 100644 index 00000000..b19e0c3e --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/FormatFactory.java @@ -0,0 +1,97 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.serialization.queryformats; + +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; + +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.Loader; +import org.onap.aai.serialization.db.DBSerializer; +import org.onap.aai.serialization.queryformats.exceptions.QueryParamInjectionException; +import org.onap.aai.serialization.queryformats.utils.QueryParamInjector; +import org.onap.aai.serialization.queryformats.utils.UrlBuilder; + +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; + +public class FormatFactory { + + private final Loader loader; + private final DBSerializer serializer; + private final UrlBuilder urlBuilder; + private final QueryParamInjector injector; + public FormatFactory (Loader loader, DBSerializer serializer) throws AAIException { + this.loader = loader; + this.serializer = serializer; + this.urlBuilder = new UrlBuilder(loader.getVersion(), serializer); + this.injector = QueryParamInjector.getInstance(); + } + + public Formatter get(Format format) throws AAIException { + return get(format, new MultivaluedHashMap()); + } + + public Formatter get(Format format, MultivaluedMap params) throws AAIException { + + Formatter formattter = null; + + switch (format) { + case graphson : + formattter = new Formatter(inject(new GraphSON(), params)); + break; + case pathed : + formattter = new Formatter(inject(new PathedURL(loader, urlBuilder), params)); + break; + case id : + formattter = new Formatter(inject(new IdURL(loader, urlBuilder), params)); + break; + case resource : + formattter = new Formatter(inject(new Resource.Builder(loader, serializer, urlBuilder), params).build()); + break; + case resource_and_url : + formattter = new Formatter(inject(new Resource.Builder(loader, serializer, urlBuilder).includeUrl(), params).build()); + break; + case raw : + formattter = new Formatter(inject(new RawFormat.Builder(loader, serializer, urlBuilder), params).build()); + break; + case simple : + formattter = new Formatter(inject(new RawFormat.Builder(loader, serializer, urlBuilder).depth(0).modelDriven(), params).build()); + break; + case console : + formattter = new Formatter(inject(new Console(), params)); + break; + default : + break; + + } + + return formattter; + } + + private T inject (T obj, MultivaluedMap 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 new file mode 100644 index 00000000..fb822dd9 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/FormatMapper.java @@ -0,0 +1,32 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.serialization.queryformats; + +import com.google.gson.JsonObject; +import org.onap.aai.serialization.queryformats.exceptions.AAIFormatVertexException; + +public interface FormatMapper { + + public JsonObject formatObject(Object v) throws AAIFormatVertexException; + + public 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 new file mode 100644 index 00000000..50042b76 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/Formatter.java @@ -0,0 +1,80 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.serialization.queryformats; + +import com.att.eelf.configuration.EELFLogger; +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.serialization.queryformats.exceptions.AAIFormatVertexException; + +import java.util.List; +import java.util.Optional; +import java.util.stream.Stream; + +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 vertices) { + Stream stream = null; + JsonObject result = new JsonObject(); + JsonArray body = new JsonArray(); + if (vertices.size() >= format.parallelThreshold()) { + stream = vertices.parallelStream(); + } else { + stream = vertices.stream(); + } + final boolean isParallel = stream.isParallel(); + stream.map(v -> { + try { + return Optional.of(format.formatObject(v)); + } catch (AAIFormatVertexException e) { + LOGGER.warn("Failed to format vertex, returning a partial list", e); + } + + return Optional.empty(); + }).forEach(obj -> { + if (obj.isPresent()) { + if (isParallel) { + synchronized (body) { + body.add(obj.get()); + } + } else { + body.add(obj.get()); + } + } + }); + + 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 new file mode 100644 index 00000000..00aa781c --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/GraphSON.java @@ -0,0 +1,63 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.serialization.queryformats; + +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.thinkaurelius.titan.graphdb.tinkerpop.TitanIoRegistry; +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 java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStream; + +public class GraphSON implements FormatMapper { + + private final GraphSONMapper mapper = GraphSONMapper.build().addRegistry(TitanIoRegistry.INSTANCE).create(); + private final GraphSONWriter writer = GraphSONWriter.build().mapper(mapper).create(); + protected JsonParser parser = new JsonParser(); + + @Override + public 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(); + } + + return parser.parse(result).getAsJsonObject(); + + } + + @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 new file mode 100644 index 00000000..320cd616 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/IdURL.java @@ -0,0 +1,71 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.serialization.queryformats; + +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.onap.aai.db.props.AAIProperties; +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.Introspector; +import org.onap.aai.introspection.Loader; +import org.onap.aai.introspection.exceptions.AAIUnknownObjectException; +import org.onap.aai.serialization.queryformats.exceptions.AAIFormatVertexException; +import org.onap.aai.serialization.queryformats.utils.UrlBuilder; + +public class IdURL implements FormatMapper { + + 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 + public JsonObject formatObject(Object input) throws AAIFormatVertexException { + Vertex v = (Vertex)input; + try { + final Introspector searchResult = this.loader.introspectorFromName("result-data"); + + searchResult.setValue("resource-type", v.value(AAIProperties.NODE_TYPE)); + searchResult.setValue("resource-link", this.urlBuilder.id(v)); + + final String json = searchResult.marshal(false); + + return 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/PathedURL.java b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/PathedURL.java new file mode 100644 index 00000000..8b9d5058 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/PathedURL.java @@ -0,0 +1,70 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.serialization.queryformats; + +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.onap.aai.db.props.AAIProperties; +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.Introspector; +import org.onap.aai.introspection.Loader; +import org.onap.aai.introspection.exceptions.AAIUnknownObjectException; +import org.onap.aai.serialization.queryformats.exceptions.AAIFormatVertexException; +import org.onap.aai.serialization.queryformats.utils.UrlBuilder; + +public final class PathedURL implements FormatMapper { + + private final UrlBuilder urlBuilder; + private final JsonParser parser; + private final 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 JsonObject formatObject(Object input) throws AAIFormatVertexException { + Vertex v = (Vertex)input; + try { + final Introspector searchResult = this.loader.introspectorFromName("result-data"); + + searchResult.setValue("resource-type", v.value(AAIProperties.NODE_TYPE)); + + searchResult.setValue("resource-link", this.urlBuilder.pathed(v)); + final String json = searchResult.marshal(false); + return 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 new file mode 100644 index 00000000..7aaf3035 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/RawFormat.java @@ -0,0 +1,190 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.serialization.queryformats; + +import java.util.Iterator; +import java.util.List; + +import org.apache.tinkerpop.gremlin.structure.Direction; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.apache.tinkerpop.gremlin.structure.VertexProperty; +import org.onap.aai.db.props.AAIProperties; +import org.onap.aai.introspection.Loader; +import org.onap.aai.serialization.db.DBSerializer; +import org.onap.aai.serialization.queryformats.exceptions.AAIFormatVertexException; +import org.onap.aai.serialization.queryformats.params.Depth; +import org.onap.aai.serialization.queryformats.params.NodesOnly; +import org.onap.aai.serialization.queryformats.utils.UrlBuilder; + +import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; + + +public class RawFormat implements FormatMapper { + 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 JsonObject formatObject(Object input) throws AAIFormatVertexException { + Vertex v = (Vertex)input; + JsonObject json = new JsonObject(); + json.addProperty("id", v.id().toString()); + json.addProperty("node-type", v.value(AAIProperties.NODE_TYPE)); + json.addProperty("url", this.urlBuilder.pathed(v)); + json.add("properties", this.createPropertiesObject(v)); + if (!nodesOnly) { + json.add("related-to", this.createRelationshipObject(v)); + } + return json; + } + + @Override + public int parallelThreshold() { + return 100; + } + + + public JsonObject createPropertiesObject(Vertex v) throws AAIFormatVertexException { + JsonObject json = new JsonObject(); + Iterator> iter = v.properties(); + + while (iter.hasNext()) { + VertexProperty 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 json; + } + protected JsonArray createRelationshipObject(Vertex v) throws AAIFormatVertexException { + JsonArray jarray = new JsonArray(); + Iterator iter = v.vertices(Direction.BOTH); + + while (iter.hasNext()) { + Vertex related = iter.next(); + + JsonObject json = new JsonObject(); + json.addProperty("id", related.id().toString()); + json.addProperty("node-type", related.value(AAIProperties.NODE_TYPE)); + json.addProperty("url", this.urlBuilder.pathed(related)); + jarray.add(json); + } + + return jarray; + } + + public static class Builder implements NodesOnly, Depth { + + 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); + } + } + } +} 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 new file mode 100644 index 00000000..649971be --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/Resource.java @@ -0,0 +1,163 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.serialization.queryformats; + +import java.io.UnsupportedEncodingException; +import java.util.ArrayList; +import java.util.List; + +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.onap.aai.db.props.AAIProperties; +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.Introspector; +import org.onap.aai.introspection.Loader; +import org.onap.aai.introspection.exceptions.AAIUnknownObjectException; +import org.onap.aai.serialization.db.DBSerializer; +import org.onap.aai.serialization.queryformats.exceptions.AAIFormatVertexException; +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 com.google.gson.JsonObject; +import com.google.gson.JsonParser; + +public class Resource implements FormatMapper { + + 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 + public JsonObject formatObject(Object input) throws AAIFormatVertexException { + Vertex v = (Vertex)input; + JsonObject json = new JsonObject(); + + if (this.includeUrl) { + json.addProperty("url", this.urlBuilder.pathed(v)); + } + json.add(v.property(AAIProperties.NODE_TYPE) + .orElse(null), this.vertexToJsonObject(v)); + + return json; + } + + protected JsonObject vertexToJsonObject(Vertex v) throws AAIFormatVertexException { + try { + final Introspector obj = getLoader().introspectorFromName( + v.property(AAIProperties.NODE_TYPE) + .orElse(null) + ); + + final List 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 getParser().parse(json).getAsJsonObject(); + } catch (AAIUnknownObjectException e) { + throw new AAIFormatVertexException("Failed to format vertex - unknown object", e); + } + } + + @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, Depth { + + 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/SimpleFormat.java b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/SimpleFormat.java new file mode 100644 index 00000000..ba49e3a3 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/SimpleFormat.java @@ -0,0 +1,76 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.serialization.queryformats; + +import java.io.UnsupportedEncodingException; +import java.util.ArrayList; +import java.util.List; + +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.onap.aai.db.props.AAIProperties; +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.Introspector; +import org.onap.aai.introspection.exceptions.AAIUnknownObjectException; +import org.onap.aai.serialization.queryformats.exceptions.AAIFormatVertexException; + +import com.google.gson.JsonObject; + +public class SimpleFormat extends RawFormat { + + + protected SimpleFormat(Builder builder) { + super(builder); + + } + + @Override + public int parallelThreshold() { + return 20; + } + + @Override + public JsonObject createPropertiesObject(Vertex v) throws AAIFormatVertexException { + try { + final Introspector obj = loader.introspectorFromName( + v.property(AAIProperties.NODE_TYPE) + .orElse(null) + ); + + final List 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 parser.parse(json).getAsJsonObject(); + } catch (AAIUnknownObjectException e) { + throw new AAIFormatVertexException("Failed to format vertex - unknown object", e); + } + + + } +} 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 new file mode 100644 index 00000000..6a8acd2f --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/SubGraphStyle.java @@ -0,0 +1,28 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.serialization.queryformats; + +public enum SubGraphStyle { + star, + prune, + no_op +} 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 new file mode 100644 index 00000000..98b90050 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/exceptions/AAIFormatVertexException.java @@ -0,0 +1,41 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.serialization.queryformats.exceptions; + +public class AAIFormatVertexException extends Exception { + + private static final long serialVersionUID = -5814240841844624097L; + + public AAIFormatVertexException() {} + + public AAIFormatVertexException(String message) { + super(message); + } + + public AAIFormatVertexException(Throwable cause) { + super(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 new file mode 100644 index 00000000..313b8942 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/exceptions/QueryParamInjectionException.java @@ -0,0 +1,41 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.serialization.queryformats.exceptions; + +import org.onap.aai.exceptions.AAIException; + +public class QueryParamInjectionException extends AAIException { + + private static final long serialVersionUID = -5575661036426538012L; + + public QueryParamInjectionException(String message) { + super("AAI_4017", message); + } + + public QueryParamInjectionException(Throwable cause) { + super("AAI_4017",cause); + } + + 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 new file mode 100644 index 00000000..e98f0667 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/params/Depth.java @@ -0,0 +1,29 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.serialization.queryformats.params; + +@Inject(name = "depth") +public interface 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 new file mode 100644 index 00000000..18d85545 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/params/Inject.java @@ -0,0 +1,35 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.serialization.queryformats.params; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +@Retention(RetentionPolicy.RUNTIME) +public @interface Inject { + + /** + * 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 new file mode 100644 index 00000000..1429d552 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/params/NodesOnly.java @@ -0,0 +1,29 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.serialization.queryformats.params; + +@Inject(name = "nodesOnly") +public interface 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 new file mode 100644 index 00000000..e95de0db --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/params/Setter.java @@ -0,0 +1,37 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.serialization.queryformats.params; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.METHOD}) +/** + * Marks what method in the object should be used for setting the value + * of the query parameter + */ +public @interface Setter { + +} 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 new file mode 100644 index 00000000..29fb56df --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/utils/QueryParamInjector.java @@ -0,0 +1,85 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.serialization.queryformats.utils; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Set; + +import javax.ws.rs.core.MultivaluedMap; + +import org.onap.aai.serialization.queryformats.exceptions.QueryParamInjectionException; +import org.onap.aai.serialization.queryformats.params.Inject; +import org.onap.aai.serialization.queryformats.params.Setter; +import org.reflections.Reflections; + +public class QueryParamInjector { + + private final Set> 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 injectParams(T obj, MultivaluedMap 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 new file mode 100644 index 00000000..8387285d --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/serialization/queryformats/utils/UrlBuilder.java @@ -0,0 +1,92 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.serialization.queryformats.utils; + +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.net.URISyntaxException; + +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.Version; +import org.onap.aai.serialization.db.DBSerializer; +import org.onap.aai.serialization.queryformats.exceptions.AAIFormatVertexException; +import org.onap.aai.util.AAIApiServerURLBase; +import org.onap.aai.util.AAIConstants; +import org.onap.aai.workarounds.LegacyURITransformer; + +public class UrlBuilder { + + private final DBSerializer serializer; + private final Version version; + private final String serverBase; + + public UrlBuilder (Version version, DBSerializer serializer) throws AAIException { + this.serializer = serializer; + this.version = version; + this.serverBase = this.getServerBase(version); + } + + public UrlBuilder (Version version, DBSerializer serializer, String serverBase) { + this.serializer = serializer; + this.version = version; + this.serverBase = serverBase; + } + + public String pathed(Vertex v) throws AAIFormatVertexException { + + try { + final StringBuilder result = new StringBuilder(); + final URI uri = this.serializer.getURIForVertex(v); + + if (this.version.compareTo(Version.v11) >= 0) { + result.append(AAIConstants.AAI_APP_ROOT); + } else { + result.append(this.serverBase); + } + result.append(this.version); + result.append(uri); + + 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(Version.v11) >= 0) { + result.insert(0, AAIConstants.AAI_APP_ROOT); + } else { + result.insert(0, this.serverBase); + } + + return result.toString(); + } + + protected String getServerBase(Version v) throws AAIException { + return AAIApiServerURLBase.get(v); + } +} 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 new file mode 100644 index 00000000..82aa7443 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/serialization/tinkerpop/TreeBackedEdge.java @@ -0,0 +1,81 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.serialization.tinkerpop; + +import org.apache.tinkerpop.gremlin.structure.Direction; +import org.apache.tinkerpop.gremlin.structure.Edge; +import org.apache.tinkerpop.gremlin.structure.Graph; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.apache.tinkerpop.gremlin.structure.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, + * 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 bothVertices() { + return this.vertices(Direction.BOTH); + } + + @Override + public Iterator 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 new file mode 100644 index 00000000..e953dc2d --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/serialization/tinkerpop/TreeBackedVertex.java @@ -0,0 +1,163 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.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; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; + +/** + * 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. + * + */ + +public class TreeBackedVertex extends DetachedVertex implements Vertex { + + private static final long serialVersionUID = -976854460992756953L; + private final Tree tree; + private final Vertex self; + public TreeBackedVertex (Vertex v, Tree tree) { + super(v, true); + this.self = v; + this.tree = tree; + } + + @Override + public Iterator edges(final Direction direction, final String... edgeLabels) { + final List edges = tree.getObjectsAtDepth(2); + final List> trees = tree.getTreesAtDepth(2); + final List> 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 eTree = new Tree<>(); + for (Tree 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> trees) { + Tree vTree = new Tree<>(); + for (Tree tree : trees) { + if (tree.keySet().contains(v)) { + vTree = tree; + break; + } + } + + return new TreeBackedVertex((Vertex)vTree.keySet().iterator().next(), vTree); + } + @Override + public Iterator vertices(final Direction direction, final String... labels) { + final List> vertexElements = tree.getTreesAtDepth(3); + final List 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 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 itr = e.bothVertices(); + while (itr.hasNext()) { + list.add(itr.next()); + } + } + return list; + + }).flatMap(list -> list.stream()).map(v -> { + Tree vTree = new Tree(); + for (Tree 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/tasks/ScheduledTasks.java b/aai-core/src/main/java/org/onap/aai/tasks/ScheduledTasks.java new file mode 100644 index 00000000..9d2e8b68 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/tasks/ScheduledTasks.java @@ -0,0 +1,91 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.tasks; + +import java.io.File; +import java.util.Arrays; +import java.util.Date; +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.util.AAIConfig; +import org.onap.aai.util.AAIConstants; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +@Component +public class ScheduledTasks { + + 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 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(); + + LoggingContext.requestId(transId); + LoggingContext.partnerName(FROM_APP_ID); + LoggingContext.component(COMPONENT); + + 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; + + // 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.info("reloaded from aaiconfig.properties"); + } + break; + } + } + } +} diff --git a/aai-core/src/main/java/org/onap/aai/util/AAIApiServerURLBase.java b/aai-core/src/main/java/org/onap/aai/util/AAIApiServerURLBase.java new file mode 100644 index 00000000..45f671ef --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/util/AAIApiServerURLBase.java @@ -0,0 +1,81 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.util; + +import java.util.List; +import java.util.Map; + +import org.apache.cxf.helpers.CastUtils; +import org.apache.cxf.message.Message; +import org.apache.cxf.phase.PhaseInterceptorChain; + +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.Version; + +public class AAIApiServerURLBase { + + /** + * Gets the. + * + * @return the string + * @throws AAIException the AAI exception + */ + public static String get() throws AAIException { + + String hostName = null; + try { + Message message = PhaseInterceptorChain.getCurrentMessage(); + Map> headers = CastUtils.cast((Map) message.get(Message.PROTOCOL_HEADERS)); + List sa = null; + if (headers != null) { + sa = headers.get("host"); + } + + if (sa != null && sa.size() == 1) { + hostName = "https://"+ sa.get(0).toString() + "/aai/"; + } + } catch (Exception e) { + // TODO: we may want to log an error here + } + // TODO: should this check the value a little closer and look for a pattern? + if (hostName == null) { + hostName = AAIConfig.get(AAIConstants.AAI_SERVER_URL_BASE); + //AAIConstants.AAI_SERVER_URL_BASE; + } + return hostName; + } + + /** + * Gets the. + * + * @param v the v + * @return the string + * @throws AAIException the AAI exception + */ + public static String get(Version v) throws AAIException { + String hostName = null; + hostName = AAIApiServerURLBase.get(); + + return hostName; + } + +} diff --git a/aai-core/src/main/java/org/onap/aai/util/AAIApiVersion.java b/aai-core/src/main/java/org/onap/aai/util/AAIApiVersion.java new file mode 100644 index 00000000..042fd177 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/util/AAIApiVersion.java @@ -0,0 +1,75 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.util; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.cxf.message.Message; +import org.apache.cxf.phase.PhaseInterceptorChain; + +import org.onap.aai.exceptions.AAIException; + +public class AAIApiVersion { + + private static final Pattern versionPattern = Pattern.compile("(^|\\/)(v\\d+)\\/"); + + private static final Pattern latestVersionPattern = Pattern.compile("(^|\\/)(latest)\\/"); + + /** + * Gets the. + * + * @return the string + * @throws AAIException the AAI exception + */ + public static String get() throws AAIException { + + String apiVersion = null; + try { + Message message = PhaseInterceptorChain.getCurrentMessage(); + String requestURI = (String) message.get(Message.REQUEST_URI); + + if (requestURI != null) { + Matcher matcher = versionPattern.matcher(requestURI); + if (matcher.find() && matcher.groupCount() >= 2) { + apiVersion = matcher.group(2); + } + if (apiVersion == null) { + Matcher latestMatcher = latestVersionPattern.matcher(requestURI); + if (latestMatcher.find() && latestMatcher.groupCount() >= 2) { + apiVersion = AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP, AAIConstants.AAI_DEFAULT_API_VERSION); + } + } + + } + + } catch (Exception e) { + // TODO: we may want to log an error here + } + // TODO: should this check the value a little closer and look for a pattern? + if (apiVersion == null || !apiVersion.startsWith("v")) { + apiVersion = AAIConfig.get (AAIConstants.AAI_DEFAULT_API_VERSION_PROP, AAIConstants.AAI_DEFAULT_API_VERSION); + //apiVersion = AAIConstants.AAI_DEFAULT_API_VERSION; + } + return apiVersion; + } +} diff --git a/aai-core/src/main/java/org/onap/aai/util/AAICSVWriter.java b/aai-core/src/main/java/org/onap/aai/util/AAICSVWriter.java new file mode 100644 index 00000000..c091fc24 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/util/AAICSVWriter.java @@ -0,0 +1,168 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +/** + * + */ +package org.onap.aai.util; + +import java.io.IOException; +import java.io.PrintWriter; +import java.io.Writer; + +import com.opencsv.CSVWriter; + +/** + * had to overwrite the separate character to separate string + * Based on the public - A very simple CSV writer released under a commercial-friendly license. + * + + */ +public class AAICSVWriter extends CSVWriter { + + private String separatorStr; + private char overridequotechar; + private String overridelineEnd; + private Writer rawWriter; + private PrintWriter pw; + + /** + * Instantiates a new AAICSV writer. + * + * @param writer the writer + */ + public AAICSVWriter(Writer writer) { + super(writer); + // TODO Auto-generated constructor stub + } + + /** + * Constructs AAICSVWriter with supplied separator string and quote char. + * + * @param writer the writer to an underlying CSV source. + * @param overrideseparator the overrideseparator + * @param quotechar the character to use for quoted elements + * @param lineEnd the line feed terminator to use + */ + public AAICSVWriter(Writer writer, String overrideseparator, char quotechar, String lineEnd) { + super(writer, CSVWriter.DEFAULT_SEPARATOR, quotechar, DEFAULT_ESCAPE_CHARACTER, lineEnd); + separatorStr = overrideseparator; + overridequotechar = quotechar; + overridelineEnd = lineEnd; + this.rawWriter = writer; + this.pw = new PrintWriter(writer); + } + + /** + * String contains special characters. + * + * @param line the line + * @return true, if successful + */ + private boolean stringContainsSpecialCharacters(String line) { + return line.indexOf(overridequotechar) != -1 || line.indexOf(DEFAULT_ESCAPE_CHARACTER) != -1 || line.indexOf(separatorStr) != -1 || line.contains("\n") || line.contains("\r"); + } + + /** + * Close the underlying stream writer flushing any buffered content. + * + * @throws IOException if bad things happen + */ + public void close() throws IOException { + flush(); + pw.close(); + rawWriter.close(); + } + + /** + * Writes the next line to the file. + * + * @param nextLine a string array with each comma-separated element as a separate + * entry. + * @param applyQuotesToAll true if all values are to be quoted. false applies quotes only + * to values which contain the separator, escape, quote or new line characters. + */ + public void writeNext(String[] nextLine, boolean applyQuotesToAll) { + + if (nextLine == null) + return; + + StringBuilder sb = new StringBuilder(INITIAL_STRING_SIZE); + for (int i = 0; i < nextLine.length; i++) { + + if (i != 0) { + sb.append(separatorStr); + } + + String nextElement = nextLine[i]; + + if (nextElement == null) + continue; + + Boolean stringContainsSpecialCharacters = stringContainsSpecialCharacters(nextElement); + + if ((applyQuotesToAll || stringContainsSpecialCharacters) && overridequotechar != NO_QUOTE_CHARACTER) + sb.append(overridequotechar); + + if (stringContainsSpecialCharacters) { + sb.append(processLine(nextElement)); + } else { + sb.append(nextElement); + } + + if ((applyQuotesToAll || stringContainsSpecialCharacters) && overridequotechar != NO_QUOTE_CHARACTER) + sb.append(overridequotechar); + } + + sb.append(overridelineEnd); + pw.write(sb.toString()); + } + + + /** + * Writes the next line to the file ignoring all exceptions. + * + * @param nextLine a string array with each comma-separated element as a separate + * entry. + */ + public void writeColumn(String[] nextLine) { + + if (nextLine == null) + return; + + StringBuilder sb = new StringBuilder(INITIAL_STRING_SIZE); + for (int i = 0; i < nextLine.length; i++) { + + + String nextElement = nextLine[i]; + + if (nextElement == null) + continue; + + sb.append(nextElement); + + + } + + sb.append(overridelineEnd); + pw.write(sb.toString()); + } +} 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 new file mode 100644 index 00000000..445fa0dd --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/util/AAIConfig.java @@ -0,0 +1,267 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.util; + +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.net.InetAddress; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Properties; +import java.util.Timer; + +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; + + +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 boolean propsInitialized = false; + + // this (probably) won't change between releases, put it in the config if it gets annoying... + private static HashMap> defaultBools = new HashMap>(); + private static Timer timer = new Timer(); + + /** + * Instantiates a new AAI config. + */ + // Don't instantiate + private AAIConfig() {} + + /** + * Inits the. + * + * @throws AAIException the AAI exception + */ + public synchronized static void init() throws AAIException{ + LOGGER.info("Initializing AAIConfig"); + + ArrayList genericVnfBools = new ArrayList(); + ArrayList l3NetworkBools = new ArrayList(); + ArrayList pserverBools = new ArrayList(); + ArrayList subnetBools = new ArrayList(); + ArrayList vserverBools = new ArrayList(); + ArrayList vnfcBools = new ArrayList(); + + genericVnfBools.add("in-maint"); + genericVnfBools.add("is-closed-loop-disabled"); + l3NetworkBools.add("is-bound-to-vpn"); + pserverBools.add("in-maint"); + subnetBools.add("dhcp-enabled"); + vserverBools.add("in-maint"); + vserverBools.add("is-closed-loop-disabled"); + vnfcBools.add("in-maint"); + vnfcBools.add("is-closed-loop-disabled"); + + defaultBools.put("generic-vnf", genericVnfBools); + defaultBools.put("l3-network", l3NetworkBools); + defaultBools.put("pserver", pserverBools); + defaultBools.put("subnet", subnetBools); + defaultBools.put("vserver", vserverBools); + defaultBools.put("vnfc", vnfcBools); + + AAIConfig.getConfigFile(); + AAIConfig.reloadConfig(); + + if (AAIConstants.AAI_NODENAME == null || AAIConstants.AAI_NODENAME == "") { + ErrorLogHelper.logError("AAI_4005", " AAI_NODENAME is not defined"); + } else { + LOGGER.info("A&AI Server Node Name = " + AAIConstants.AAI_NODENAME); + } + } + + /** + * Gets the default bools. + * + * @return the default bools + */ + public static HashMap> getDefaultBools() { + return defaultBools; + } + + /** + * Cleanup. + */ + public static void cleanup() { + timer.cancel(); + } + + /** + * Gets the config file. + * + * @return the config file + */ + public static String getConfigFile() { +// if (GlobalPropFileName == null) { +// String nc = System.getProperty("aaiconfig"); +// if (nc == null) nc = "/home/aaiadmin/etc/aaiconfig.props"; +// logger.info( "aaiconfig = " + nc==null?"null":nc); +// GlobalPropFileName = nc; +// } + return GLOBAL_PROP_FILE_NAME; + } + + /** + * Reload config. + */ + public synchronized static void reloadConfig() { + + String propFileName = GLOBAL_PROP_FILE_NAME; + Properties newServerProps = null; + + LOGGER.info("Reloading config from " + propFileName); + + try { + InputStream is = new FileInputStream(propFileName); + newServerProps = new Properties(); + newServerProps.load(is); + propsInitialized = true; + + serverProps = newServerProps; + newServerProps = null; + + } catch (FileNotFoundException fnfe) { + ErrorLogHelper.logError("AAI_4001", " " + propFileName + ". Exception: "+fnfe.getMessage()); + } catch (IOException e) { + ErrorLogHelper.logError("AAI_4002", " " + propFileName + ". IOException: "+e.getMessage()); + } + } + + /** + * Gets the. + * + * @param key the key + * @param defaultValue the default value + * @return the string + */ + public static String get(String key, String defaultValue) { + String result = defaultValue; + try { + result = get (key); + } + catch ( AAIException a ) { + + } + return ( result ); + } + + /** + * Gets the. + * + * @param key the key + * @return the string + * @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; + } + + /** + * Gets the int. + * + * @param key the key + * @return the int + * @throws AAIException the AAI exception + */ + public static int getInt(String key) throws AAIException{ + return Integer.valueOf(AAIConfig.get(key)); + } + + /** + * Gets the server props. + * + * @return the server props + */ + public static Properties getServerProps() { + return serverProps; + } + + /** + * Gets the node name. + * + * @return the node name + */ + public static String getNodeName() { + try { + InetAddress ip = InetAddress.getLocalHost(); + if (ip != null) { + String hostname = ip.getHostName(); + if (hostname != null) { + return hostname; + } + } + } catch (Exception e) { + return null; + } + return null; + } + + + /** + * 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 new file mode 100644 index 00000000..9c301871 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/util/AAIConfigCommandLinePropGetter.java @@ -0,0 +1,67 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.util; + +import org.onap.aai.exceptions.AAIException; + +/* + * The script deobfuscatePW.sh needs to retrieve pws from the AAIConfig file. + * As AAIConfig has no main to be callable on the command line, this class helps + * by providing one for accessing AAIConfig that way. + * (AAIConfig deobfuscates pws itself, so we just need to call its .get() on the desired pw.) + * + * This could be used to get any property from AAIConfig via the command line, + * not just the pws, even though it was made for pw-related needs. + */ +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); + } + + } + +} 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 new file mode 100644 index 00000000..9b7afe52 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/util/AAIConstants.java @@ -0,0 +1,152 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.util; + +import org.onap.aai.db.props.AAIProperties; + +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"); + // + /** 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; + + /** etc directory, relative to AAI_HOME */ + public static final String AAI_HOME_ETC = AAI_HOME_BUNDLECONFIG + AAI_FILESEP + "etc" + AAI_FILESEP; + public static final String AAI_HOME_ETC_APP_PROPERTIES = AAI_HOME_ETC + "appprops" + AAI_FILESEP; + public static final String AAI_V2_OUTPUT_TRANSFORMS = AAIConstants.AAI_HOME_ETC_APP_PROPERTIES + AAIConstants.AAI_FILESEP + "output" + AAIConstants.AAI_FILESEP; + public static final String AAI_HOME_ETC_AUTH = AAI_HOME_ETC + "auth" + AAI_FILESEP; + public static final String AAI_CONFIG_FILENAME = AAI_HOME_ETC_APP_PROPERTIES + "aaiconfig.properties"; + public static final String AAI_AUTH_CONFIG_FILENAME = AAI_HOME_ETC_AUTH + "aai_policy.json"; + public static final String AAI_MECHID_CONFIG_FILENAME = AAI_HOME_ETC_APP_PROPERTIES + "mechIds.json"; + public static final String AAI_HOME_ETC_QUERY = AAI_HOME_ETC + "query" + AAI_FILESEP + "stored-queries.properties"; + public static final String REALTIME_DB_CONFIG = AAI_HOME_ETC_APP_PROPERTIES + "titan-realtime.properties"; + public static final String CACHED_DB_CONFIG = AAI_HOME_ETC_APP_PROPERTIES + "titan-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_PROV_LOGBACK_PROPS = "prov-logback.xml"; + public static final String AAI_GETRES_LOGBACK_PROPS = "getres-logback.xml"; + public static final String AAI_DELTOOL_LOGBACK_PROPS = "deltool-logback.xml"; + public static final String AAI_UPDTOOL_LOGBACK_PROPS = "updtool-logback.xml"; + public static final String AAI_PUTTOOL_LOGBACK_PROPS = "puttool-logback.xml"; + public static final String AAI_POSTTOOL_LOGBACK_PROPS = "posttool-logback.xml"; + public static final String AAI_NOTIFYSDNCTOOL_LOGBACK_PROPS = "notifysdnctool-logback.xml"; + public static final String AAI_RSHIPTOOL_LOGBACK_PROPS = "rshiptool-logback.xml"; + public static final String AAI_LOGBACK_PROPS = "logback.xml"; + + + public static final String AAI_CREATE_DB_SCHEMA_LOGBACK_PROPS = "createDBSchema-logback.xml"; + public static final String AAI_PULL_INV_DATA_LOGBACK_PROPS = "pullInvData-logback.xml"; + public static final String AAI_DATA_GROOMING_LOGBACK_PROPS = "dataGrooming-logback.xml"; + public static final String AAI_DATA_SNAPSHOT_LOGBACK_PROPS = "dataSnapshot-logback.xml"; + public static final String AAI_SCHEMA_MOD_LOGBACK_PROPS = "schemaMod-logback.xml"; + public static final String AAI_FORCE_DELETE_LOGBACK_PROPS = "forceDelete-logback.xml"; + + public static final String AAI_LOAD_DATA_DHV_LOGBACK_PROPS = "loadDataForDHV-logback.xml"; + + public static final String AVPN_INTERIM_LAG_INTERFACE = "aai.avpn.interim.laginterface"; + + public static final String AAI_TRUSTSTORE_FILENAME = "aai.truststore.filename"; + public static final String AAI_TRUSTSTORE_PASSWD = "aai.truststore.passwd"; + public static final String AAI_KEYSTORE_FILENAME = "aai.keystore.filename"; + public static final String AAI_KEYSTORE_PASSWD = "aai.keystore.passwd"; + + public static final String AAI_OLDSERVER_URL_BASE = "aai.oldserver.url.base"; + public static final String AAI_SERVER_URL_BASE = "aai.server.url.base"; + public static final String AAI_SERVER_URL = "aai.server.url"; + public static final String AAI_OLDSERVER_URL = "aai.oldserver.url"; + public static final String AAI_GLOBAL_CALLBACK_URL = "aai.global.callback.url"; + public static final String AAI_LOCAL_REST = "https://localhost:%d/aai/" + AAIProperties.LATEST + "/"; + public static final String AAI_APP_ROOT = "/aai/"; + + public static final int AAI_RESOURCES_PORT = 8447; + public static final int AAI_QUERY_PORT = 8446; + public static final int AAI_LEGACY_PORT = 8443; + + public static final String AAI_DEFAULT_API_VERSION = "v7"; + public static final String AAI_DEFAULT_API_VERSION_PROP = "aai.default.api.version"; + public static final String AAI_NOTIFICATION_CURRENT_VERSION = "aai.notification.current.version"; + + public static final String AAI_NODENAME = "aai.config.nodename"; + + public static final String AAI_LOGGING_HBASE_INTERCEPTOR = "aai.logging.hbase.interceptor"; + public static final String AAI_LOGGING_HBASE_ENABLED = "aai.logging.hbase.enabled"; + public static final String AAI_LOGGING_HBASE_LOGREQUEST = "aai.logging.hbase.logrequest"; + public static final String AAI_LOGGING_HBASE_LOGRESPONSE = "aai.logging.hbase.logresponse"; + + public static final String AAI_LOGGING_TRACE_ENABLED = "aai.logging.trace.enabled"; + public static final String AAI_LOGGING_TRACE_LOGREQUEST = "aai.logging.trace.logrequest"; + public static final String AAI_LOGGING_TRACE_LOGRESPONSE = "aai.logging.trace.logresponse"; + + public static final String AAI_CONFIG_CHECKINGTIME = "aai.config.checktime"; + public static final String AAI_DBMODEL_FILENAME = "aai.dbmodel.filename"; + public static final String AAI_RESVERSION_ENABLEFLAG = "aai.resourceversion.enableflag"; + + public static final int AAI_MAX_TRANS_RETRIES = 5; + public static final long AAI_TRANS_RETRY_SLEEP_MSEC = 500; + + public static final int AAI_GROOMING_DEFAULT_MAX_FIX = 150; + public static final int AAI_GROOMING_DEFAULT_SLEEP_MINUTES = 7; + + public static final int AAI_DUPETOOL_DEFAULT_MAX_FIX = 25; + public static final int AAI_DUPETOOL_DEFAULT_SLEEP_MINUTES = 7; + + public static final String LOGGING_MAX_STACK_TRACE_ENTRIES = "aai.logging.maxStackTraceEntries"; + + /** Default to skipping real-time grooming unless system property aai.skiprealtime.grooming is set to "false" */ + public static final String AAI_SKIPREALTIME_GROOMING = (System.getProperty("aai.skiprealtime.grooming") == null) ? "true" : System.getProperty("aai.skiprealtime.grooming"); + + + /*** UEB ***/ + public static final String UEB_PUB_PARTITION_AAI = "AAI"; + public static final String UEB_PUB_AAI_VCE_INTERFACE_DATA_TOPIC = "ueb.pub.aai.vce.interface.data.topic"; + + + /** Service description for Hosted Communications */ + public static final String AAI_SERVICEDESCRIPTION_HOSTEDCOMM = "aai.servicedescription.hostedcomm"; + + /** Service description for Mobility */ + public static final String AAI_SERVICEDESCRIPTION_MOBILITY = "aai.servicedescription.mobility"; + + /** Service description for Mobility */ + public static final String AAI_SERVICEDESCRIPTION_VUSP = "aai.servicedescription.vusp"; + + /** Service description for Vvig */ + public static final String AAI_SERVICEDESCRIPTION_VVIG = "aai.servicedescription.vvig"; + + /** Service description for LRSI */ + public static final String AAI_SERVICEDESCRIPTION_LRSI = "aai.servicedescription.lrsi"; + + /** + * Instantiates a new AAI constants. + */ + private AAIConstants() { + // prevent instantiation + } + +} diff --git a/aai-core/src/main/java/org/onap/aai/util/AAIMechIdConfig.java b/aai-core/src/main/java/org/onap/aai/util/AAIMechIdConfig.java new file mode 100644 index 00000000..04d0774b --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/util/AAIMechIdConfig.java @@ -0,0 +1,130 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.util; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Set; + +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; + +import org.onap.aai.logging.ErrorLogHelper; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +public class AAIMechIdConfig { + private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(AAIMechIdConfig.class); + private static final String mechIdConfigFileName = AAIConstants.AAI_HOME_ETC_APP_PROPERTIES + "mechid-config.json"; + + public static final String SYSTEM_GFP_IP = "GFP"; + public static final String SYSTEM_GCP = "GCP"; + public static final String SYSTEM_DCAE = "DCAE"; + public static final String SYSTEM_RUBY = "RUBY"; + public static final String SYSTEM_ACTION = "ACTION"; + public static final String SYSTEM_INSTAR = "INSTAR-LPP-AMS"; + public static final String FILE_CLASS_GFP_IP = "GFP-IP"; + public static final String FILE_CLASS_INSTAR = "INSTAR-LPP-AMS"; + + public static HashMap mechIdtoSystem = new HashMap(); + public static HashMap> fileClassToMechId = new HashMap>(); + + /** + * Inits the. + * + * @param tId the t id + * @param appId the app id + * @param logger the logger + */ + public static void init() { + LOGGER.debug("Initializing AAIMechIdConfig"); + Boolean enable; + String systemMechId = ""; + JSONParser parser = new JSONParser(); + + try { + Object obj = parser.parse(new FileReader(mechIdConfigFileName)); + JSONObject jsonObject = (JSONObject) obj; + JSONObject mechIds = (JSONObject) jsonObject.get("mech-ids"); + + @SuppressWarnings("unchecked") + Set systemSet = mechIds.keySet(); + for (String system : systemSet) { + JSONObject systemJsonObj = (JSONObject) mechIds.get(system); + systemMechId = (String) systemJsonObj.get("mechid"); + enable = (Boolean) systemJsonObj.get("enable"); + if (systemMechId != null && !systemMechId.isEmpty() && enable != null && enable == true) { + mechIdtoSystem.put(systemMechId, system); + JSONArray fileClasses = (JSONArray) systemJsonObj.get("file-classes"); + if (fileClasses != null ) { + String fileClass = ""; + for (Object fileClassObj : fileClasses) { + fileClass = (String) fileClassObj; + + if (!fileClassToMechId.containsKey(fileClass)) { + fileClassToMechId.put(fileClass, new ArrayList()); + fileClassToMechId.get(fileClass).add(systemMechId); + } else { + if(!fileClassToMechId.get(fileClass).contains(systemMechId)){ + fileClassToMechId.get(fileClass).add(systemMechId); + + } + } + } + } + } + } + + } catch (FileNotFoundException fnfe) { + ErrorLogHelper.logError("AAI_4001", + " " + mechIdConfigFileName + ". Exception: " + fnfe.getMessage()); + } catch (Exception e) { + ErrorLogHelper.logError("AAI_4004", + " " + mechIdConfigFileName + ". Exception: " + e.getMessage()); + } + } + + + /** + * Transform mech id to pickup dir. + * + * @param systemMechId the system mech id + * @return the string + */ + public static String transformMechIdToPickupDir(String systemMechId) { + String pickupDir = ""; + if (systemMechId != null && !systemMechId.isEmpty()) { + pickupDir = "/opt/aaihome/" + systemMechId + "/pickup"; + + if (pickupDir != null && !pickupDir.isEmpty() && new File(pickupDir).isDirectory()) { + return pickupDir; + } + + } + return null; + } + +} diff --git a/aai-core/src/main/java/org/onap/aai/util/AAIRSyncUtility.java b/aai-core/src/main/java/org/onap/aai/util/AAIRSyncUtility.java new file mode 100644 index 00000000..f20346eb --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/util/AAIRSyncUtility.java @@ -0,0 +1,198 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +/** + * + */ +package org.onap.aai.util; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.util.ArrayList; +import java.util.List; +import java.util.StringTokenizer; + +import org.onap.aai.exceptions.AAIException; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + + +public class AAIRSyncUtility { + + private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(AAIRSyncUtility.class); + private final String DEFAULT_CHECK = new String("aai.primary.filetransfer."); + + /** + * Instantiates a new AAIR sync utility. + */ + public AAIRSyncUtility() { + + } + + /** + * Do command. + * + * @param command the command + * @return the int + * @throws Exception the exception + */ + public int doCommand(List command) + throws Exception + { + String s = null; + + ProcessBuilder pb = new ProcessBuilder(command); + Process process = pb.start(); + + BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream())); + BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream())); + + LOGGER.debug("Here is the standard output of the command:\n"); + while ((s = stdInput.readLine()) != null) + { + LOGGER.debug(s); + } + + LOGGER.debug("Here is the standard error of the command (if any):\n"); + while ((s = stdError.readLine()) != null) + { + LOGGER.debug(s); + } + return process.waitFor(); + } + + + /** + * Method sendRsyncCommand. + * + * @param transId the trans id + * @param fileName the file name + */ + public void sendRsyncCommand(String transId, String fileName) + { + String aaiServerList = null; + String rsyncOptionsList = null; + + try { + aaiServerList = AAIConfig.get(DEFAULT_CHECK + "serverlist"); + rsyncOptionsList = AAIConfig.get("aai.rsync.options.list"); + String enableRsync = AAIConfig.get("aai.rsync.enabled"); + + if (!AAIConfig.isEmpty(enableRsync) && "n".equalsIgnoreCase(enableRsync)){ + LOGGER.info("rsync not invoked for " + fileName + ": rsync is not enabled in aaiconfig.properties"); + return; + } + } catch ( Exception e ) { + LOGGER.warn( "rsync not invoked: missing aaiconfig.properties entries for rsync" ); + } + + LOGGER.info("rsync to copy files started...."); + + ArrayList remoteHostList = new ArrayList(); + StringTokenizer serverList = new StringTokenizer( aaiServerList, "|" ); + String host = null; + try { + host = getHost(); + String remoteConnString = null; + + remoteHostList = getRemoteHostList(serverList, host); + LOGGER.debug("This host:" + host); + String pickUpDirectory = AAIConfig.get("instar.pickup.dir"); + String user = AAIConfig.get("aai.rsync.remote.user"); + String rsyncCmd = AAIConfig.get("aai.rsync.command"); + + //Push: rsync [OPTION...] SRC... [USER@]HOST:DEST + + java.util.Iterator remoteHostItr = remoteHostList.iterator(); + while (!remoteHostList.isEmpty() && remoteHostItr.hasNext()) { + String remoteHost = remoteHostItr.next(); + remoteConnString =user+"@"+remoteHost+":"+pickUpDirectory; + + List commands = new ArrayList(); + commands.add(rsyncCmd); + StringTokenizer optionTks = new StringTokenizer( rsyncOptionsList, "|" ); + while (optionTks.hasMoreTokens()){ + commands.add(optionTks.nextToken()); + } + commands.add(fileName); // src directory/fileName + commands.add(remoteConnString); // target username/host/path + LOGGER.debug("Commands: " + commands.toString()); + int rsyncResult = doCommand(commands); + if ( rsyncResult == 0 ) { + LOGGER.info("rsync completed for "+remoteHost); + }else { + LOGGER.error("rsync failed for "+ remoteHost+ " with response code "+rsyncResult ); + } + } + } catch ( Exception e) { + LOGGER.error("no server found processing serverList for host " + host + ": " + e.getMessage() + " (AAI_4000)"); + } + } + + /** + * Gets the remote host list. + * + * @param serverList the server list + * @param host the host + * @return the remote host list + */ + private ArrayList getRemoteHostList(StringTokenizer serverList, String host) { + ArrayList remoteHostList = new ArrayList(); + String remoteHost = null; + while ( serverList.hasMoreTokens() ) { + remoteHost = serverList.nextToken(); + if (!host.equalsIgnoreCase(remoteHost)){ + remoteHostList.add(remoteHost); + } + } + return remoteHostList; + } + + /** + * Gets the host. + * + * @return the host + * @throws AAIException the AAI exception + */ + private String getHost() throws AAIException { + String aaiServerList = AAIConfig.get(DEFAULT_CHECK + "serverlist"); + String hostname = null; + try { + InetAddress ip = InetAddress.getLocalHost(); + if ( ip != null ) { + hostname = ip.getHostName(); + if ( hostname != null ) { + if ( !( aaiServerList.contains(hostname) ) ) + LOGGER.warn("Host name not found in server list " + hostname); + } else + LOGGER.warn("InetAddress returned null hostname"); + } + + } catch (UnknownHostException e) { + LOGGER.warn("InetAddress getLocalHost exception " + e.getMessage()); + } + + return hostname; + } + +} 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 new file mode 100644 index 00000000..b672ffb2 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/util/Entity.java @@ -0,0 +1,197 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.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 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" +}) +public class Entity { + + @JsonProperty("equipment-role") + private String equipmentRole; + @JsonProperty("action") + private String action; + @JsonProperty("key-value-list") + private List keyValueList = new ArrayList(); + @JsonProperty("self-link") + private String selfLink; + @JsonIgnore + private Map additionalProperties = new HashMap(); + + /** + * + * @return + * The equipmentRole + */ + @JsonProperty("equipment-role") + public String getEquipmentRole() { + return equipmentRole; + } + + /** + * + * @param equipmentRole + * The equipment-role + */ + @JsonProperty("equipment-role") + public void setEquipmentRole(String equipmentRole) { + this.equipmentRole = equipmentRole; + } + + public Entity withEquipmentRole(String equipmentRole) { + this.equipmentRole = equipmentRole; + return this; + } + + /** + * + * @return + * The action + */ + @JsonProperty("action") + public String getAction() { + return action; + } + + /** + * + * @param action + * The action + */ + @JsonProperty("action") + public void setAction(String action) { + this.action = action; + } + + public Entity withAction(String action) { + this.action = action; + return this; + } + + /** + * + * @return + * The keyValueList + */ + @JsonProperty("key-value-list") + public List getKeyValueList() { + return keyValueList; + } + + /** + * + * @param keyValueList + * The key-value-list + */ + @JsonProperty("key-value-list") + public void setKeyValueList(List keyValueList) { + this.keyValueList = keyValueList; + } + + public Entity withKeyValueList(List keyValueList) { + this.keyValueList = keyValueList; + return this; + } + + /** + * + * @return + * The selfLink + */ + @JsonProperty("self-link") + public String getSelfLink() { + return selfLink; + } + + /** + * + * @param selfLink + * The self-link + */ + @JsonProperty("self-link") + public void setSelfLink(String selfLink) { + this.selfLink = selfLink; + } + + public Entity withSelfLink(String selfLink) { + this.selfLink = selfLink; + return this; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + @JsonAnySetter + public void setAdditionalProperty(String name, Object value) { + this.additionalProperties.put(name, value); + } + + public Entity withAdditionalProperty(String name, Object value) { + this.additionalProperties.put(name, value); + return this; + } + + @Override + public int hashCode() { + return new HashCodeBuilder().append(equipmentRole).append(action).append(keyValueList).append(selfLink).append(additionalProperties).toHashCode(); + } + + @Override + public boolean equals(Object other) { + if (other == this) { + return true; + } + if ((other instanceof Entity) == false) { + 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(); + } + +} 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 new file mode 100644 index 00000000..fb91795a --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/util/EntityList.java @@ -0,0 +1,113 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.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 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" +}) +public class EntityList { + + @JsonProperty("entity") + private List entity = new ArrayList(); + @JsonIgnore + private Map additionalProperties = new HashMap(); + + /** + * + * @return + * The entity + */ + @JsonProperty("entity") + public List getEntity() { + return entity; + } + + /** + * + * @param entity + * The entity + */ + @JsonProperty("entity") + public void setEntity(List entity) { + this.entity = entity; + } + + public EntityList withEntity(List entity) { + this.entity = entity; + return this; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + @JsonAnySetter + public void setAdditionalProperty(String name, Object value) { + this.additionalProperties.put(name, value); + } + + public EntityList withAdditionalProperty(String name, Object value) { + this.additionalProperties.put(name, value); + return this; + } + + @Override + public int hashCode() { + return new HashCodeBuilder().append(entity).append(additionalProperties).toHashCode(); + } + + @Override + public boolean equals(Object other) { + if (other == this) { + return true; + } + if ((other instanceof EntityList) == false) { + return false; + } + EntityList rhs = ((EntityList) other); + 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 new file mode 100644 index 00000000..55d0123f --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/util/FileWatcher.java @@ -0,0 +1,60 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.util; + +import java.util.*; +import java.io.*; + +public abstract class FileWatcher extends TimerTask { + 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(); + } + + /** + * runs a timer task + * @see java.util.TimerTask.run + */ + public final void run() { + long timeStamp = file.lastModified(); + + if( (timeStamp - this.timeStamp) > 500 ) { + this.timeStamp = timeStamp; + onChange(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 new file mode 100644 index 00000000..bf44dd19 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/util/FormatDate.java @@ -0,0 +1,47 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.util; + +import java.time.ZoneId; +import java.time.ZonedDateTime; +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))); + } +} diff --git a/aai-core/src/main/java/org/onap/aai/util/GenerateXsd.java b/aai-core/src/main/java/org/onap/aai/util/GenerateXsd.java new file mode 100644 index 00000000..c9405264 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/util/GenerateXsd.java @@ -0,0 +1,1698 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.util; + +import com.google.common.base.Joiner; +import com.jayway.jsonpath.JsonPath; +import org.onap.aai.introspection.Version; +import org.onap.aai.serialization.db.EdgeProperty; +import org.w3c.dom.*; + +import javax.xml.XMLConstants; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.xpath.*; +import java.io.*; +import java.nio.charset.Charset; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.*; + + + +public class GenerateXsd { + + static String apiVersion = null; + static String apiVersionFmt = null; + static boolean useAnnotationsInXsd = false; + static String responsesUrl = null; + static String responsesLabel = null; + static String jsonEdges = null; + + static Map generatedJavaType; + static Map appliedPaths; + static NodeList javaTypeNodes; + + + public static final int VALUE_NONE = 0; + public static final int VALUE_DESCRIPTION = 1; + public static final int VALUE_INDEXED_PROPS = 2; + + private static final String generateTypeXSD = "xsd"; + private static final String generateTypeYAML = "yaml"; + + private static final String root = "../aai-schema/src/main/resources"; + private static final String xsd_dir = root + "/aai_schema"; + private static final String yaml_dir = root + "/aai_swagger_yaml"; + + private static int annotationsStartVersion = 9; // minimum version to support annotations in xsd + private static int swaggerSupportStartsVersion = 7; // minimum version to support swagger documentation + + private static XPath xpath = XPathFactory.newInstance().newXPath(); + + + private enum LineageType { + PARENT, CHILD, UNRELATED; + } + private class EdgeDescription { + + private String ruleKey; + private LineageType type = LineageType.UNRELATED; + private String direction; + private String multiplicity; + private boolean hasDelTarget = false; + + public String getRuleKey() { + return ruleKey; + } + public String getMultiplicity() { + return multiplicity; + } + public String getDirection() { + return direction; + } + public void setRuleKey(String val) { + this.ruleKey=val; + } + public void setType(LineageType val) { + this.type=val; + } + public void setDirection(String val) { + this.direction = val; + } + public void setMultiplicity(String val) { + this.multiplicity=val; + } + public void setHasDelTarget(String val) { + hasDelTarget = Boolean.parseBoolean(val); + } + + public String getRelationshipDescription(String fromTo, String otherNodeName) { + + String result = ""; + + if ("FROM".equals(fromTo)) { + if ("OUT".equals(direction)) { + if (LineageType.PARENT == type) { + result = " (is composed of "+otherNodeName; + } + } + else { + if (LineageType.CHILD == type) { + result = " (comprises "+otherNodeName; + } + else if (LineageType.PARENT == type) { + result = " (comprises "+otherNodeName; + } + } + } else { + if ("OUT".equals(direction)) { + if (LineageType.PARENT == type) { + result = " (comprises "+otherNodeName; + } + } else { + if (LineageType.PARENT == type) { + result = " (is composed of "+otherNodeName; + } + } + } + +// if (type != null) { +// if (LineageType.PARENT.equals(type) && "FROM".equals(fromTo)) { +// if ("OUT".equals(direction)) { +// result = " (is composed of "+otherNodeName; +// } else { +// result = " (comprises "+otherNodeName; +// } +// } else { +// result = " (comprises " + otherNodeName; +// // if (!(multiplicity.startsWith("One"))) { +// // System.err.println("Surprised to find multiplicity "+multiplicity+" with comprises for "+ruleKey); +// // } +// } +// } + if ("TO".equals(fromTo)) { + if (result.length() == 0) result = result + " ("; + else result = result + ", "; + + result = result + mapMultiplicity(fromTo); + if (hasDelTarget) result = result + ", will delete target node"; + } + + if (result.length() > 0) result = result + ")"; + + return result; + } + + private String mapMultiplicity(String fromTo) { + String result = multiplicity; +// Below logic works if an IN switches multiplicity, which it doesn't today. +// if ("TO".equals(fromTo)) { +// if (direction.equals("OUT")) { +// result = multiplicity; +// } else { +// result = switchMultiplicity(multiplicity); +// } +// } else { +// if (direction.equals("OUT")) { +// result = multiplicity; +// } else { +// result = switchMultiplicity(multiplicity); +// } +// } + return result; + } + +// private String switchMultiplicity(String val) throws IllegalArgumentException +// { +// String result = null; +// switch (val) { +// case "Many2Many": +// case "One2One": +// result = val; +// break; +// case "Many2One": +// result = "One2Many"; +// break; +// case "One2Many": +// result = "Many2One"; +// break; +// default: +// throw new IllegalArgumentException("Multiplicity cannot be "+val); +// } +// System.out.println("Switched Multiplicity from "+val+" to "+result); +// return result; +// } + } + + private static boolean validVersion(String versionToGen) { + + if ("ALL".equalsIgnoreCase(versionToGen)) { + return true; + } + + for (Version v : Version.values()) { + if (v.name().equals(versionToGen)) { + return true; + } + } + + return false; + } + + private static boolean versionUsesAnnotations( String version) { + if (new Integer(version.substring(1)).intValue() >= annotationsStartVersion ) { + return true; + } + return false; + } + + private static boolean versionSupportsSwagger( String version) { + if (new Integer(version.substring(1)).intValue() >= swaggerSupportStartsVersion ) { + return true; + } + return false; + } + + public static void main(String[] args) throws IOException { + String versionToGen = System.getProperty("gen_version").toLowerCase(); + String fileTypeToGen = System.getProperty("gen_type").toLowerCase(); + if ( fileTypeToGen == null ) { + fileTypeToGen = generateTypeXSD; + } + + if ( !fileTypeToGen.equals( generateTypeXSD ) && !fileTypeToGen.equals( generateTypeYAML )) { + System.err.println("Invalid gen_type passed. " + fileTypeToGen); + System.exit(1); + } + + + if ( versionToGen == null ) { + System.err.println("Version is required, ie v or ALL."); + System.exit(1); + } + + responsesUrl = System.getProperty("yamlresponses_url"); + String responsesLabel = System.getProperty("yamlresponses_label"); + List versionsToGen = new ArrayList<>(); + + + if (!"ALL".equalsIgnoreCase(versionToGen) && !versionToGen.matches("v\\d+") && !validVersion(versionToGen)) { + System.err.println("Invalid version passed. " + versionToGen); + System.exit(1); + } + + if ("ALL".equalsIgnoreCase(versionToGen)) { + versionsToGen = Arrays.asList(Version.values()); + Collections.sort(versionsToGen); + Collections.reverse(versionsToGen); + } else { + versionsToGen.add(Version.valueOf(versionToGen)); + } + + if ( fileTypeToGen.equals(generateTypeYAML) ) { + if ( responsesUrl == null || responsesUrl.length() < 1 + || responsesLabel == null || responsesLabel.length() < 1 ) { + System.err.println("generating swagger yaml file requires yamlresponses_url and yamlresponses_label properties" ); + System.exit(1); + } + responsesUrl = "description: "+ responsesLabel+ "(" + responsesUrl + ").\n"; + } + String oxmPath = root + "/oxm/"; + + String outfileName; + File outfile; + String fileContent; + + for (Version v : versionsToGen) { + apiVersion = v.toString(); + System.out.println("Generating " + apiVersion + " " + fileTypeToGen); + File oxm_file = new File(oxmPath + "aai_oxm_" + apiVersion + ".xml"); + apiVersionFmt = "." + apiVersion + "."; + generatedJavaType = new HashMap(); + appliedPaths = new HashMap(); + if ( fileTypeToGen.equals(generateTypeXSD) ) { + useAnnotationsInXsd = versionUsesAnnotations(apiVersion); + outfileName = xsd_dir + "/aai_schema_" + apiVersion + "." + generateTypeXSD; + fileContent = processOxmFile(oxm_file, v); + } else if ( versionSupportsSwagger(apiVersion )) { + outfileName = yaml_dir + "/aai_swagger_" + apiVersion + "." + generateTypeYAML; + fileContent = generateSwaggerFromOxmFile( oxm_file); + } else { + continue; + } + outfile = new File(outfileName); + File parentDir = outfile.getParentFile(); + if(! parentDir.exists()) + parentDir.mkdirs(); + + try { + outfile.createNewFile(); + } catch (IOException e) { + System.out.println( "Exception creating output file " + outfileName); + e.printStackTrace(); + } + BufferedWriter bw = null; + try { + Charset charset = Charset.forName("UTF-8"); + Path path = Paths.get(outfileName); + bw = Files.newBufferedWriter(path, charset); + bw.write(fileContent); + } catch ( IOException e) { + System.out.println( "Exception writing output file " + outfileName); + e.printStackTrace(); + } finally { + if ( bw != null ) { + bw.close(); + } + } + System.out.println( "GeneratedXSD successful, saved in " + outfileName); + } + + } + + + public static String processJavaTypeElement( String javaTypeName, Element javaTypeElement) { + + String xmlRootElementName = null; + + NodeList parentNodes = javaTypeElement.getElementsByTagName("java-attributes"); + StringBuffer sb = new StringBuffer(); + if ( parentNodes.getLength() == 0 ) { + //System.out.println( "no java-attributes for java-type " + javaTypeName); + return ""; + + } + + NamedNodeMap attributes; + + NodeList valNodes = javaTypeElement.getElementsByTagName("xml-root-element"); + Element valElement = (Element) valNodes.item(0); + attributes = valElement.getAttributes(); + for ( int i = 0; i < attributes.getLength(); ++i ) { + Attr attr = (Attr) attributes.item(i); + String attrName = attr.getNodeName(); + + String attrValue = attr.getNodeValue(); + //System.out.println("Found xml-root-element attribute: " + attrName + " with value: " + attrValue); + if ( attrName.equals("name")) + xmlRootElementName = attrValue; + } + /* + if ( javaTypeName.equals("RelationshipList")) { + System.out.println( "Skipping " + javaTypeName); + generatedJavaType.put(javaTypeName, null); + return ""; + } + */ + + Element parentElement = (Element)parentNodes.item(0); + NodeList xmlElementNodes = parentElement.getElementsByTagName("xml-element"); + NodeList childNodes; + Element childElement; + String xmlElementWrapper; + + Element xmlElementElement; + String addType; + String elementName, elementType, elementIsKey, elementIsRequired, elementContainerType; + StringBuffer sb1 = new StringBuffer(); + if ( xmlElementNodes.getLength() > 0 ) { + sb1.append(" \n"); + sb1.append(" \n"); + NodeList properties = GenerateXsd.locateXmlProperties(javaTypeElement); + if (properties != null && useAnnotationsInXsd) { + //System.out.println("properties found for: " + xmlRootElementName); + sb1.append(" \r\n"); + insertAnnotation(properties, false, "class", sb1, " "); + + sb1.append(" \r\n"); + } /*else { + System.out.println("no properties found for: " + xmlRootElementName); + }*/ + sb1.append(" \n"); + for ( int i = 0; i < xmlElementNodes.getLength(); ++i ) { + + xmlElementElement = (Element)xmlElementNodes.item(i); + childNodes = xmlElementElement.getElementsByTagName("xml-element-wrapper"); + + xmlElementWrapper = null; + if ( childNodes.getLength() > 0 ) { + childElement = (Element)childNodes.item(0); + // get name + attributes = childElement.getAttributes(); + for ( int k = 0; k < attributes.getLength(); ++k ) { + Attr attr = (Attr) attributes.item(k); + String attrName = attr.getNodeName(); + String attrValue = attr.getNodeValue(); + if ( attrName.equals("name")) { + xmlElementWrapper = attrValue; + //System.out.println("found xml-element-wrapper " + xmlElementWrapper); + } + } + + } + attributes = xmlElementElement.getAttributes(); + addType = null; + + + elementName = elementType = elementIsKey = elementIsRequired = elementContainerType = null; + for ( int j = 0; j < attributes.getLength(); ++j ) { + Attr attr = (Attr) attributes.item(j); + String attrName = attr.getNodeName(); + + String attrValue = attr.getNodeValue(); + //System.out.println("For " + xmlRootElementName + " Found xml-element attribute: " + attrName + " with value: " + attrValue); + if ( attrName.equals("name")) { + elementName = attrValue; + } + if ( attrName.equals("type")) { + elementType = attrValue; + if ( attrValue.contains(apiVersionFmt) ) { + addType = attrValue.substring(attrValue.lastIndexOf('.')+1); + if ( !generatedJavaType.containsKey(addType) ) { + generatedJavaType.put(addType, attrValue); + sb.append(processJavaTypeElement( addType, getJavaTypeElement(addType) )); + } + } + + } + + if ( attrName.equals("xml-key")) { + elementIsKey = attrValue; + } + if ( attrName.equals("required")) { + elementIsRequired = attrValue; + } + if ( attrName.equals("container-type")) { + elementContainerType = attrValue; + } + } + + if ( xmlElementWrapper != null ) { + sb1.append(" \n"); + sb1.append(" \n"); + properties = GenerateXsd.locateXmlProperties(javaTypeElement); + if (properties != null && useAnnotationsInXsd) { + sb1.append(" \r\n"); + insertAnnotation(properties, false, "class", sb1, " "); + sb1.append(" \r\n"); + } /*else { + System.out.println("no properties found for: " + xmlElementWrapper); + }*/ + sb1.append(" \n"); + sb1.append(" "); + } + if ("Nodes".equals(addType)) { + //System.out.println ("Skipping nodes, temporary testing"); + continue; + } + if ( addType != null ) { + //sb1.append(" \n"); + if ( useAnnotationsInXsd ) { + sb1.append(" \r\n"); + insertAnnotation(properties, elementIsKey != null, "field", sb1, " "); + sb1.append(" \r\n"); + } + if (xmlElementWrapper== null) { + sb1.append(" \n"); + } + } else { + sb1.append("/>\n"); + } + if ( xmlElementWrapper != null ) { + sb1.append(" \n"); + sb1.append(" \n"); + sb1.append(" \n"); + } + } + /* + if ( xmlRootElementName.equals("notify") || + xmlRootElementName.equals("relationship") || + xmlRootElementName.equals("relationship-data") || + xmlRootElementName.equals("related-to-property") ) + + sb1.append(" \n"); + */ + sb1.append(" \n"); + sb1.append(" \n"); + sb1.append(" \n"); + } + /* + NodeList valNodes = javaTypeElement.getElementsByTagName("xml-root-element"); + Element valElement = (Element) valNodes.item(0); + attributes = valElement.getAttributes(); + for ( int i = 0; i < attributes.getLength(); ++i ) { + Attr attr = (Attr) attributes.item(i); + String attrName = attr.getNodeName(); + + String attrValue = attr.getNodeValue(); + System.out.println("Found xml-root-element attribute: " + attrName + " with value: " + attrValue); + if ( attrValue.equals("name")) + xmlRootElementName = attrValue; + } + */ + + if ( xmlElementNodes.getLength() < 1 ) { + sb.append(" \n"); + sb.append(" \n"); + sb.append(" \n"); + sb.append(" \n"); + sb.append(" \n"); + generatedJavaType.put(javaTypeName, null); + return sb.toString(); + } + + sb.append( sb1 ); + + return sb.toString(); + } + + private static void insertAnnotation(NodeList items, boolean isKey, String target, StringBuffer sb1, String indentation) { + if (items != null || isKey) { + List metadata = new ArrayList<>(); + + String name = ""; + String value = ""; + Element item = null; + if (isKey) { + metadata.add("isKey=true"); + } + if (items != null) { + for (int i = 0; i < items.getLength(); i++) { + item = (Element)items.item(i); + name = item.getAttribute("name"); + value = item.getAttribute("value"); + if (name.equals("abstract")) { + name = "isAbstract"; + } else if (name.equals("extends")) { + name = "extendsFrom"; + } + metadata.add(name + "=\"" + value.replaceAll("&", "&") + "\""); + //System.out.println("property name: " + name); + + } + } + sb1.append( + indentation + " \r\n" + + indentation + " @org.onap.aai.annotations.Metadata(" + Joiner.on(",").join(metadata) + ")\r\n" + + indentation + " \r\n"); + } + + } + + private static Element getJavaTypeElement( String javaTypeName ) + { + + String attrName, attrValue; + Attr attr; + Element javaTypeElement; + for ( int i = 0; i < javaTypeNodes.getLength(); ++ i ) { + javaTypeElement = (Element) javaTypeNodes.item(i); + NamedNodeMap attributes = javaTypeElement.getAttributes(); + for ( int j = 0; j < attributes.getLength(); ++j ) { + attr = (Attr) attributes.item(j); + attrName = attr.getNodeName(); + attrValue = attr.getNodeValue(); + if ( attrName.equals("name") && attrValue.equals(javaTypeName)) + return javaTypeElement; + } + } + System.out.println( "oxm file format error, missing java-type " + javaTypeName); + return (Element) null; + } + + private static Element getJavaTypeElementSwagger( String javaTypeName ) + { + + String attrName, attrValue; + Attr attr; + Element javaTypeElement; + for ( int i = 0; i < javaTypeNodes.getLength(); ++ i ) { + javaTypeElement = (Element) javaTypeNodes.item(i); + NamedNodeMap attributes = javaTypeElement.getAttributes(); + for ( int j = 0; j < attributes.getLength(); ++j ) { + attr = (Attr) attributes.item(j); + attrName = attr.getNodeName(); + attrValue = attr.getNodeValue(); + if ( attrName.equals("name") && attrValue.equals(javaTypeName)) + return javaTypeElement; + } + } + System.out.println( "oxm file format error, missing java-type " + javaTypeName); + return (Element) null; + } + private static String getXmlRootElementName( String javaTypeName ) + { + + String attrName, attrValue; + Attr attr; + Element javaTypeElement; + for ( int i = 0; i < javaTypeNodes.getLength(); ++ i ) { + javaTypeElement = (Element) javaTypeNodes.item(i); + NamedNodeMap attributes = javaTypeElement.getAttributes(); + for ( int j = 0; j < attributes.getLength(); ++j ) { + attr = (Attr) attributes.item(j); + attrName = attr.getNodeName(); + attrValue = attr.getNodeValue(); + if ( attrName.equals("name") && attrValue.equals(javaTypeName)) { + NodeList valNodes = javaTypeElement.getElementsByTagName("xml-root-element"); + Element valElement = (Element) valNodes.item(0); + attributes = valElement.getAttributes(); + for ( int k = 0; k < attributes.getLength(); ++k ) { + attr = (Attr) attributes.item(k); + attrName = attr.getNodeName(); + + attrValue = attr.getNodeValue(); + //System.out.println("Found xml-root-element attribute: " + attrName + " with value: " + attrValue); + if ( attrName.equals("name")) + return (attrValue); + } + } + } + } + System.out.println( "oxm file format error, missing java-type " + javaTypeName); + return null; + } + + + public static String processOxmFile( File oxmFile, Version v ) + { + StringBuilder sb = new StringBuilder(); + sb.append("\n"); + String namespace = "org.openecomp"; + if ( useAnnotationsInXsd ) { + sb.append("\n\n"); + } else { + sb.append("\n\n"); + } + + try { + + DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); + dbFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); + DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); + Document doc = dBuilder.parse(oxmFile); + + NodeList bindingsNodes = doc.getElementsByTagName("xml-bindings"); + Element bindingElement; + NodeList javaTypesNodes; + Element javaTypesElement; + + Element javaTypeElement; + + + if ( bindingsNodes == null || bindingsNodes.getLength() == 0 ) { + System.out.println( "missing in " + oxmFile ); + return null; + } + + bindingElement = (Element) bindingsNodes.item(0); + javaTypesNodes = bindingElement.getElementsByTagName("java-types"); + if ( javaTypesNodes.getLength() < 1 ) { + System.out.println( "missing in " + oxmFile ); + return null; + } + javaTypesElement = (Element) javaTypesNodes.item(0); + javaTypeNodes = javaTypesElement.getElementsByTagName("java-type"); + if ( javaTypeNodes.getLength() < 1 ) { + System.out.println( "missing in " + oxmFile ); + return null; + } + + String javaTypeName; + String attrName, attrValue; + Attr attr; + for ( int i = 0; i < javaTypeNodes.getLength(); ++ i ) { + javaTypeElement = (Element) javaTypeNodes.item(i); + NamedNodeMap attributes = javaTypeElement.getAttributes(); + javaTypeName = null; + for ( int j = 0; j < attributes.getLength(); ++j ) { + attr = (Attr) attributes.item(j); + attrName = attr.getNodeName(); + attrValue = attr.getNodeValue(); + if ( attrName.equals("name")) + javaTypeName = attrValue; + } + if ( javaTypeName == null ) { + System.out.println( " has no name attribute in " + oxmFile ); + return null; + } + if ("Nodes".equals(javaTypeName)) { + //System.out.println("skipping Nodes entry (temporary feature)"); + continue; + } + if ( !generatedJavaType.containsKey(javaTypeName) ) { + generatedJavaType.put(javaTypeName, null); + sb.append(processJavaTypeElement( javaTypeName, javaTypeElement )); + } + } + + } catch (Exception e) { + e.printStackTrace(); + return null; + } + sb.append("\n"); + return sb.toString(); + } + + private static boolean isStandardType( String elementType ) + { + switch ( elementType ) { + case "java.lang.String": + case "java.lang.Long": + case "java.lang.Integer": + case"java.lang.Boolean": + return true; + } + return false; + } + + private static Vector getIndexedProps( String attrValue ) + { + if ( attrValue == null ) + return null; + StringTokenizer st = new StringTokenizer( attrValue, ","); + if ( st.countTokens() == 0 ) + return null; + Vector result = new Vector(); + while ( st.hasMoreTokens()) { + result.add(st.nextToken()); + } + return result; + } + + /** + * Guaranteed to at least return non null but empty collection of edge descriptions + * @param nodeName name of the vertex whose edge relationships to return + * @return collection of node neighbors based on DbEdgeRules + **/ + private static Collection getEdgeRulesFromJson( String path, boolean skipMatch ) + { + + ArrayList result = new ArrayList<>(); + Iterator> edgeRulesIterator; + try { + + GenerateXsd x = new GenerateXsd(); + + List> inEdges = JsonPath.parse(jsonEdges).read(path); + + edgeRulesIterator = inEdges.iterator(); + Map edgeMap; + String fromNode; + String toNode; + String ruleKey; + String direction; + String multiplicity; + String isParent; + String hasDelTarget; + EdgeDescription edgeDes; + + while( edgeRulesIterator.hasNext() ){ + edgeMap = edgeRulesIterator.next(); + fromNode = (String)edgeMap.get("from"); + toNode = (String)edgeMap.get("to"); + if ( skipMatch ) { + if ( fromNode.equals(toNode)) { + continue; + } + } + edgeDes = x.new EdgeDescription(); + edgeDes.setRuleKey(fromNode + "|" + toNode); + direction = (String)edgeMap.get("direction"); + edgeDes.setDirection(direction); + multiplicity = (String)edgeMap.get("multiplicity"); + edgeDes.setMultiplicity(multiplicity); + isParent = (String)edgeMap.get(EdgeProperty.CONTAINS.toString()); + if ( "${direction}".equals(isParent)) { + edgeDes.setType(LineageType.PARENT); + } else { + edgeDes.setType(LineageType.UNRELATED); + } + hasDelTarget = (String)edgeMap.get(EdgeProperty.DELETE_OTHER_V.toString()); + edgeDes.setHasDelTarget(hasDelTarget); + result.add(edgeDes); + + } + } catch (Exception ex) { + ex.printStackTrace(); + } + return result; + + } + + /** + * Guaranteed to at least return non null but empty collection of edge descriptions + * @param nodeName name of the vertex whose edge relationships to return + * @return collection of node neighbors based on DbEdgeRules + **/ + private static Collection getEdgeRules( String nodeName ) + { + String fromRulesPath = "$['rules'][?(@['from']=='" + nodeName + "')]"; + String toRulesPath = "$['rules'][?(@['to']=='" + nodeName + "')]"; + Collection fromEdges = getEdgeRulesFromJson( fromRulesPath, false ); + Collection edges = getEdgeRulesFromJson( toRulesPath, true ); + edges.addAll(fromEdges); + return edges; + } + + public static String processJavaTypeElementSwagger( String javaTypeName, Element javaTypeElement, + StringBuffer pathSb, StringBuffer definitionsSb, String path, String tag, String opId, + String getItemName, StringBuffer pathParams, String queryParams, String validEdges) { + + String xmlRootElementName = null; + + //Map addJavaType = new HashMap(); + String useTag = null; + String useOpId = null; + + if ( tag != null ) { + switch ( tag ) { + case "Network": + case "ServiceDesignAndCreation": + case "Business": + case "LicenseManagement": + case "CloudInfrastructure": + case "ExternalSystem": + break; + default: + return null; + } + } + /* + if ( path == null ) + System.out.println( "processJavaTypeElementSwagger called with null path for javaTypeName " + javaTypeName); + */ + /* + if ( path == null || !(path.contains("cloud-infrastructure"))) + switch ( javaTypeName) { + case "Inventory": + useTag = null; + break; + + case "CloudInfrastructure": + case "Search": + case "Actions": + case "ServiceDesignAndCreation": + case "LicenseManagement": + case "Network": + if ( tag == null ) + useTag = javaTypeName; + + break; + default: + return null; + + } + */ + + if ( !javaTypeName.equals("Inventory") ) { + if ( javaTypeName.equals("AaiInternal")) + return null; + if ( opId == null ) + useOpId = javaTypeName; + else + useOpId = opId + javaTypeName; + if ( tag == null ) + useTag = javaTypeName; + } + + /* + if ( javaTypeName.equals("GenericVnf")) + System.out.println( "Processing " + javaTypeName); + else if ( javaTypeName.equals("Service")) + System.out.println( "Processing " + javaTypeName); + else if ( javaTypeName.equals("SitePair")) + System.out.println( "Processing " + javaTypeName); + */ + NodeList parentNodes = javaTypeElement.getElementsByTagName("java-attributes"); + + if ( parentNodes.getLength() == 0 ) { + //System.out.println( "no java-attributes for java-type " + javaTypeName); + return ""; + + } + + NamedNodeMap attributes; + + NodeList valNodes = javaTypeElement.getElementsByTagName("xml-root-element"); + Element valElement = (Element) valNodes.item(0); + attributes = valElement.getAttributes(); + for ( int i = 0; i < attributes.getLength(); ++i ) { + Attr attr = (Attr) attributes.item(i); + String attrName = attr.getNodeName(); + + String attrValue = attr.getNodeValue(); + //System.out.println("Found xml-root-element attribute: " + attrName + " with value: " + attrValue); + if ( attrName.equals("name")) + xmlRootElementName = attrValue; + } + /* + if ( xmlRootElementName.equals("oam-networks")) + System.out.println( "xmlRootElement oam-networks with getItemData [" + getItemName + "]"); + */ + //already processed + /* + if ( generatedJavaType.containsKey(xmlRootElementName) ) { + return null; + } + */ + NodeList childNodes; + Element childElement; + NodeList xmlPropNodes = javaTypeElement.getElementsByTagName("xml-properties"); + Element xmlPropElement; + String pathDescriptionProperty = null; + + + Vector indexedProps = null; + + /*System.out.println( "javaTypeName " + javaTypeName + " has xml-properties length " + xmlPropNodes.getLength()); + if ( path != null && path.equals("/network/generic-vnfs")) + System.out.println("path is " + "/network/generic-vnfs with getItemName " + getItemName); + */ + if ( xmlPropNodes.getLength() > 0 ) { + + for ( int i = 0; i < xmlPropNodes.getLength(); ++i ) { + xmlPropElement = (Element)xmlPropNodes.item(i); + if ( !xmlPropElement.getParentNode().isSameNode(javaTypeElement)) + continue; + childNodes = xmlPropElement.getElementsByTagName("xml-property"); + + if ( childNodes.getLength() > 0 ) { + for ( int j = 0; j < childNodes.getLength(); ++j ) { + childElement = (Element)childNodes.item(j); + // get name + int useValue = VALUE_NONE; + attributes = childElement.getAttributes(); + for ( int k = 0; k < attributes.getLength(); ++k ) { + Attr attr = (Attr) attributes.item(k); + String attrName = attr.getNodeName(); + String attrValue = attr.getNodeValue(); + if ( attrName == null || attrValue == null ) + continue; + if ( attrName.equals("name") && attrValue.equals("description")) { + useValue = VALUE_DESCRIPTION; + } + if ( useValue == VALUE_DESCRIPTION && attrName.equals("value")) { + pathDescriptionProperty = attrValue; + //break; + //System.out.println("found xml-element-wrapper " + xmlElementWrapper); + } + if ( attrValue.equals("indexedProps")) { + useValue = VALUE_INDEXED_PROPS; + } + if ( useValue == VALUE_INDEXED_PROPS && attrName.equals("value")) { + indexedProps = getIndexedProps( attrValue ); + } + } + } + } + } + } + //System.out.println("javaTypeName " + javaTypeName + " description " + pathDescriptionProperty); + + /* + if ( javaTypeName.equals("RelationshipList")) { + System.out.println( "Skipping " + javaTypeName); + generatedJavaType.put(javaTypeName, null); + return ""; + } + */ + + Element parentElement = (Element)parentNodes.item(0); + NodeList xmlElementNodes = parentElement.getElementsByTagName("xml-element"); + + + String attrDescription = null; + + Element xmlElementElement; + String addType = null; + String elementType = null, elementIsKey = null, elementIsRequired, elementContainerType = null; + String elementName = null; + StringBuffer sbParameters = new StringBuffer(); + + StringBuffer sbRequired = new StringBuffer(); + int requiredCnt = 0; + int propertyCnt = 0; + StringBuffer sbProperties = new StringBuffer(); + StringBuffer sbIndexedParams = new StringBuffer(); + + + StringTokenizer st; + if ( xmlRootElementName.equals("inventory")) + path = ""; + else if ( path == null ) + //path = "/aai/" + apiVersion; + path = "/" + xmlRootElementName; + else + path += "/" + xmlRootElementName; + st = new StringTokenizer(path, "/"); + /* + if ( path.equals("/business/customers/customer/{global-customer-id}/service-subscriptions/service-subscription")) + System.out.println("processing path /business/customers/customer/{global-customer-id}/service-subscriptions with tag " + tag); + */ + boolean genPath = false; + /* + if ( path != null && path.equals("/network/generic-vnfs/generic-vnf")) + System.out.println("path is " + "/network/generic-vnfs/generic-vnf"); + */ + if ( st.countTokens() > 1 && getItemName == null ) { + if ( appliedPaths.containsKey(path)) + return null; + appliedPaths.put(path, null); + genPath = true; + if ( path.contains("/relationship/") ) { // filter paths with relationship-list + genPath = false; + } + if ( path.endsWith("/relationship-list")) { + genPath = false; + } + + } + + Vector addTypeV = null; + if ( xmlElementNodes.getLength() > 0 ) { + + for ( int i = 0; i < xmlElementNodes.getLength(); ++i ) { + xmlElementElement = (Element)xmlElementNodes.item(i); + if ( !xmlElementElement.getParentNode().isSameNode(parentElement)) + continue; + /*childNodes = xmlElementElement.getElementsByTagName("xml-element-wrapper"); + if ( childNodes.getLength() > 0 ) { + childElement = (Element)childNodes.item(0); + // get name + attributes = childElement.getAttributes(); + for ( int k = 0; k < attributes.getLength(); ++k ) { + Attr attr = (Attr) attributes.item(k); + String attrName = attr.getNodeName(); + String attrValue = attr.getNodeValue(); + if ( attrName.equals("name")) { + xmlElementWrapper = attrValue; + //System.out.println("found xml-element-wrapper " + xmlElementWrapper); + } + } + + } + */ + valNodes = xmlElementElement.getElementsByTagName("xml-properties"); + attrDescription = null; + if ( valNodes.getLength() > 0 ) { + for ( int j = 0; j < valNodes.getLength(); ++j ) { + valElement = (Element)valNodes.item(j); + if ( !valElement.getParentNode().isSameNode(xmlElementElement)) + continue; + childNodes = valElement.getElementsByTagName("xml-property"); + if ( childNodes.getLength() > 0 ) { + childElement = (Element)childNodes.item(0); + // get name + attributes = childElement.getAttributes(); + attrDescription = null; + boolean useValue = false; + for ( int k = 0; k < attributes.getLength(); ++k ) { + Attr attr = (Attr) attributes.item(k); + String attrName = attr.getNodeName(); + String attrValue = attr.getNodeValue(); + if ( attrName.equals("name") && attrValue.equals("description")) { + useValue = true; + } + if ( useValue && attrName.equals("value")) { + attrDescription = attrValue; + //System.out.println("found xml-element-wrapper " + xmlElementWrapper); + } + } + + } + } + } + + attributes = xmlElementElement.getAttributes(); + addTypeV = null; // vector of 1 + addType = null; + + elementName = elementType = elementIsKey = elementIsRequired = elementContainerType = null; + for ( int j = 0; j < attributes.getLength(); ++j ) { + Attr attr = (Attr) attributes.item(j); + String attrName = attr.getNodeName(); + + String attrValue = attr.getNodeValue(); + //System.out.println("For " + xmlRootElementName + " Found xml-element attribute: " + attrName + " with value: " + attrValue); + if ( attrName.equals("name")) { + elementName = attrValue; + + } + if ( attrName.equals("type") && getItemName == null ) { + elementType = attrValue; + if ( attrValue.contains(apiVersionFmt) ) { + addType = attrValue.substring(attrValue.lastIndexOf('.')+1); + if ( addTypeV == null ) + addTypeV = new Vector(); + addTypeV.add(addType); + } + + } + if ( attrName.equals("xml-key")) { + elementIsKey = attrValue; + path += "/{" + elementName + "}"; + } + if ( attrName.equals("required")) { + elementIsRequired = attrValue; + } + if ( attrName.equals("container-type")) { + elementContainerType = attrValue; + } + } + if ( getItemName != null ) { + if ( getItemName.equals("array") ) { + if ( elementContainerType != null && elementContainerType.equals("java.util.ArrayList")) { + //System.out.println( " returning array " + elementName ); + return elementName; + } + + } else { // not an array check + if ( elementContainerType == null || !elementContainerType.equals("java.util.ArrayList")) { + //System.out.println( " returning object " + elementName ); + return elementName; + } + + } + //System.out.println( " returning null" ); + return null; + } + if ( elementIsRequired != null ) { + if ( requiredCnt == 0 ) + sbRequired.append(" required:\n"); + ++requiredCnt; + if ( addTypeV != null ) { + for ( int k = 0; k < addTypeV.size(); ++i ) { + sbRequired.append(" - " + getXmlRootElementName(addTypeV.elementAt(k)) + ":\n"); + } + } else + sbRequired.append(" - " + elementName + "\n"); + + } + + if ( elementIsKey != null ) { + sbParameters.append((" - name: " + elementName + "\n")); + sbParameters.append((" in: path\n")); + if ( attrDescription != null && attrDescription.length() > 0 ) + sbParameters.append((" description: " + attrDescription + "\n")); + sbParameters.append((" required: true\n")); + if ( elementType.equals("java.lang.String")) + sbParameters.append(" type: string\n"); + if ( elementType.equals("java.lang.Long")) { + sbParameters.append(" type: integer\n"); + sbParameters.append(" format: int64\n"); + } + if ( elementType.equals("java.lang.Integer")) { + sbParameters.append(" type: integer\n"); + sbParameters.append(" format: int32\n"); + } + if ( elementType.equals("java.lang.Boolean")) + sbParameters.append(" type: boolean\n"); + + + } else if ( indexedProps != null + && indexedProps.contains(elementName ) ) { + sbIndexedParams.append((" - name: " + elementName + "\n")); + sbIndexedParams.append((" in: query\n")); + if ( attrDescription != null && attrDescription.length() > 0 ) + sbIndexedParams.append((" description: " + attrDescription + "\n")); + sbIndexedParams.append((" required: false\n")); + if ( elementType.equals("java.lang.String")) + sbIndexedParams.append(" type: string\n"); + if ( elementType.equals("java.lang.Long")) { + sbIndexedParams.append(" type: integer\n"); + sbIndexedParams.append(" format: int64\n"); + } + if ( elementType.equals("java.lang.Integer")) { + sbIndexedParams.append(" type: integer\n"); + sbIndexedParams.append(" format: int32\n"); + } + if ( elementType.equals("java.lang.Boolean")) + sbIndexedParams.append(" type: boolean\n"); + } + + /* + if ( elementName != null && elementName.equals("inventory-item")) + System.out.println( "processing inventory-item elementName"); + */ + + if ( isStandardType(elementType)) { + sbProperties.append(" " + elementName + ":\n"); + ++propertyCnt; + sbProperties.append(" type: "); + + if ( elementType.equals("java.lang.String")) + sbProperties.append("string\n"); + else if ( elementType.equals("java.lang.Long")) { + sbProperties.append("integer\n"); + sbProperties.append(" format: int64\n"); + } + else if ( elementType.equals("java.lang.Integer")){ + sbProperties.append("integer\n"); + sbProperties.append(" format: int32\n"); + } + else if ( elementType.equals("java.lang.Boolean")) + sbProperties.append("boolean\n"); + if ( attrDescription != null && attrDescription.length() > 0 ) + sbProperties.append(" description: " + attrDescription + "\n"); + } + + //if ( addType != null && elementContainerType != null && elementContainerType.equals("java.util.ArrayList") ) { + + if ( addTypeV != null ) { + StringBuffer newPathParams = null; + if ( pathParams != null ) { + newPathParams = new StringBuffer(); + newPathParams.append(pathParams); + } + if ( sbParameters.toString().length() > 0 ) { + if ( newPathParams == null ) + newPathParams = new StringBuffer(); + newPathParams.append(sbParameters); + } + String newQueryParams = null; + if ( sbIndexedParams.toString().length() > 0 ) { + if ( queryParams == null ) + newQueryParams = sbIndexedParams.toString(); + else + newQueryParams = queryParams + sbIndexedParams.toString(); + } else { + newQueryParams = queryParams; + } + for ( int k = 0; k < addTypeV.size(); ++k ) { + addType = addTypeV.elementAt(k); + + if ( opId == null || !opId.contains(addType)) { + processJavaTypeElementSwagger( addType, getJavaTypeElementSwagger(addType), + pathSb, definitionsSb, path, tag == null ? useTag : tag, useOpId, null, + newPathParams, newQueryParams, validEdges); + } + // need item name of array + String itemName = processJavaTypeElementSwagger( addType, getJavaTypeElementSwagger(addType), + pathSb, definitionsSb, path, tag == null ? useTag : tag, useOpId, + "array", null, null, null ); + + if ( itemName != null ) { + if ( addType.equals("AaiInternal") ) { + //System.out.println( "addType AaiInternal, skip properties"); + + } else if ( getItemName == null) { + ++propertyCnt; + sbProperties.append(" " + getXmlRootElementName(addType) + ":\n"); + sbProperties.append(" type: array\n items:\n"); + sbProperties.append(" $ref: \"#/definitions/" + itemName + "\"\n"); + if ( attrDescription != null && attrDescription.length() > 0 ) + sbProperties.append(" description: " + attrDescription + "\n"); + } + } else { + /*itemName = processJavaTypeElementSwagger( addType, getJavaTypeElementSwagger(addType), + pathSb, definitionsSb, path, tag == null ? useTag : tag, useOpId, "other" ); + if ( itemName != null ) { + */ + if ( elementContainerType != null && elementContainerType.equals("java.util.ArrayList")) { + // need properties for getXmlRootElementName(addType) + newPathParams = null; + if ( pathParams != null ) { + newPathParams = new StringBuffer(); + newPathParams.append(pathParams); + } + if ( sbParameters.toString().length() > 0 ) { + if ( newPathParams == null ) + newPathParams = new StringBuffer(); + newPathParams.append(sbParameters); + } + newQueryParams = null; + if ( sbIndexedParams.toString().length() > 0 ) { + if ( queryParams == null ) + newQueryParams = sbIndexedParams.toString(); + else + newQueryParams = queryParams + sbIndexedParams.toString(); + } else { + newQueryParams = queryParams; + } + processJavaTypeElementSwagger( addType, getJavaTypeElementSwagger(addType), + pathSb, definitionsSb, path, tag == null ? useTag : tag, useOpId, + null, newPathParams, newQueryParams, validEdges ); + sbProperties.append(" " + getXmlRootElementName(addType) + ":\n"); + sbProperties.append(" type: array\n items: \n"); + sbProperties.append(" $ref: \"#/definitions/" + getXmlRootElementName(addType) + "\"\n"); + } else { + sbProperties.append(" " + getXmlRootElementName(addType) + ":\n"); + sbProperties.append(" type: object\n"); + sbProperties.append(" $ref: \"#/definitions/" + getXmlRootElementName(addType) + "\"\n"); + } + if ( attrDescription != null && attrDescription.length() > 0 ) + sbProperties.append(" description: " + attrDescription + "\n"); + ++propertyCnt; + /*} + else { + System.out.println(" unable to define swagger object for " + addType); + } + */ + } + //if ( getItemName == null) looking for missing properties + //generatedJavaType.put(addType, null); + } + } + } + } + if ( genPath ) { + /* + if ( useOpId.equals("CloudInfrastructureComplexesComplexCtagPools")) + System.out.println( "adding path CloudInfrastructureComplexesComplexCtagPools"); + */ + + if ( !path.endsWith("/relationship") ) { + pathSb.append(" " + path + ":\n" ); + pathSb.append(" get:\n"); + pathSb.append(" tags:\n"); + pathSb.append(" - " + tag + "\n"); + pathSb.append(" summary: returns " + xmlRootElementName + "\n"); + + pathSb.append(" description: returns " + xmlRootElementName + "\n"); + pathSb.append(" operationId: get" + useOpId + "\n"); + pathSb.append(" produces:\n"); + pathSb.append(" - application/json\n"); + pathSb.append(" - application/xml\n"); + + pathSb.append(" responses:\n"); + pathSb.append(" \"200\":\n"); + pathSb.append(" description: successful operation\n"); + pathSb.append(" schema:\n"); + pathSb.append(" $ref: \"#/definitions/" + xmlRootElementName + "\"\n"); + pathSb.append(" \"default\":\n"); + pathSb.append(" " + responsesUrl); + /* + pathSb.append(" \"200\":\n"); + pathSb.append(" description: successful operation\n"); + pathSb.append(" schema:\n"); + pathSb.append(" $ref: \"#/definitions/" + xmlRootElementName + "\"\n"); + pathSb.append(" \"404\":\n"); + pathSb.append(" description: resource was not found\n"); + pathSb.append(" \"400\":\n"); + pathSb.append(" description: bad request\n"); + */ + if ( path.indexOf('{') > 0 ) { + + if ( sbParameters.toString().length() > 0 ) { + if ( pathParams == null ) + pathParams = new StringBuffer(); + pathParams.append(sbParameters); + } + if ( pathParams != null) { + pathSb.append(" parameters:\n"); + pathSb.append(pathParams); + } else + System.out.println( "null pathParams for " + useOpId); + if ( sbIndexedParams.toString().length() > 0 ) { + if ( queryParams == null ) + queryParams = sbIndexedParams.toString(); + else + queryParams = queryParams + sbIndexedParams.toString(); + } + if ( queryParams != null ) { + if ( pathParams == null ) { + pathSb.append(" parameters:\n"); + } + pathSb.append(queryParams); + } + } + } + boolean skipPutDelete = false; // no put or delete for "all" + if ( !path.endsWith("/relationship") ) { + if ( !path.endsWith("}") ){ + skipPutDelete = true; + } + + } + if ( path.indexOf('{') > 0 && !opId.startsWith("Search") &&!skipPutDelete) { + // add PUT + if ( path.endsWith("/relationship") ) { + pathSb.append(" " + path + ":\n" ); + } + pathSb.append(" put:\n"); + pathSb.append(" tags:\n"); + pathSb.append(" - " + tag + "\n"); + + if ( path.endsWith("/relationship") ) { + pathSb.append(" summary: see node definition for valid relationships\n"); + } else { + pathSb.append(" summary: create or update an existing " + xmlRootElementName + "\n"); + pathSb.append(" description: create or update an existing " + xmlRootElementName + "\n"); + } + pathSb.append(" operationId: createOrUpdate" + useOpId + "\n"); + pathSb.append(" consumes:\n"); + pathSb.append(" - application/json\n"); + pathSb.append(" - application/xml\n"); + pathSb.append(" produces:\n"); + pathSb.append(" - application/json\n"); + pathSb.append(" - application/xml\n"); + pathSb.append(" responses:\n"); + pathSb.append(" \"default\":\n"); + pathSb.append(" " + responsesUrl); + /* + pathSb.append(" responses:\n"); + pathSb.append(" \"200\":\n"); + pathSb.append(" description: existing resource has been modified and there is a response buffer\n"); + pathSb.append(" \"201\":\n"); + pathSb.append(" description: new resource is created\n"); + pathSb.append(" \"202\":\n"); + pathSb.append(" description: action requested but may have taken other actions as well, which are returned in the response payload\n"); + pathSb.append(" \"204\":\n"); + pathSb.append(" description: existing resource has been modified and there is no response buffer\n"); + pathSb.append(" \"400\":\n"); + pathSb.append(" description: Bad Request will be returned if headers are missing\n"); + pathSb.append(" \"404\":\n"); + pathSb.append(" description: Not Found will be returned if an unknown URL is used\n"); + */ + pathSb.append(" parameters:\n"); + //pathSb.append(" - in: path\n"); + pathSb.append(pathParams); // for nesting + pathSb.append(" - name: body\n"); + pathSb.append(" in: body\n"); + pathSb.append(" description: " + xmlRootElementName + " object that needs to be created or updated\n"); + pathSb.append(" required: true\n"); + pathSb.append(" schema:\n"); + pathSb.append(" $ref: \"#/definitions/" + xmlRootElementName + "\"\n"); + /* + if ( queryParams != null ) { + pathSb.append(queryParams); + } + */ + // add DELETE + pathSb.append(" delete:\n"); + pathSb.append(" tags:\n"); + pathSb.append(" - " + tag + "\n"); + pathSb.append(" summary: delete an existing " + xmlRootElementName + "\n"); + + pathSb.append(" description: delete an existing " + xmlRootElementName + "\n"); + + pathSb.append(" operationId: delete" + useOpId + "\n"); + pathSb.append(" consumes:\n"); + pathSb.append(" - application/json\n"); + pathSb.append(" - application/xml\n"); + pathSb.append(" produces:\n"); + pathSb.append(" - application/json\n"); + pathSb.append(" - application/xml\n"); + pathSb.append(" responses:\n"); + pathSb.append(" \"default\":\n"); + pathSb.append(" " + responsesUrl); + /* + pathSb.append(" responses:\n"); + pathSb.append(" \"200\":\n"); + pathSb.append(" description: successful, the response includes an entity describing the status\n"); + pathSb.append(" \"204\":\n"); + pathSb.append(" description: successful, action has been enacted but the response does not include an entity\n"); + pathSb.append(" \"400\":\n"); + pathSb.append(" description: Bad Request will be returned if headers are missing\n"); + pathSb.append(" \"404\":\n"); + pathSb.append(" description: Not Found will be returned if an unknown URL is used\n"); + */ + pathSb.append(" parameters:\n"); + //pathSb.append(" - in: path\n"); + pathSb.append(pathParams); // for nesting + if ( !path.endsWith("/relationship") ) { + pathSb.append(" - name: resource-version\n"); + + pathSb.append(" in: query\n"); + pathSb.append(" description: resource-version for concurrency\n"); + pathSb.append(" required: true\n"); + pathSb.append(" type: string\n"); + } + /* + if ( queryParams != null ) { + pathSb.append(queryParams); + } + */ + } + + } + if ( generatedJavaType.containsKey(xmlRootElementName) ) { + return null; + } + + definitionsSb.append(" " + xmlRootElementName + ":\n"); + Collection edges = getEdgeRules(xmlRootElementName ); + if ( edges.size() > 0 ) { + StringBuffer sbEdge = new StringBuffer(); + sbEdge.append(" ###### Related Nodes\n"); + for (EdgeDescription ed : edges) { + if ( ed.getRuleKey().startsWith(xmlRootElementName)) { + sbEdge.append(" - TO ").append(ed.getRuleKey().substring(ed.getRuleKey().indexOf("|")+1)); + sbEdge.append(ed.getRelationshipDescription("TO", xmlRootElementName)); + sbEdge.append("\n"); + } + } + for (EdgeDescription ed : edges) { + if ( ed.getRuleKey().endsWith(xmlRootElementName)) { + sbEdge.append(" - FROM ").append(ed.getRuleKey().substring(0, ed.getRuleKey().indexOf("|"))); + sbEdge.append(ed.getRelationshipDescription("FROM", xmlRootElementName)); + sbEdge.append("\n"); + } + } + validEdges = sbEdge.toString(); + } + + // Handle description property. Might have a description OR valid edges OR both OR neither. + // Only put a description: tag if there is at least one. + if (pathDescriptionProperty != null || validEdges != null) { + definitionsSb.append(" description: |\n"); + + if ( pathDescriptionProperty != null ) + definitionsSb.append(" " + pathDescriptionProperty + "\n" ); + if (validEdges != null) + definitionsSb.append(validEdges); + } + + if ( requiredCnt > 0 ) + definitionsSb.append(sbRequired); + if ( propertyCnt > 0 ) { + definitionsSb.append(" properties:\n"); + definitionsSb.append(sbProperties); + } + generatedJavaType.put(xmlRootElementName, null); + return null; + } + + public static String generateSwaggerFromOxmFile( File oxmFile ) + { + + StringBuffer sb = new StringBuffer(); + sb.append("swagger: \"2.0\"\ninfo:\n description: |\n Copyright © 2017 AT&T Intellectual Property. All rights reserved.\n\n Licensed under the Creative Commons License, Attribution 4.0 Intl. (the "License"); you may not use this documentation except in compliance with the License.\n\n You may obtain a copy of the License at\n\n (https://creativecommons.org/licenses/by/4.0/)\n\n 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.\n\n ECOMP and OpenECOMP are trademarks and service marks of AT&T Intellectual Property.\n\n This document is best viewed with Firefox or Chrome. Nodes can be found by appending /#/definitions/node-type-to-find to the path to this document. Edge definitions can be found with the node definitions.\n version: \"" + apiVersion +"\"\n"); + sb.append(" title: Active and Available Inventory REST API\n"); + sb.append(" license:\n name: Apache 2.0\n url: http://www.apache.org/licenses/LICENSE-2.0.html\n"); + sb.append(" contact:\n name:\n url:\n email:\n"); + sb.append("host:\nbasePath: /aai/" + apiVersion + "\n"); + sb.append("schemes:\n - https\npaths:\n"); + /* + sb.append("responses:\n"); + sb.append(" \"200\":\n"); + sb.append(" description: successful operation\n"); + sb.append(" \"404\":\n"); + sb.append(" description: resource was not found\n"); + sb.append(" \"400\":\n"); + sb.append(" description: bad request\n"); + */ + try { + File initialFile = new File("src/main/resources/dbedgerules/DbEdgeRules_" + apiVersion + ".json"); + InputStream is = new FileInputStream(initialFile); + + Scanner scanner = new Scanner(is); + jsonEdges = scanner.useDelimiter("\\Z").next(); + scanner.close(); + is.close(); + + DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); + dbFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); + DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); + Document doc = dBuilder.parse(oxmFile); + + NodeList bindingsNodes = doc.getElementsByTagName("xml-bindings"); + Element bindingElement; + NodeList javaTypesNodes; + Element javaTypesElement; + + Element javaTypeElement; + + + if ( bindingsNodes == null || bindingsNodes.getLength() == 0 ) { + System.out.println( "missing in " + oxmFile ); + return null; + } + + bindingElement = (Element) bindingsNodes.item(0); + javaTypesNodes = bindingElement.getElementsByTagName("java-types"); + if ( javaTypesNodes.getLength() < 1 ) { + System.out.println( "missing in " + oxmFile ); + return null; + } + javaTypesElement = (Element) javaTypesNodes.item(0); + + javaTypeNodes = javaTypesElement.getElementsByTagName("java-type"); + if ( javaTypeNodes.getLength() < 1 ) { + System.out.println( "missing in " + oxmFile ); + return null; + } + + String javaTypeName; + String attrName, attrValue; + Attr attr; + StringBuffer pathSb = new StringBuffer(); + + StringBuffer definitionsSb = new StringBuffer("definitions:\n"); + + for ( int i = 0; i < javaTypeNodes.getLength(); ++ i ) { + javaTypeElement = (Element) javaTypeNodes.item(i); + NamedNodeMap attributes = javaTypeElement.getAttributes(); + javaTypeName = null; + for ( int j = 0; j < attributes.getLength(); ++j ) { + attr = (Attr) attributes.item(j); + attrName = attr.getNodeName(); + attrValue = attr.getNodeValue(); + if ( attrName.equals("name")) + javaTypeName = attrValue; + } + if ( javaTypeName == null ) { + System.out.println( " has no name attribute in " + oxmFile ); + return null; + } + if ( !generatedJavaType.containsKey(getXmlRootElementName(javaTypeName)) ) { + + //generatedJavaType.put(javaTypeName, null); + //if ( javaTypeName.equals("search")||javaTypeName.equals("actions")) + + processJavaTypeElementSwagger( javaTypeName, javaTypeElement, pathSb, + definitionsSb, null, null, null, null, null, null, null); + } + } + sb.append(pathSb); + //System.out.println( "definitions block\n" + definitionsSb.toString()); + sb.append(definitionsSb.toString()); + //sb.append(definitionsSb); + + } catch (Exception e) { + e.printStackTrace(); + return null; + } + //System.out.println("generated " + sb.toString()); + return sb.toString(); + } + + private static NodeList locateXmlProperties(Element element) { + XPathExpression expr; + NodeList result = null; + try { + expr = xpath.compile("xml-properties"); + if (expr != null) { + Object nodeset = expr.evaluate(element, XPathConstants.NODESET); + if (nodeset != null) { + NodeList nodes = (NodeList) nodeset; + if (nodes.getLength() > 0) { + Element xmlProperty = (Element)nodes.item(0); + result = xmlProperty.getElementsByTagName("xml-property"); + } + } + } + } catch (XPathExpressionException e) { + e.printStackTrace(); + } + return result; + + } +} 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 new file mode 100644 index 00000000..792f7d52 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/util/HbaseSaltPrefixer.java @@ -0,0 +1,61 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.util; + +/* + * logging to hbase encountered hotspotting issues, so per + * http://archive.cloudera.com/cdh5/cdh/5/hbase-0.98.6-cdh5.3.8/book/rowkey.design.html + * we decided to salt the rowkeys + * 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 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; + } +} 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 new file mode 100644 index 00000000..24ba1ba8 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/util/HttpsAuthClient.java @@ -0,0 +1,136 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.util; + +import java.io.FileInputStream; +import java.security.KeyManagementException; +import java.security.KeyStore; + +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.HttpsURLConnection; +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; + } + +} 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 new file mode 100644 index 00000000..12672b3b --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/util/KeyValueList.java @@ -0,0 +1,139 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.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 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" +}) +public class KeyValueList { + + @JsonProperty("key") + private String key; + @JsonProperty("value") + private String value; + @JsonIgnore + private Map additionalProperties = new HashMap(); + + /** + * + * @return + * The key + */ + @JsonProperty("key") + public String getKey() { + return key; + } + + /** + * + * @param key + * The key + */ + @JsonProperty("key") + public void setKey(String key) { + this.key = key; + } + + public KeyValueList withKey(String key) { + this.key = key; + return this; + } + + /** + * + * @return + * The value + */ + @JsonProperty("value") + public String getValue() { + return value; + } + + /** + * + * @param value + * The value + */ + @JsonProperty("value") + public void setValue(String value) { + this.value = value; + } + + public KeyValueList withValue(String value) { + this.value = value; + return this; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + @JsonAnySetter + public void setAdditionalProperty(String name, Object value) { + this.additionalProperties.put(name, value); + } + + public KeyValueList withAdditionalProperty(String name, Object value) { + this.additionalProperties.put(name, value); + return this; + } + + @Override + public int hashCode() { + return new HashCodeBuilder().append(key).append(value).append(additionalProperties).toHashCode(); + } + + @Override + public boolean equals(Object other) { + if (other == this) { + return true; + } + if ((other instanceof KeyValueList) == false) { + return false; + } + KeyValueList rhs = ((KeyValueList) other); + 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 new file mode 100644 index 00000000..9633fdaf --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/util/MapperUtil.java @@ -0,0 +1,116 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.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; + +public class MapperUtil { + + + /** + * Read as object of. + * + * @param the generic type + * @param clazz the clazz + * @param value the value + * @return the t + * @throws AAIException the AAI exception + */ + public static T readAsObjectOf(Class clazz, String value) throws AAIException { + com.fasterxml.jackson.databind.ObjectMapper MAPPER = new ObjectMapper(); + try { + return MAPPER.readValue(value, clazz); + } catch (Exception e) { + throw new AAIException("AAI_4007", e); + } + } + + /** + * Read with dashes as object of. + * + * @param the generic type + * @param clazz the clazz + * @param value the value + * @return the t + * @throws AAIException the AAI exception + */ + public static T readWithDashesAsObjectOf(Class clazz, String value) throws AAIException { + com.fasterxml.jackson.databind.ObjectMapper MAPPER = new ObjectMapper(); + try { + MAPPER.registerModule(new JaxbAnnotationModule()); + MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + MAPPER.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, false); + + return MAPPER.readValue(value, clazz); + } catch (Exception e) { + throw new AAIException("AAI_4007", e); + } + } + + /** + * Write as JSON string. + * + * @param obj the obj + * @return the string + * @throws AAIException the AAI exception + */ + public static String writeAsJSONString(Object obj) throws AAIException { + com.fasterxml.jackson.databind.ObjectMapper MAPPER = new ObjectMapper(); + try { + String s = MAPPER.writeValueAsString(obj); + return s; + //readValue(value, clazz); + } catch (Exception e) { + throw new AAIException("AAI_4008", e); + } + } + + /** + * Write as JSON string with dashes. + * + * @param obj the obj + * @return the string + * @throws AAIException the AAI exception + */ + public static String writeAsJSONStringWithDashes(Object obj) throws AAIException { + com.fasterxml.jackson.databind.ObjectMapper MAPPER = new ObjectMapper(); + try { + 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.registerModule(new JaxbAnnotationModule()); + String s = MAPPER.writeValueAsString(obj); + return s; + } catch (Exception e) { + throw new AAIException("AAI_4008", e); + } + } +} 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 new file mode 100644 index 00000000..5a84d9d0 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/util/PojoUtils.java @@ -0,0 +1,83 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.util; + +import java.io.IOException; + +import org.apache.commons.io.output.ByteArrayOutputStream; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.core.JsonGenerationException; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule; + +public class PojoUtils { + /** + * Gets the json from object. + * + * @param 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 String getJsonFromObject(T clazz) throws JsonGenerationException, JsonMappingException, IOException { + return getJsonFromObject(clazz, false, true); + } + + /** + * Gets the json from object. + * + * @param 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 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(); + } +} 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 new file mode 100644 index 00000000..605aa2b9 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/util/Request.java @@ -0,0 +1,161 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.util; + +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; + +import javax.ws.rs.core.UriBuilder; + +import org.onap.aai.exceptions.AAIException; + +public class Request { + + public static final String V2 = "v2"; + public static final String V3 = "v3"; + public static final String V4 = "v4"; + public static final String V5 = "v5"; + public final String fromAppId; + public final String transactionId; + public final String path; + public final RestObject restObj; + public final boolean oldServer; + public final String apiVersion; + + + /** + * Instantiates a new request. + * + * @param builder the builder + */ + public Request(RequestBuilder 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 { + private String fromAppId; + private String transactionId; + private String path; + private RestObject restObj; + private boolean oldServer; + private String apiVersion = Request.V4; + + + /** + * Sets the from app id. + * + * @param fromAppId the from app id + * @return the request builder + */ + public RequestBuilder setFromAppId(String fromAppId) { + this.fromAppId = fromAppId; + return this; + } + + /** + * Sets the transaction id. + * + * @param transactionId the transaction id + * @return the request builder + */ + public RequestBuilder setTransactionId(String transactionId) { + this.transactionId = transactionId; + return this; + + } + + /** + * Sets the path. + * + * @param path the path + * @return the request builder + */ + public RequestBuilder setPath(String path) { + + this.path = path; + return this; + + } + + /** + * Sets the restcore obj. + * + * @param restObj the restcore obj + * @return the request builder + */ + public RequestBuilder setRestObj(RestObject restObj) { + this.restObj = restObj; + return this; + + } + + /** + * Sets the old server. + * + * @param oldServer the old server + * @return the request builder + */ + public RequestBuilder setOldServer(boolean oldServer) { + this.oldServer = oldServer; + return this; + + } + + /** + * Sets the api version. + * + * @param apiVersion the api version + * @return the request builder + */ + public RequestBuilder setApiVersion(String apiVersion) { + this.apiVersion = apiVersion; + return this; + } + + /** + * Builds the. + * + * @return the request + */ + public Request build() { + return new Request(this); + } + + } + +} 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 new file mode 100644 index 00000000..0b267d43 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/util/RestObject.java @@ -0,0 +1,47 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.util; + +public class RestObject { + + /** + * Generic version of the RestObject class. + * @param the type of the value being called for the Rest object interface + */ + // T stands for "Type" + private T t; + + /** + * Sets the. + * + * @param t the t + */ + public void set(T t) { this.t = t; } + + /** + * Gets the. + * + * @return the 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 new file mode 100644 index 00000000..0b97c66e --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/util/RestURLEncoder.java @@ -0,0 +1,42 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.util; + +import java.io.UnsupportedEncodingException; +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"); + } +} + 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 new file mode 100644 index 00000000..96dbfeb4 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/util/StoreNotificationEvent.java @@ -0,0 +1,337 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.util; + +import java.io.StringWriter; +import java.util.Iterator; +import java.util.UUID; + +import javax.xml.bind.Marshaller; + +import org.eclipse.persistence.dynamic.DynamicEntity; +import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext; +import org.json.JSONException; +import org.json.JSONObject; +import org.onap.aai.dmaap.AAIDmaapEventJMSProducer; +import org.onap.aai.domain.notificationEvent.NotificationEvent; +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.Introspector; +import org.onap.aai.introspection.Loader; +import org.onap.aai.introspection.exceptions.AAIUnknownObjectException; + +public class StoreNotificationEvent { + + private AAIDmaapEventJMSProducer messageProducer; + private String fromAppId = ""; + private String transId = ""; + private final String transactionId; + private final String sourceOfTruth; + /** + * Instantiates a new store notification event. + */ + public StoreNotificationEvent(String transactionId, String sourceOfTruth) { + this.messageProducer = new AAIDmaapEventJMSProducer(); + this.transactionId = transactionId; + this.sourceOfTruth = sourceOfTruth; + } + + /** + * Store event. + * + * @param eh + * the eh + * @param obj + * the obj + * @throws AAIException + * the AAI exception + */ + public void 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); + } 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 void 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", AAIConstants.UEB_PUB_PARTITION_AAI); + } + + notificationEvent.setValue("event-header", eventHeader.getUnderlyingObject()); + notificationEvent.setValue("entity", obj.getUnderlyingObject()); + + String entityJson = notificationEvent.marshal(false); + sendToDmaapJmsQueue(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 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/util/UniquePropertyCheck.java b/aai-core/src/main/java/org/onap/aai/util/UniquePropertyCheck.java new file mode 100644 index 00000000..ae2cdaae --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/util/UniquePropertyCheck.java @@ -0,0 +1,268 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.util; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Properties; +import java.util.UUID; + +import org.apache.tinkerpop.gremlin.structure.Direction; +import org.apache.tinkerpop.gremlin.structure.Edge; +import org.apache.tinkerpop.gremlin.structure.Graph; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.apache.tinkerpop.gremlin.structure.VertexProperty; +import org.onap.aai.exceptions.AAIException; +import org.slf4j.MDC; + +import com.att.eelf.configuration.Configuration; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.thinkaurelius.titan.core.TitanFactory; +import com.thinkaurelius.titan.core.TitanGraph; + + + +public class UniquePropertyCheck { + + + private static final String FROMAPPID = "AAI-UTILS"; + private static final String TRANSID = UUID.randomUUID().toString(); + private static final String COMPONENT = "UniquePropertyCheck"; + + /** + * The main method. + * + * @param args the arguments + */ + public static void main(String[] args) { + + + Properties props = System.getProperties(); + props.setProperty(Configuration.PROPERTY_LOGGING_FILE_NAME, "uniquePropertyCheck-logback.xml"); + props.setProperty(Configuration.PROPERTY_LOGGING_FILE_PATH, AAIConstants.AAI_HOME_ETC_APP_PROPERTIES); + EELFLogger logger = EELFManager.getInstance().getLogger(UniquePropertyCheck.class.getSimpleName()); + MDC.put("logFilenameAppender", UniquePropertyCheck.class.getSimpleName()); + + if( args == null || args.length != 1 ){ + String msg = "usage: UniquePropertyCheck propertyName \n"; + System.out.println(msg); + logAndPrint(logger, msg ); + System.exit(1); + } + String propertyName = args[0]; + Graph graph = null; + + try { + AAIConfig.init(); + System.out.println(" ---- NOTE --- about to open graph (takes a little while)--------\n"); + TitanGraph tGraph = TitanFactory.open(AAIConstants.REALTIME_DB_CONFIG); + + if( tGraph == null ) { + logAndPrint(logger, " Error: Could not get TitanGraph "); + System.exit(1); + } + + graph = tGraph.newTransaction(); + if( graph == null ){ + logAndPrint(logger, "could not get graph object in UniquePropertyCheck() \n"); + System.exit(0); + } + } + catch (AAIException e1) { + String msg = "Threw Exception: [" + e1.toString() + "]"; + logAndPrint(logger, msg); + System.exit(0); + } + catch (Exception e2) { + String msg = "Threw Exception: [" + e2.toString() + "]"; + logAndPrint(logger, msg); + System.exit(0); + } + + runTheCheckForUniqueness( TRANSID, FROMAPPID, graph, propertyName, logger ); + System.exit(0); + + }// End main() + + + /** + * Run the check for uniqueness. + * + * @param transId the trans id + * @param fromAppId the from app id + * @param graph the graph + * @param propertyName the property name + * @param logger the logger + * @return the boolean + */ + public static Boolean runTheCheckForUniqueness( String transId, String fromAppId, Graph graph, + String propertyName, EELFLogger logger ){ + + // Note - property can be found in more than one nodetype + // our uniqueness constraints are always across the entire db - so this + // tool looks across all nodeTypes that the property is found in. + Boolean foundDupesFlag = false; + + HashMap valuesAndVidHash = new HashMap (); + HashMap dupeHash = new HashMap (); + + int propCount = 0; + int dupeCount = 0; + Iterator vertItor = graph.traversal().V().has(propertyName); + while( vertItor.hasNext() ){ + propCount++; + Vertex v = vertItor.next(); + String thisVid = v.id().toString(); + Object val = (v.property(propertyName)).orElse(null); + if( valuesAndVidHash.containsKey(val) ){ + // We've seen this one before- track it in our dupe hash + dupeCount++; + if( dupeHash.containsKey(val) ){ + // This is not the first one being added to the dupe hash for this value + String updatedDupeList = dupeHash.get(val) + "|" + thisVid; + dupeHash.put(val.toString(), updatedDupeList); + } + else { + // This is the first time we see this value repeating + String firstTwoVids = valuesAndVidHash.get(val) + "|" + thisVid; + dupeHash.put(val.toString(), firstTwoVids); + } + } + else { + valuesAndVidHash.put(val.toString(), thisVid); + } + } + + + String info = "\n Found this property [" + propertyName + "] " + propCount + " times in our db."; + logAndPrint(logger, info); + info = " Found " + dupeCount + " cases of duplicate values for this property.\n\n"; + logAndPrint(logger, info); + + try { + if( ! dupeHash.isEmpty() ){ + Iterator dupeItr = dupeHash.entrySet().iterator(); + while( dupeItr.hasNext() ){ + Map.Entry pair = (Map.Entry) dupeItr.next(); + String dupeValue = pair.getKey().toString();; + String vidsStr = pair.getValue().toString(); + String[] vidArr = vidsStr.split("\\|"); + logAndPrint(logger, "\n\n -------------- Found " + vidArr.length + + " nodes with " + propertyName + " of this value: [" + dupeValue + "]. Node details: "); + + for( int i = 0; i < vidArr.length; i++ ){ + String vidString = vidArr[i]; + Long idLong = Long.valueOf(vidString); + Vertex tvx = graph.traversal().V(idLong).next(); + showPropertiesAndEdges( TRANSID, FROMAPPID, tvx, logger ); + } + } + } + } + catch( Exception e2 ){ + logAndPrint(logger, "Threw Exception: [" + e2.toString() + "]"); + } + finally { + if( graph != null ){ + graph.tx().rollback(); + } + } + + return foundDupesFlag; + + }// end of runTheCheckForUniqueness() + + + /** + * Show properties and edges. + * + * @param transId the trans id + * @param fromAppId the from app id + * @param tVert the t vert + * @param logger the logger + */ + private static void showPropertiesAndEdges( String transId, String fromAppId, Vertex tVert, + EELFLogger logger ){ + + if( tVert == null ){ + logAndPrint(logger, "Null node passed to showPropertiesAndEdges."); + } + else { + String nodeType = ""; + Object ob = tVert.property("aai-node-type").orElse(null); + if( ob == null ){ + nodeType = "null"; + } + else{ + nodeType = ob.toString(); + } + + logAndPrint(logger, " AAINodeType/VtxID for this Node = [" + nodeType + "/" + tVert.id() + "]"); + logAndPrint(logger, " Property Detail: "); + Iterator> pI = tVert.properties(); + while( pI.hasNext() ){ + VertexProperty tp = pI.next(); + Object val = tp.value(); + logAndPrint(logger, "Prop: [" + tp.key() + "], val = [" + val + "] "); + } + + Iterator eI = tVert.edges(Direction.BOTH); + if( ! eI.hasNext() ){ + logAndPrint(logger, "No edges were found for this vertex. "); + } + while( eI.hasNext() ){ + Edge ed = eI.next(); + String lab = ed.label(); + Vertex vtx; + if (tVert.equals(ed.inVertex())) { + vtx = ed.outVertex(); + } else { + vtx = ed.inVertex(); + } + if( vtx == null ){ + logAndPrint(logger, " >>> COULD NOT FIND VERTEX on the other side of this edge edgeId = " + ed.id() + " <<< "); + } + else { + String nType = vtx.property("aai-node-type").orElse(null); + String vid = vtx.id().toString(); + logAndPrint(logger, "Found an edge (" + lab + ") from this vertex to a [" + nType + "] node with VtxId = " + vid); + } + } + } + } // End of showPropertiesAndEdges() + + + /** + * Log and print. + * + * @param logger the logger + * @param msg the msg + */ + protected static void logAndPrint(EELFLogger logger, String msg) { + System.out.println(msg); + logger.info(msg); + } + +} + + diff --git a/aai-core/src/main/java/org/onap/aai/util/swagger/Api.java b/aai-core/src/main/java/org/onap/aai/util/swagger/Api.java new file mode 100644 index 00000000..e1e16c25 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/util/swagger/Api.java @@ -0,0 +1,311 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.util.swagger; + +import java.util.List; +import java.util.Map; + +public class Api { + + private String path; + + private List httpMethods; + + private String tag; + + public List getHttpMethods() { + return httpMethods; + } + + public void setHttpMethods(List httpMethods) { + this.httpMethods = httpMethods; + } + + public String getTag(){ + + if(this.tag != null){ + return this.tag; + } + + if(this.httpMethods != null){ + if(this.httpMethods.size() != 0){ + if(this.httpMethods.get(0).getTags() != null){ + if(this.httpMethods.get(0).getTags().size() != 0){ + this.tag = this.httpMethods.get(0).getTags().get(0); + } + } + } + } + + if(this.tag == null){ + this.tag = ""; + } + + return this.tag; + } + + @Override + public String toString() { + return "Api{" + + "path='" + path + '\'' + + ", httpMethods=" + httpMethods + + '}'; + } + + public void setPath(String path) { + this.path = path; + } + + public String getPath() { + return this.path; + } + + public String getOperation(){ + + if(this.path != null){ + return this.path.replaceAll("[^a-zA-Z0-9\\-]", "-") + "-"; + } + + return ""; + } + + public static class HttpVerb { + + private List tags; + + private String type; + + private String summary; + + private String operationId; + + private List consumes; + + private boolean consumerEnabled; + + private List produces; + + private List responses; + + private List> parameters; + + private Map bodyParameters; + + private boolean bodyParametersEnabled; + + private boolean parametersEnabled; + + private String schemaLink; + + private String schemaType; + + private boolean hasReturnSchema; + + private String returnSchemaLink; + + private String returnSchemaObject; + + public void setConsumerEnabled(boolean consumerEnabled){ + this.consumerEnabled = consumerEnabled; + } + + public boolean isConsumerEnabled() { + return consumerEnabled; + } + + + public List getTags() { + return tags; + } + + public void setTags(List tags) { + this.tags = tags; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getSummary() { + return summary; + } + + public void setSummary(String summary) { + this.summary = summary; + } + + public String getOperationId() { + return operationId; + } + + public void setOperationId(String operationId) { + this.operationId = operationId; + } + + public List getConsumes() { + return consumes; + } + + public void setConsumes(List consumes) { + this.consumes = consumes; + } + + public List getProduces() { + return produces; + } + + public void setProduces(List produces) { + this.produces = produces; + } + + public List getResponses() { + return responses; + } + + public void setResponses(List responses) { + this.responses = responses; + } + + public List> getParameters() { + return parameters; + } + + public void setParameters(List> parameters) { + this.parameters = parameters; + } + + @Override + public String toString() { + return "HttpVerb{" + + "tags=" + tags + + ", type='" + type + '\'' + + ", summary='" + summary + '\'' + + ", operationId='" + operationId + '\'' + + ", consumes=" + consumes + + ", produces=" + produces + + ", responses=" + responses + + ", parameters=" + parameters + + '}'; + } + + public void setParametersEnabled(boolean b) { + this.parametersEnabled = b; + } + + public boolean isParametersEnabled() { + return parametersEnabled; + } + + public boolean isBodyParametersEnabled() { + return bodyParametersEnabled; + } + + public void setBodyParametersEnabled(boolean bodyParametersEnabled) { + this.bodyParametersEnabled = bodyParametersEnabled; + } + + public Map getBodyParameters() { + return bodyParameters; + } + + public void setBodyParameters(Map bodyParameters) { + this.bodyParameters = bodyParameters; + } + + public String getSchemaLink() { + return schemaLink; + } + + public void setSchemaLink(String schemaLink) { + this.schemaLink = schemaLink; + } + + public String getSchemaType() { + return schemaType; + } + + public void setSchemaType(String schemaType) { + this.schemaType = schemaType; + } + + public boolean isHasReturnSchema() { + return hasReturnSchema; + } + + public void setHasReturnSchema(boolean hasReturnSchema) { + this.hasReturnSchema = hasReturnSchema; + } + + public String getReturnSchemaLink() { + return returnSchemaLink; + } + + public void setReturnSchemaLink(String returnSchemaLink) { + this.returnSchemaLink = returnSchemaLink; + } + + public String getReturnSchemaObject() { + return returnSchemaObject; + } + + public void setReturnSchemaObject(String returnSchemaObject) { + this.returnSchemaObject = returnSchemaObject; + } + + public static class Response { + + private String responseCode; + + private String description; + + public String getResponseCode() { + return responseCode; + } + + public void setResponseCode(String responseCode) { + this.responseCode = responseCode; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + @Override + public String toString() { + return "Response{" + + "responseCode='" + responseCode + '\'' + + ", description='" + description + '\'' + + '}'; + } + } + + } + +} diff --git a/aai-core/src/main/java/org/onap/aai/util/swagger/Definition.java b/aai-core/src/main/java/org/onap/aai/util/swagger/Definition.java new file mode 100644 index 00000000..9c8f0784 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/util/swagger/Definition.java @@ -0,0 +1,200 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.util.swagger; + +import java.util.List; + +public class Definition { + + private String definitionName; + + private String definitionDescription; + + private List propertyList; + + private List schemaPropertyList; + + private List regularPropertyList; + + private boolean hasDescription; + + public String getDefinitionName() { + return definitionName; + } + + public void setDefinitionName(String definitionName) { + this.definitionName = definitionName; + } + + public List getPropertyList() { + return propertyList; + } + + public void setPropertyList(List propertyList) { + this.propertyList = propertyList; + } + + public String getDefinitionDescription() { + return definitionDescription; + } + + public void setDefinitionDescription(String definitionDescription) { + this.definitionDescription = definitionDescription; + } + + @Override + public String toString() { + return "Definition{" + + "definitionName='" + definitionName + '\'' + + ", definitionDescription='" + definitionDescription + '\'' + + ", propertyList=" + propertyList + + '}'; + } + + public boolean isHasDescription() { + return hasDescription; + } + + public void setHasDescription(boolean hasDescription) { + this.hasDescription = hasDescription; + } + + public List getSchemaPropertyList() { + return schemaPropertyList; + } + + public void setSchemaPropertyList(List schemaPropertyList) { + this.schemaPropertyList = schemaPropertyList; + } + + public List getRegularPropertyList() { + return regularPropertyList; + } + + public void setRegularPropertyList(List regularPropertyList) { + this.regularPropertyList = regularPropertyList; + } + + public static class Property { + + private String propertyName; + + private String propertyDescription; + + private boolean hasPropertyDescription; + + private String propertyType; + + private boolean hasType; + + private String propertyReference; + + private String propertyReferenceObjectName; + + private boolean isRequired; + + private boolean hasPropertyReference; + + public Property(){} + + public String getPropertyName() { + return propertyName; + } + + public void setPropertyName(String propertyName) { + this.propertyName = propertyName; + } + + public String getPropertyType() { + return propertyType; + } + + public void setPropertyType(String propertyType) { + this.propertyType = propertyType; + } + + public String getPropertyReference() { + return propertyReference; + } + + public void setPropertyReference(String propertyReference) { + this.propertyReference = propertyReference; + } + + @Override + public String toString() { + return "Property{" + + "propertyName='" + propertyName + '\'' + + ", propertyType='" + propertyType + '\'' + + ", propertyReference='" + propertyReference + '\'' + + '}'; + } + + public boolean isHasType() { + return hasType; + } + + public void setHasType(boolean hasType) { + this.hasType = hasType; + } + + public boolean isRequired() { + return isRequired; + } + + public void setRequired(boolean required) { + isRequired = required; + } + + public boolean isHasPropertyReference() { + return hasPropertyReference; + } + + public void setHasPropertyReference(boolean hasPropertyReference) { + this.hasPropertyReference = hasPropertyReference; + } + + public String getPropertyReferenceObjectName() { + return propertyReferenceObjectName; + } + + public void setPropertyReferenceObjectName(String propertyReferenceObjectName) { + this.propertyReferenceObjectName = propertyReferenceObjectName; + } + + public String getPropertyDescription() { + return propertyDescription; + } + + public void setPropertyDescription(String propertyDescription) { + this.propertyDescription = propertyDescription; + } + + public boolean isHasPropertyDescription() { + return hasPropertyDescription; + } + + public void setHasPropertyDescription(boolean hasPropertyDescription) { + this.hasPropertyDescription = hasPropertyDescription; + } + } +} diff --git a/aai-core/src/main/java/org/onap/aai/util/swagger/GenerateSwagger.java b/aai-core/src/main/java/org/onap/aai/util/swagger/GenerateSwagger.java new file mode 100644 index 00000000..a85b548e --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/util/swagger/GenerateSwagger.java @@ -0,0 +1,433 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.util.swagger; + +import com.fasterxml.jackson.dataformat.yaml.snakeyaml.Yaml; +import com.fasterxml.jackson.dataformat.yaml.snakeyaml.constructor.SafeConstructor; +import freemarker.template.Configuration; +import freemarker.template.Template; +import freemarker.template.TemplateException; + +import java.io.*; +import java.util.*; +import java.util.stream.Collectors; + +public class GenerateSwagger { + + public static final String LINE_SEPARATOR = System.getProperty("line.separator"); + public static final String DEFAULT_WIKI = ""; + + public static final String DEFAULT_SCHEMA_DIR = "../aai-schema"; + public static final String CURRENT_VERSION = "v11"; + + public static void main(String[] args) throws IOException, TemplateException { + + String schemaDir = System.getProperty("aai.schema.dir"); + String versionToGenerate = System.getProperty("aai.generate.version"); + String wikiLink = System.getProperty("aai.wiki.link"); + + if(schemaDir == null){ + System.out.println("Warning: Schema directory is not set so using default schema dir: " + DEFAULT_SCHEMA_DIR); + schemaDir = DEFAULT_SCHEMA_DIR; + } + + if(versionToGenerate == null){ + System.out.println("Warning: Version to generate is not set so using default version: " + CURRENT_VERSION); + versionToGenerate = CURRENT_VERSION; + } + + if(wikiLink == null){ + System.out.println("Warning: aai.wiki.link property is not set so using default"); + wikiLink = DEFAULT_WIKI; + } + + String yamlFile = schemaDir + "/src/main/resources/aai_swagger_yaml/aai_swagger_" + versionToGenerate + ".yaml"; + File swaggerYamlFile = new File(yamlFile); + + if(!swaggerYamlFile.exists()){ + System.err.println("Unable to find the swagger yaml file: " + swaggerYamlFile); + System.exit(1); + } + + Yaml yaml = new Yaml(new SafeConstructor()); + Map swaggerMap = null; + + try (BufferedReader reader = new BufferedReader(new FileReader(swaggerYamlFile))){ + swaggerMap = (Map) yaml.load(reader); + } catch(IOException ex){ + ex.printStackTrace(); + } + + if(null == swaggerMap) { + throw new IOException(); + } + + Map map = (Map) swaggerMap.get("paths"); + Map schemaDefinitionmap = (Map) swaggerMap.get("definitions"); + Map infoMap = (Map) swaggerMap.get("info"); + Map> tagMap = new LinkedHashMap<>(); + + List apis = convertToApi(map); + apis.forEach((api) -> { + if(!tagMap.containsKey(api.getTag())){ + List newApis = new ArrayList<>(); + newApis.add(api); + tagMap.put(api.getTag(), newApis); + } else { + tagMap.get(api.getTag()).add(api); + } + }); + + Map> sortedTagMap = new TreeMap<>(tagMap); + sortedTagMap.forEach((key, value) -> { + value.sort(Comparator.comparing(Api::getPath)); + }); + + Map resultMap = new HashMap<>(); + + List definitionList = convertToDefinition(schemaDefinitionmap); + + definitionList = definitionList + .stream().sorted(Comparator.comparing(Definition::getDefinitionName)).collect(Collectors.toList()); + + resultMap.put("aaiApis", tagMap); + resultMap.put("sortedAaiApis", sortedTagMap); + resultMap.put("wikiLink", wikiLink); + resultMap.put("definitions", definitionList); + if (infoMap.containsKey("description")) { + String infoDescription = infoMap.get("description").toString(); + + infoDescription = Arrays.stream(infoDescription.split("\n")) + .map(line -> { + line = line.trim(); + String hyperLink = ""; + if(line.trim().contains("https://")){ + int startIndex = line.indexOf("https://"); + int endIndex = line.lastIndexOf("/"); + hyperLink = line.substring(startIndex, endIndex); + return String.format("%s
", hyperLink, line); + } + return String.format("%s
", line); + }) + + .collect(Collectors.joining(LINE_SEPARATOR)); + + resultMap.put("description", infoDescription); + } + + Configuration configuration = new Configuration(); + configuration.setClassForTemplateLoading(Api.class, "/"); + configuration.setDirectoryForTemplateLoading(new File("src/main/resources/")); + + Template template = configuration.getTemplate("swagger.html.ftl"); + + String outputDirStr = schemaDir + "/src/main/resources/aai_swagger_html"; + + File outputDir = new File(outputDirStr); + + if(!outputDir.exists()){ + boolean resp = outputDir.mkdir(); + if(!resp){ + System.err.println("Unable to create the directory: " + outputDirStr); + System.exit(1); + } + } else if(outputDir.isFile()){ + System.err.println("Unable to create the directory: " + outputDirStr + " since a filename with that string exists"); + System.exit(1); + } + + Writer file = new FileWriter(new File(outputDirStr + "/aai_swagger_" + versionToGenerate + ".html")); + template.process(resultMap, file); + } + + public static List convertToApi(Map pathMap){ + + if(pathMap == null) + throw new IllegalArgumentException(); + + List apis = new ArrayList<>(); + + pathMap.forEach( (pathKey, pathValue) -> { + + Api api = new Api(); + Map httpVerbMap = (Map) pathValue; + List httpVerbs = new ArrayList<>(); + + api.setPath(pathKey); + + httpVerbMap.forEach((httpVerbKey, httpVerbValue) -> { + + Api.HttpVerb httpVerb = new Api.HttpVerb(); + + Map httpVerbValueMap = (Map)httpVerbValue; + + httpVerb.setType(httpVerbKey); + + if(httpVerbValueMap.containsKey("tags")){ + httpVerb.setTags((List)httpVerbValueMap.get("tags")); + } + + if(httpVerbValueMap.containsKey("summary")){ + httpVerb.setSummary((String)httpVerbValueMap.get("summary")); + } + + if(httpVerbValueMap.containsKey("operationId")){ + httpVerb.setOperationId((String)httpVerbValueMap.get("operationId")); + } + + if(httpVerbValueMap.containsKey("consumes")){ + httpVerb.setConsumes((List)httpVerbValueMap.get("consumes")); + if(httpVerb.getConsumes() != null){ + httpVerb.setConsumerEnabled(true); + } + } + + if(httpVerbValueMap.containsKey("produces")){ + httpVerb.setProduces((List)httpVerbValueMap.get("produces")); + } + + if(httpVerbValueMap.containsKey("parameters")){ + List> parameters = (List>) httpVerbValueMap.get("parameters"); + List> requestParameters = parameters + .stream() + .filter((parameter) -> !parameter.get("name").equals("body")) + .collect(Collectors.toList()); + httpVerb.setParameters(requestParameters); + if(httpVerb.getParameters() != null){ + httpVerb.setParametersEnabled(true); + } + + List> requestBodyList = parameters + .stream() + .filter((parameter) -> parameter.get("name").equals("body")) + .collect(Collectors.toList()); + + Map requestBody = null; + + if(requestBodyList != null && requestBodyList.size() == 1){ + requestBody = requestBodyList.get(0); + httpVerb.setBodyParametersEnabled(true); + httpVerb.setBodyParameters(requestBody); + + if(requestBody != null && requestBody.containsKey("schema")){ + Map schemaMap = (Map)requestBody.get("schema"); + if(schemaMap != null && schemaMap.containsKey("$ref")){ + String schemaLink = schemaMap.get("$ref").toString(); + httpVerb.setSchemaLink(schemaLink); + int retCode = schemaLink.lastIndexOf('/'); + if(retCode != -1 && retCode != schemaLink.length()){ + httpVerb.setSchemaType(schemaLink.substring(retCode)); + } + } + } + } + } + + if(httpVerbValueMap.containsKey("responses")){ + + List responses = new ArrayList(); + + Map responsesMap = (Map) httpVerbValueMap.get("responses"); + + responsesMap + .entrySet() + .stream() + .filter((res) -> !"default".equalsIgnoreCase(res.getKey())) + .forEach((responseMap) -> { + + Map responseValueMap = (Map)responseMap.getValue(); + + Api.HttpVerb.Response response = new Api.HttpVerb.Response(); + + response.setResponseCode(responseMap.getKey()); + response.setDescription((String) responseValueMap.get("description")); + + if(responseValueMap != null && responseValueMap.containsKey("schema")){ + Map schemaMap = (Map)responseValueMap.get("schema"); + if(schemaMap != null && schemaMap.containsKey("$ref")){ + String schemaLink = schemaMap.get("$ref").toString(); + httpVerb.setHasReturnSchema(true); + httpVerb.setReturnSchemaLink(schemaLink); + int retCode = schemaLink.lastIndexOf('/'); + if(retCode != -1 && retCode != schemaLink.length()){ + httpVerb.setReturnSchemaObject(schemaLink.substring(retCode)); + } + } + } + + responses.add(response); + } + ); + + httpVerb.setResponses(responses); + } + + httpVerbs.add(httpVerb); + }); + + api.setHttpMethods(httpVerbs); + apis.add(api); + }); + + return apis; + } + + public static List convertToDefinition(Map definitionMap) { + + if(definitionMap == null) + throw new IllegalArgumentException(); + + List defintionsList = new ArrayList<>(); + + definitionMap + .entrySet() + .forEach((entry) -> { + + Definition definition = new Definition(); + String key = entry.getKey(); + Map valueMap = (Map) entry.getValue(); + + definition.setDefinitionName(key); + + if(valueMap.containsKey("description")){ + String description = valueMap.get("description").toString(); + description = formatDescription(description); + definition.setDefinitionDescription(description); + definition.setHasDescription(true); + } + + List definitionProperties = new ArrayList<>(); + + List requiredProperties = (valueMap.get("required") == null) ? new ArrayList<>() : (List) valueMap.get("required"); + + Set requiredPropsSet = requiredProperties.stream().collect(Collectors.toSet()); + + valueMap + .entrySet() + .stream() + .filter( (e) -> "properties".equals(e.getKey())) + .forEach((propertyEntries) -> { + Map propertyRealEntries = (Map) propertyEntries.getValue(); + propertyRealEntries + .entrySet() + .forEach((propertyEntry) -> { + Definition.Property definitionProperty = new Definition.Property(); + String propertyKey = propertyEntry.getKey(); + if(requiredPropsSet.contains(propertyKey)){ + definitionProperty.setRequired(true); + } + definitionProperty.setPropertyName(propertyKey); + Map definitionPropertyMap = (Map) propertyEntry.getValue(); + + if(definitionPropertyMap.containsKey("description")){ + definitionProperty.setPropertyDescription(definitionPropertyMap.get("description").toString()); + definitionProperty.setHasPropertyDescription(true); + } + if(definitionPropertyMap.containsKey("type")){ + String type = definitionPropertyMap.get("type").toString(); + definitionProperty.setPropertyType(type); + definitionProperty.setHasType(true); + if ("array".equals(type)) { + definitionProperty.setPropertyType("object[]"); + if(!definitionPropertyMap.containsKey("items")){ + throw new RuntimeException("Unable to find the property items even though the type is array for " + propertyEntry.getKey()); + } else { + Map itemMap = (Map) definitionPropertyMap.get("items"); + if(itemMap.containsKey("$ref")){ + definitionProperty.setHasPropertyReference(true); + String refItem = itemMap.get("$ref").toString(); + int retCode = refItem.lastIndexOf('/'); + if(retCode != -1 && retCode != refItem.length()){ + definitionProperty.setPropertyReferenceObjectName(refItem.substring(retCode + 1)); + } + definitionProperty.setPropertyReference(refItem); + } + } + } else { + if(definitionPropertyMap.containsKey("$ref")){ + definitionProperty.setHasPropertyReference(true); + String refItem = definitionPropertyMap.get("$ref").toString(); + int retCode = refItem.lastIndexOf('/'); + if(retCode != -1 && retCode != refItem.length()){ + definitionProperty.setPropertyReferenceObjectName(refItem.substring(retCode + 1)); + } + definitionProperty.setPropertyReference(refItem); + } + } + } + definitionProperties.add(definitionProperty); + }); + }); + + definition.setPropertyList(definitionProperties); + + List schemaProperties = definitionProperties. + stream() + .filter((o) -> o.isHasPropertyReference()) + .collect(Collectors.toList()); + + List regularProperties = definitionProperties. + stream() + .filter((o) -> !o.isHasPropertyReference()) + .collect(Collectors.toList()); + + definition.setRegularPropertyList(regularProperties); + definition.setSchemaPropertyList(schemaProperties); + + defintionsList.add(definition); + }); + return defintionsList; + } + + public static String formatDescription(String description){ + + description = Arrays.stream(description.split("\n")) + .map((line) -> { + line = line.trim(); + if(line.contains("######")){ + line = line.replaceAll("#", ""); + line = line.trim(); + String headerId = line.toLowerCase().replaceAll("\\s", "-"); + + if(line.contains("Related Nodes")){ + return String.format("
%s
%s
    ", headerId, line, LINE_SEPARATOR); + } else { + return String.format("
    %s
    ", headerId, line); + } + } else if(line.startsWith("-")){ + line = line.replaceFirst("-", ""); + line = line.trim(); + return String.format("
  • %s
  • ", line); + } else { + return String.format("

    %s

    ", line); + } + }) + .collect(Collectors.joining(LINE_SEPARATOR)); + + if(description.contains("
      ")){ + description = description + "
    "; + } + + return description; + } + +} diff --git a/aai-core/src/main/java/org/onap/aai/workarounds/LegacyURITransformer.java b/aai-core/src/main/java/org/onap/aai/workarounds/LegacyURITransformer.java new file mode 100644 index 00000000..aabad328 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/workarounds/LegacyURITransformer.java @@ -0,0 +1,94 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.workarounds; + +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class LegacyURITransformer { + + private final Pattern legacyUriPattern = Pattern.compile("/aai/servers/(?v[23])/(?.*?)/vservers/(?[^/]*?$)"); + private final Pattern currentUriPattern = Pattern.compile("/aai/(?v\\d+)/cloud-infrastructure/tenants/tenant/(?.*?)/vservers/vserver/(?[^/]*?$)"); + /** + * Instantiates a new legacy URL transformer. + */ + private LegacyURITransformer() { + + } + + private static class Helper { + private static final LegacyURITransformer INSTANCE = new LegacyURITransformer(); + } + + /** + * Gets the single instance of LegacyURLTransformer. + * + * @return single instance of LegacyURLTransformer + */ + public static LegacyURITransformer getInstance() { + return Helper.INSTANCE; + } + + /** + * Gets the legacy URL. + * + * @param url the url + * @return the legacy URL + * @throws URISyntaxException + * @throws MalformedURLException the malformed URL exception + */ + public URI getLegacyURI(URI url) throws URISyntaxException { + String replacement = "/aai/servers/${version}/${tenantKey}/vservers/${vserverKey}"; + String result = url.toString(); + Matcher m = currentUriPattern.matcher(result); + if (m.find()) { + result = m.replaceFirst(replacement); + + } + + return new URI(result); + + } + + /** + * Gets the current URL. + * + * @param url the url + * @return the current URL + * @throws URISyntaxException + * @throws MalformedURLException the malformed URL exception + */ + public URI getCurrentURI(URI url) throws URISyntaxException { + String replacement = "/aai/${version}/cloud-infrastructure/tenants/tenant/${tenantKey}/vservers/vserver/${vserverKey}"; + String result = url.toString(); + Matcher m = legacyUriPattern.matcher(result); + if (m.find()) { + result = m.replaceFirst(replacement); + + } + + return new URI(result); + } +} 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 new file mode 100644 index 00000000..e2be0d77 --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/workarounds/NamingExceptions.java @@ -0,0 +1,80 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.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; + + } +} diff --git a/aai-core/src/main/java/org/onap/aai/workarounds/RemoveDME2QueryParams.java b/aai-core/src/main/java/org/onap/aai/workarounds/RemoveDME2QueryParams.java new file mode 100644 index 00000000..1116ed5b --- /dev/null +++ b/aai-core/src/main/java/org/onap/aai/workarounds/RemoveDME2QueryParams.java @@ -0,0 +1,66 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.workarounds; + +import javax.ws.rs.core.MultivaluedMap; + +public class RemoveDME2QueryParams { + + private final String[] blacklist = {"version", "envContext", "routeOffer"}; + + + /** + * Should remove query params. + * + * @param params the params + * @return true, if successful + */ + public boolean shouldRemoveQueryParams(MultivaluedMap params) { + boolean remove = true; + + for (String param : blacklist) { + if (!params.containsKey(param)) { + remove = false; + break; + } + } + + return remove; + + } + + /** + * Removes the query params. + * + * @param params the params + */ + public void removeQueryParams(MultivaluedMap params) { + + + for (String param : blacklist) { + params.remove(param); + } + + + } + +} diff --git a/aai-core/src/main/java/org/openecomp/aai/audit/ListEndpoints.java b/aai-core/src/main/java/org/openecomp/aai/audit/ListEndpoints.java deleted file mode 100644 index 1e1df8fc..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/audit/ListEndpoints.java +++ /dev/null @@ -1,302 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.audit; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.commons.lang.StringUtils; - -import org.openecomp.aai.db.props.AAIProperties; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.introspection.LoaderFactory; -import org.openecomp.aai.introspection.ModelType; -import org.openecomp.aai.introspection.Version; -import org.openecomp.aai.introspection.exceptions.AAIUnknownObjectException; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.google.common.base.CaseFormat; - -/** - * The Class ListEndpoints. - */ -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 endpoints = new ArrayList<>(); - private Map endpointToLogicalName = new HashMap(); - - /** - * The main method. - * - * @param args the arguments - */ - public static void main(String[] args) { - ListEndpoints endPoints = new ListEndpoints(AAIProperties.LATEST); - - System.out.println(endPoints.toString("relationship-list")); - - } - - /** - * Instantiates a new list endpoints. - * - * @param version the version - */ - public ListEndpoints(Version version) { - - Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, version); - - try { - final Introspector start = loader.introspectorFromName(this.start); - Set startMap = new HashSet<>(); - beginAudit(start, "/aai/" + 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 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 properties = obj.getProperties(); - Set 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)", 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 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)", e); - } - } - } else if (obj.isComplexType(propName)) { - try { - final Introspector nestedObj = obj.newIntrospectorInstanceOfProperty(propName); - Set 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)", 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 getLogicalNames() { - - return endpointToLogicalName; - - } - - /** - * Gets the endpoints. - * - * @return the endpoints - */ - public List getEndpoints() { - - return this.getEndpoints(""); - - } - - /** - * Gets the endpoints. - * - * @param filterOut the filter out - * @return the endpoints - */ - public List getEndpoints(String filterOut) { - List 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/openecomp/aai/auth/exceptions/AAIUnrecognizedFunctionException.java b/aai-core/src/main/java/org/openecomp/aai/auth/exceptions/AAIUnrecognizedFunctionException.java deleted file mode 100644 index 5a3d8c6b..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/auth/exceptions/AAIUnrecognizedFunctionException.java +++ /dev/null @@ -1,42 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.auth.exceptions; - -import org.openecomp.aai.exceptions.AAIException; - -public class AAIUnrecognizedFunctionException extends AAIException { - - private static final long serialVersionUID = 3297064867724071290L; - - public AAIUnrecognizedFunctionException() {} - - public AAIUnrecognizedFunctionException(String message) { - super("AAI_3012", message); - } - - public AAIUnrecognizedFunctionException(Throwable cause) { - super("AAI_3012",cause); - } - - public AAIUnrecognizedFunctionException(String message, Throwable cause) { - super("AAI_3012", cause, message); - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/db/DbMethHelper.java b/aai-core/src/main/java/org/openecomp/aai/db/DbMethHelper.java deleted file mode 100644 index 79172d9b..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/db/DbMethHelper.java +++ /dev/null @@ -1,158 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.db; - -import java.io.UnsupportedEncodingException; -import java.net.URI; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Optional; - -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.apache.tinkerpop.gremlin.structure.VertexProperty; - -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.introspection.exceptions.AAIUnknownObjectException; -import org.openecomp.aai.parsers.query.QueryParser; -import org.openecomp.aai.parsers.relationship.RelationshipToURI; -import org.openecomp.aai.query.builder.QueryBuilder; -import org.openecomp.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 searchVertexByIdentityMap(String type, Map 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 results = queryParser.getQueryBuilder().toList(); - - return reduceToSingleVertex(results, map); - } - - /** - * @param type - * @param map - form [{propname}:{value}] - * @return - * @throws AAIException - */ - public Optional locateUniqueVertex(String type, Map map) throws AAIException { - - return reduceToSingleVertex(locateUniqueVertices(type, map), map); - } - - public List locateUniqueVertices(String type, Map 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 map) throws AAIUnknownObjectException { - final Introspector relationship = loader.introspectorFromName("relationship"); - relationship.setValue("related-to", type); - final List data = relationship.getValue("relationship-data"); - for (Entry 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 propHash) throws AAIUnknownObjectException { - final Introspector result = loader.introspectorFromName(targetNodeType); - for (Entry entry : propHash.entrySet()) { - result.setValue(entry.getKey(), entry.getValue()); - } - return result; - } - - private Optional reduceToSingleVertex(List vertices, Map 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 getVertexProperties(Vertex v) { - List retArr = new ArrayList<>(); - if( v == null ){ - retArr.add("null Node object passed to showPropertiesForNode()\n"); - } - else { - String nodeType; - Object ob = v.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> pI = v.properties(); - while( pI.hasNext() ){ - VertexProperty 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/openecomp/aai/db/props/AAIProperties.java b/aai-core/src/main/java/org/openecomp/aai/db/props/AAIProperties.java deleted file mode 100644 index caac6744..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/db/props/AAIProperties.java +++ /dev/null @@ -1,39 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.db.props; - -import org.openecomp.aai.introspection.Version; - -public class AAIProperties { - public static final String NODE_TYPE = "aai-node-type"; - public static final String LAST_MOD_SOURCE_OF_TRUTH = "last-mod-source-of-truth"; - public static final String SOURCE_OF_TRUTH = "source-of-truth"; - public static final String LAST_MOD_TS = "aai-last-mod-ts"; - public static final String UNIQUE_KEY = "aai-unique-key"; - public static final String CREATED_TS = "aai-created-ts"; - public static final String RESOURCE_VERSION = "resource-version"; - public static final String AAI_URI = "aai-uri"; - public static final Version LATEST = Version.v11; - public static final Integer MAXIMUM_DEPTH = 10000; - public static final String LINKED = "linked"; - public static final String DB_ALIAS_SUFFIX = "-local"; - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/db/schema/AuditDoc.java b/aai-core/src/main/java/org/openecomp/aai/db/schema/AuditDoc.java deleted file mode 100644 index 58d3dc0b..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/db/schema/AuditDoc.java +++ /dev/null @@ -1,89 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.db.schema; - -import java.util.List; - -import org.codehaus.jackson.annotate.JsonProperty; - -public class AuditDoc { - - private List properties; - private List indexes; - private List edgeLabels; - - /** - * Gets the properties. - * - * @return the properties - */ - public List getProperties() { - return properties; - } - - /** - * Sets the properties. - * - * @param properties the new properties - */ - public void setProperties(List properties) { - this.properties = properties; - } - - /** - * Gets the indexes. - * - * @return the indexes - */ - public List getIndexes() { - return indexes; - } - - /** - * Sets the indexes. - * - * @param indexes the new indexes - */ - public void setIndexes(List indexes) { - this.indexes = indexes; - } - - /** - * Gets the edge labels. - * - * @return the edge labels - */ - @JsonProperty("edge-labels") - public List getEdgeLabels() { - return edgeLabels; - } - - /** - * Sets the edge labels. - * - * @param edgeLabels the new edge labels - */ - public void setEdgeLabels(List edgeLabels) { - this.edgeLabels = edgeLabels; - } - - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/db/schema/AuditOXM.java b/aai-core/src/main/java/org/openecomp/aai/db/schema/AuditOXM.java deleted file mode 100644 index b7aab081..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/db/schema/AuditOXM.java +++ /dev/null @@ -1,249 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.db.schema; - -import java.io.IOException; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashSet; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Set; - -import javax.xml.XMLConstants; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; - -import org.openecomp.aai.serialization.db.EdgeRule; -import org.openecomp.aai.serialization.db.EdgeRules; -import org.w3c.dom.Document; -import org.w3c.dom.NodeList; -import org.xml.sax.SAXException; - -import org.openecomp.aai.db.props.AAIProperties; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.introspection.LoaderFactory; -import org.openecomp.aai.introspection.ModelType; -import org.openecomp.aai.introspection.Version; -import org.openecomp.aai.introspection.exceptions.AAIUnknownObjectException; -import org.openecomp.aai.schema.enums.ObjectMetadata; -import org.openecomp.aai.util.AAIConstants; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.google.common.collect.Multimap; -import com.thinkaurelius.titan.core.Cardinality; -import com.thinkaurelius.titan.core.Multiplicity; -import com.thinkaurelius.titan.core.schema.SchemaStatus; - -public class AuditOXM extends Auditor { - - private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(AuditOXM.class); - - private Set allObjects; - - /** - * Instantiates a new audit OXM. - * - * @param version the version - */ - public AuditOXM(Version version) { - Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, version); - Set objectNames = getAllObjects(version); - allObjects = new HashSet<>(); - for (String key : objectNames) { - try { - final Introspector temp = loader.introspectorFromName(key); - allObjects.add(temp); - this.createDBProperties(temp); - } catch (AAIUnknownObjectException e) { - LOGGER.warn("Skipping audit for object " + key + " (Unknown Object)", e); - } - } - for (Introspector temp : allObjects) { - this.createDBIndexes(temp); - } - createEdgeLabels(); - - } - - /** - * Gets the all objects. - * - * @param version the version - * @return the all objects - */ - private Set getAllObjects(Version version) { - String fileName = AAIConstants.AAI_HOME_ETC_OXM + "aai_oxm_" + version.toString() + ".xml"; - Set result = new HashSet<>(); - DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); - try { - docFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); - DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); - Document doc = docBuilder.parse(fileName); - NodeList list = doc.getElementsByTagName("java-type"); - for (int i = 0; i < list.getLength(); i++) { - result.add(list.item(i).getAttributes().getNamedItem("name").getNodeValue()); - } - } catch (ParserConfigurationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (SAXException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - result.remove("EdgePropNames"); - return result; - - } - - /** - * Creates the DB properties. - * - * @param temp the temp - */ - private void createDBProperties(Introspector temp) { - Set objectProperties = temp.getProperties(); - - for (String prop : objectProperties) { - if (!properties.containsKey(prop)) { - DBProperty dbProperty = new DBProperty(); - dbProperty.setName(prop); - if (temp.isListType(prop)) { - dbProperty.setCardinality(Cardinality.SET); - if (temp.isSimpleGenericType(prop)) { - Class clazz = null; - try { - clazz = Class.forName(temp.getGenericType(prop)); - } catch (ClassNotFoundException e) { - clazz = Object.class; - } - dbProperty.setTypeClass(clazz); - properties.put(prop, dbProperty); - } - } else { - dbProperty.setCardinality(Cardinality.SINGLE); - if (temp.isSimpleType(prop)) { - Class clazz = null; - try { - clazz = Class.forName(temp.getType(prop)); - } catch (ClassNotFoundException e) { - clazz = Object.class; - } - dbProperty.setTypeClass(clazz); - properties.put(prop, dbProperty); - } - } - } - } - - } - - /** - * Creates the DB indexes. - * - * @param temp the temp - */ - private void createDBIndexes(Introspector temp) { - String uniqueProps = temp.getMetadata(ObjectMetadata.UNIQUE_PROPS); - String namespace = temp.getMetadata(ObjectMetadata.NAMESPACE); - if (uniqueProps == null) { - uniqueProps = ""; - } - if (namespace == null) { - namespace = ""; - } - boolean isTopLevel = namespace != ""; - List unique = Arrays.asList(uniqueProps.split(",")); - Set indexed = temp.getIndexedProperties(); - Set keys = temp.getKeys(); - - for (String prop : indexed) { - DBIndex dbIndex = new DBIndex(); - LinkedHashSet properties = new LinkedHashSet<>(); - if (!this.indexes.containsKey(prop)) { - dbIndex.setName(prop); - dbIndex.setUnique(unique.contains(prop)); - properties.add(this.properties.get(prop)); - dbIndex.setProperties(properties); - dbIndex.setStatus(SchemaStatus.ENABLED); - this.indexes.put(prop, dbIndex); - } - } - if (keys.size() > 1 || isTopLevel) { - DBIndex dbIndex = new DBIndex(); - LinkedHashSet properties = new LinkedHashSet<>(); - dbIndex.setName("key-for-" + temp.getDbName()); - if (!this.indexes.containsKey(dbIndex.getName())) { - boolean isUnique = false; - if (isTopLevel) { - properties.add(this.properties.get(AAIProperties.NODE_TYPE)); - } - for (String key : keys) { - properties.add(this.properties.get(key)); - - if (unique.contains(key) && !isUnique) { - isUnique = true; - } - } - dbIndex.setUnique(isUnique); - dbIndex.setProperties(properties); - dbIndex.setStatus(SchemaStatus.ENABLED); - this.indexes.put(dbIndex.getName(), dbIndex); - } - } - - } - - /** - * Creates the edge labels. - */ - private void createEdgeLabels() { - Multimap edgeRules = EdgeRules.getInstance().getAllRules(); - for (String key : edgeRules.keySet()) { - Collection collection = edgeRules.get(key); - EdgeProperty prop = new EdgeProperty(); - //there is only ever one, they used the wrong type for EdgeRules - String label = ""; - for (EdgeRule item : collection) { - label = item.getLabel(); - } - prop.setName(label); - prop.setMultiplicity(Multiplicity.MULTI); - this.edgeLabels.put(label, prop); - } - } - - /** - * Gets the all introspectors. - * - * @return the all introspectors - */ - public Set getAllIntrospectors() { - return this.allObjects; - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/db/schema/AuditTitan.java b/aai-core/src/main/java/org/openecomp/aai/db/schema/AuditTitan.java deleted file mode 100644 index 838a9b60..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/db/schema/AuditTitan.java +++ /dev/null @@ -1,123 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.db.schema; - - -import java.util.Iterator; -import java.util.LinkedHashSet; - -import org.apache.tinkerpop.gremlin.structure.Vertex; - -import com.thinkaurelius.titan.core.EdgeLabel; -import com.thinkaurelius.titan.core.PropertyKey; -import com.thinkaurelius.titan.core.TitanGraph; -import com.thinkaurelius.titan.core.schema.TitanGraphIndex; -import com.thinkaurelius.titan.core.schema.TitanManagement; - -public class AuditTitan extends Auditor { - - private final TitanGraph graph; - - /** - * Instantiates a new audit titan. - * - * @param g the g - */ - public AuditTitan (TitanGraph g) { - this.graph = g; - buildSchema(); - } - - /** - * Builds the schema. - */ - private void buildSchema() { - populateProperties(); - populateIndexes(); - populateEdgeLabels(); - } - - /** - * Populate properties. - */ - private void populateProperties() { - TitanManagement mgmt = graph.openManagement(); - Iterable iterable = mgmt.getRelationTypes(PropertyKey.class); - Iterator titanProperties = iterable.iterator(); - PropertyKey propKey; - while (titanProperties.hasNext()) { - propKey = titanProperties.next(); - DBProperty prop = new DBProperty(); - - prop.setName(propKey.name()); - prop.setCardinality(propKey.cardinality()); - prop.setTypeClass(propKey.dataType()); - - this.properties.put(prop.getName(), prop); - } - } - - /** - * Populate indexes. - */ - private void populateIndexes() { - TitanManagement mgmt = graph.openManagement(); - Iterable iterable = mgmt.getGraphIndexes(Vertex.class); - Iterator titanIndexes = iterable.iterator(); - TitanGraphIndex titanIndex; - while (titanIndexes.hasNext()) { - titanIndex = titanIndexes.next(); - if (titanIndex.isCompositeIndex()) { - DBIndex index = new DBIndex(); - LinkedHashSet dbProperties = new LinkedHashSet<>(); - index.setName(titanIndex.name()); - index.setUnique(titanIndex.isUnique()); - PropertyKey[] keys = titanIndex.getFieldKeys(); - for (PropertyKey key : keys) { - dbProperties.add(this.properties.get(key.name())); - } - index.setProperties(dbProperties); - index.setStatus(titanIndex.getIndexStatus(keys[0])); - this.indexes.put(index.getName(), index); - } - } - } - - /** - * Populate edge labels. - */ - private void populateEdgeLabels() { - TitanManagement mgmt = graph.openManagement(); - Iterable iterable = mgmt.getRelationTypes(EdgeLabel.class); - Iterator titanEdgeLabels = iterable.iterator(); - EdgeLabel edgeLabel; - while (titanEdgeLabels.hasNext()) { - edgeLabel = titanEdgeLabels.next(); - EdgeProperty edgeProperty = new EdgeProperty(); - - edgeProperty.setName(edgeLabel.name()); - edgeProperty.setMultiplicity(edgeLabel.multiplicity()); - - this.edgeLabels.put(edgeProperty.getName(), edgeProperty); - } - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/db/schema/Auditor.java b/aai-core/src/main/java/org/openecomp/aai/db/schema/Auditor.java deleted file mode 100644 index cd811041..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/db/schema/Auditor.java +++ /dev/null @@ -1,54 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.db.schema; - -import java.util.*; - -public abstract class Auditor { - - protected Map properties = new HashMap<>(); - protected Map indexes = new HashMap<>(); - protected Map edgeLabels = new HashMap<>(); - - /** - * Gets the audit doc. - * - * @return the audit doc - */ - public AuditDoc getAuditDoc() { - AuditDoc doc = new AuditDoc(); - List propertyList = new ArrayList<>(); - List indexList = new ArrayList<>(); - List edgeLabelList = new ArrayList<>(); - propertyList.addAll(this.properties.values()); - indexList.addAll(this.indexes.values()); - edgeLabelList.addAll(this.edgeLabels.values()); - Collections.sort(propertyList, new CompareByName()); - Collections.sort(indexList, new CompareByName()); - Collections.sort(edgeLabelList, new CompareByName()); - - doc.setProperties(propertyList); - doc.setIndexes(indexList); - doc.setEdgeLabels(edgeLabelList); - - return doc; - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/db/schema/AuditorFactory.java b/aai-core/src/main/java/org/openecomp/aai/db/schema/AuditorFactory.java deleted file mode 100644 index 66e52820..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/db/schema/AuditorFactory.java +++ /dev/null @@ -1,47 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.db.schema; - -import org.openecomp.aai.introspection.Version; -import com.thinkaurelius.titan.core.TitanGraph; - -public class AuditorFactory { - - /** - * Gets the OXM auditor. - * - * @param v the v - * @return the OXM auditor - */ - public static Auditor getOXMAuditor (Version v) { - return new AuditOXM(v); - } - - /** - * Gets the graph auditor. - * - * @param g the g - * @return the graph auditor - */ - public static Auditor getGraphAuditor (TitanGraph g) { - return new AuditTitan(g); - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/db/schema/CompareByName.java b/aai-core/src/main/java/org/openecomp/aai/db/schema/CompareByName.java deleted file mode 100644 index ea45fd75..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/db/schema/CompareByName.java +++ /dev/null @@ -1,36 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.db.schema; - -import java.util.Comparator; - -public class CompareByName implements Comparator{ - - /** - * {@inheritDoc} - */ - @Override - public int compare(Named o1, Named o2) { - return o1.getName().compareTo(o2.getName()); - } - - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/db/schema/DBIndex.java b/aai-core/src/main/java/org/openecomp/aai/db/schema/DBIndex.java deleted file mode 100644 index 9e157a93..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/db/schema/DBIndex.java +++ /dev/null @@ -1,105 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.db.schema; - -import java.util.LinkedHashSet; -import java.util.Set; - -import com.thinkaurelius.titan.core.schema.SchemaStatus; - -public class DBIndex implements Named { - - private String name = null; - private boolean unique = false; - private LinkedHashSet properties = new LinkedHashSet<>(); - private SchemaStatus status = null; - - /** - * Gets the name - */ - public String getName() { - return name; - } - - /** - * Sets the name. - * - * @param name the new name - */ - public void setName(String name) { - this.name = name; - } - - /** - * Checks if is unique. - * - * @return true, if is unique - */ - public boolean isUnique() { - return unique; - } - - /** - * Sets the unique. - * - * @param unique the new unique - */ - public void setUnique(boolean unique) { - this.unique = unique; - } - - /** - * Gets the properties. - * - * @return the properties - */ - public Set getProperties() { - return properties; - } - - /** - * Sets the properties. - * - * @param properties the new properties - */ - public void setProperties(LinkedHashSet properties) { - this.properties = properties; - } - - /** - * Gets the status. - * - * @return the status - */ - public SchemaStatus getStatus() { - return status; - } - - /** - * Sets the status. - * - * @param status the new status - */ - public void setStatus(SchemaStatus status) { - this.status = status; - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/db/schema/DBProperty.java b/aai-core/src/main/java/org/openecomp/aai/db/schema/DBProperty.java deleted file mode 100644 index d142e15b..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/db/schema/DBProperty.java +++ /dev/null @@ -1,85 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.db.schema; - -import org.openecomp.aai.introspection.Introspector; -import com.thinkaurelius.titan.core.Cardinality; - -public class DBProperty implements Named { - - - private String name = null; - private Cardinality cardinality = null; - private Class typeClass = null; - - /** - * Gets the name - */ - public String getName() { - return name; - } - - /** - * Sets the name. - * - * @param name the new name - */ - public void setName(String name) { - this.name = name; - } - - /** - * Gets the cardinality. - * - * @return the cardinality - */ - public Cardinality getCardinality() { - return cardinality; - } - - /** - * Sets the cardinality. - * - * @param cardinality the new cardinality - */ - public void setCardinality(Cardinality cardinality) { - this.cardinality = cardinality; - } - - /** - * Gets the type class. - * - * @return the type class - */ - public Class getTypeClass() { - return typeClass; - } - - /** - * Sets the type class. - * - * @param type the new type class - */ - public void setTypeClass(Class type) { - this.typeClass = type; - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/db/schema/EdgeProperty.java b/aai-core/src/main/java/org/openecomp/aai/db/schema/EdgeProperty.java deleted file mode 100644 index 0f9fafd3..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/db/schema/EdgeProperty.java +++ /dev/null @@ -1,69 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.db.schema; - -import com.thinkaurelius.titan.core.Multiplicity; -import org.codehaus.jackson.annotate.JsonProperty; -import org.codehaus.jackson.annotate.JsonPropertyOrder; - -@JsonPropertyOrder({ "label", "multiplicity" }) -public class EdgeProperty implements Named { - - private String name = null; - private Multiplicity multiplicity = null; - - /** - * Gets the name - */ - @JsonProperty("label") - public String getName() { - return name; - } - - /** - * Sets the name. - * - * @param name the new name - */ - @JsonProperty("label") - public void setName(String name) { - this.name = name; - } - - /** - * Gets the multiplicity. - * - * @return the multiplicity - */ - public Multiplicity getMultiplicity() { - return multiplicity; - } - - /** - * Sets the multiplicity. - * - * @param multiplicity the new multiplicity - */ - public void setMultiplicity(Multiplicity multiplicity) { - this.multiplicity = multiplicity; - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/db/schema/ManageTitanSchema.java b/aai-core/src/main/java/org/openecomp/aai/db/schema/ManageTitanSchema.java deleted file mode 100644 index a7f835e6..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/db/schema/ManageTitanSchema.java +++ /dev/null @@ -1,329 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.db.schema; - -import java.util.ArrayList; -import java.util.List; -import java.util.Set; - -import org.apache.tinkerpop.gremlin.structure.Vertex; - -import org.openecomp.aai.introspection.Version; -import com.thinkaurelius.titan.core.PropertyKey; -import com.thinkaurelius.titan.core.TitanGraph; -import com.thinkaurelius.titan.core.schema.SchemaStatus; -import com.thinkaurelius.titan.core.schema.TitanGraphIndex; -import com.thinkaurelius.titan.core.schema.TitanManagement; -import com.thinkaurelius.titan.core.schema.TitanManagement.IndexBuilder; - -public class ManageTitanSchema { - - - private TitanManagement graphMgmt; - private TitanGraph graph; - private List aaiProperties; - private List aaiIndexes; - private List aaiEdgeProperties; - private Auditor oxmInfo = null; - private Auditor graphInfo = null; - - /** - * Instantiates a new manage titan schema. - * - * @param graph the graph - */ - public ManageTitanSchema(final TitanGraph graph) { - this.graph = graph; - oxmInfo = AuditorFactory.getOXMAuditor(Version.v8); - graphInfo = AuditorFactory.getGraphAuditor(graph); - } - - - /** - * Builds the schema. - */ - public void buildSchema() { - - this.graphMgmt = graph.openManagement(); - aaiProperties = new ArrayList<>(); - aaiEdgeProperties = new ArrayList<>(); - aaiIndexes = new ArrayList<>(); - aaiProperties.addAll(oxmInfo.getAuditDoc().getProperties()); - aaiIndexes.addAll(oxmInfo.getAuditDoc().getIndexes()); - aaiEdgeProperties.addAll(oxmInfo.getAuditDoc().getEdgeLabels()); - try { - createPropertyKeys(); - createIndexes(); - createEdgeLabels(); - } catch (Exception e) { - e.printStackTrace(); - graphMgmt.rollback(); - } - graphMgmt.commit(); - } - - /** - * Creates the property keys. - */ - private void createPropertyKeys() { - - - for (DBProperty prop : aaiProperties) { - - if (graphMgmt.containsPropertyKey(prop.getName())) { - PropertyKey key = graphMgmt.getPropertyKey(prop.getName()); - boolean isChanged = false; - if (!prop.getCardinality().equals(key.cardinality())) { - isChanged = true; - } - if (!prop.getTypeClass().equals(key.dataType())) { - isChanged = true; - } - if (isChanged) { - //must modify! - this.replaceProperty(prop); - } - } else { - //create a new property key - System.out.println("Key: " + prop.getName() + " not found - adding"); - graphMgmt.makePropertyKey(prop.getName()).dataType(prop.getTypeClass()).cardinality(prop.getCardinality()).make(); - } - } - - } - - /** - * Creates the indexes. - */ - private void createIndexes() { - - for (DBIndex index : aaiIndexes) { - Set props = index.getProperties(); - boolean isChanged = false; - boolean isNew = false; - List keyList = new ArrayList<>(); - for (DBProperty prop : props) { - keyList.add(graphMgmt.getPropertyKey(prop.getName())); - } - if (graphMgmt.containsGraphIndex(index.getName())) { - TitanGraphIndex titanIndex = graphMgmt.getGraphIndex(index.getName()); - PropertyKey[] dbKeys = titanIndex.getFieldKeys(); - if (dbKeys.length != keyList.size()) { - isChanged = true; - } else { - int i = 0; - for (PropertyKey key : keyList) { - if (!dbKeys[i].equals(key)) { - isChanged = true; - break; - } - i++; - } - } - } else { - isNew = true; - } - if (keyList.size() > 0) { - this.createIndex(graphMgmt, index.getName(), keyList, index.isUnique(), isNew, isChanged); - } - } - } - - // 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. - /** - * Creates the edge labels. - */ - private void createEdgeLabels() { - - - for (EdgeProperty prop : aaiEdgeProperties) { - - if (graphMgmt.containsEdgeLabel(prop.getName())) { - // see what changed - } else { - graphMgmt.makeEdgeLabel(prop.getName()).multiplicity(prop.getMultiplicity()).make(); - } - - } - - - } - - /** - * Creates the property. - * - * @param mgmt the mgmt - * @param prop the prop - */ - private void createProperty(TitanManagement mgmt, DBProperty prop) { - if (mgmt.containsPropertyKey(prop.getName())) { - PropertyKey key = mgmt.getPropertyKey(prop.getName()); - boolean isChanged = false; - if (!prop.getCardinality().equals(key.cardinality())) { - isChanged = true; - } - if (!prop.getTypeClass().equals(key.dataType())) { - isChanged = true; - } - if (isChanged) { - //must modify! - this.replaceProperty(prop); - } - } else { - //create a new property key - System.out.println("Key: " + prop.getName() + " not found - adding"); - mgmt.makePropertyKey(prop.getName()).dataType(prop.getTypeClass()).cardinality(prop.getCardinality()).make(); - } - } - - /** - * Creates the index. - * - * @param mgmt the mgmt - * @param indexName the index name - * @param keys the keys - * @param isUnique the is unique - * @param isNew the is new - * @param isChanged the is changed - */ - private void createIndex(TitanManagement mgmt, String indexName, List keys, boolean isUnique, boolean isNew, boolean isChanged) { - - /*if (isChanged) { - System.out.println("Changing index: " + indexName); - TitanGraphIndex oldIndex = mgmt.getGraphIndex(indexName); - mgmt.updateIndex(oldIndex, SchemaAction.DISABLE_INDEX); - mgmt.commit(); - //cannot remove indexes - //graphMgmt.updateIndex(oldIndex, SchemaAction.REMOVE_INDEX); - }*/ - if (isNew || isChanged) { - - if (isNew) { - IndexBuilder builder = mgmt.buildIndex(indexName,Vertex.class); - for (PropertyKey k : keys) { - builder.addKey(k); - } - if (isUnique) { - builder.unique(); - } - builder.buildCompositeIndex(); - System.out.println("Built index for " + indexName + " with keys: " + keys); - - //mgmt.commit(); - } - - //mgmt = graph.asAdmin().getManagementSystem(); - //mgmt.updateIndex(mgmt.getGraphIndex(indexName), SchemaAction.REGISTER_INDEX); - //mgmt.commit(); - - try { - //waitForCompletion(indexName); - //TitanIndexRepair.hbaseRepair(AAIConstants.AAI_CONFIG_FILENAME, indexName, ""); - } catch (Exception e) { - // TODO Auto-generated catch block - graph.tx().rollback(); - graph.close(); - e.printStackTrace(); - } - - //mgmt = graph.asAdmin().getManagementSystem(); - //mgmt.updateIndex(mgmt.getGraphIndex(indexName), SchemaAction.REINDEX); - - //mgmt.updateIndex(mgmt.getGraphIndex(indexName), SchemaAction.ENABLE_INDEX); - - //mgmt.commit(); - - } - } - - /** - * Wait for completion. - * - * @param name the name - * @throws InterruptedException the interrupted exception - */ - private void waitForCompletion(String name) throws InterruptedException { - - boolean registered = false; - long before = System.currentTimeMillis(); - while (!registered) { - Thread.sleep(500L); - TitanManagement mgmt = graph.openManagement(); - TitanGraphIndex idx = mgmt.getGraphIndex(name); - registered = true; - for (PropertyKey k : idx.getFieldKeys()) { - SchemaStatus s = idx.getIndexStatus(k); - registered &= s.equals(SchemaStatus.REGISTERED); - } - mgmt.rollback(); - } - System.out.println("Index REGISTERED in " + (System.currentTimeMillis() - before) + " ms"); - } - - /** - * Replace property. - * - * @param key the key - */ - private void replaceProperty(DBProperty key) { - - - - - } - - /** - * Update index. - * - * @param index the index - */ - public void updateIndex(DBIndex index) { - - TitanManagement mgmt = graph.openManagement(); - List keys = new ArrayList<>(); - boolean isNew = false; - boolean isChanged = false; - for (DBProperty prop : index.getProperties()) { - createProperty(mgmt, prop); - keys.add(mgmt.getPropertyKey(prop.getName())); - } - if (mgmt.containsGraphIndex(index.getName())) { - System.out.println("index already exists"); - isNew = false; - isChanged = true; - } else { - isNew = true; - isChanged = false; - } - this.createIndex(mgmt, index.getName(), keys, index.isUnique(), isNew, isChanged); - - mgmt.commit(); - - } - - - - - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/db/schema/Named.java b/aai-core/src/main/java/org/openecomp/aai/db/schema/Named.java deleted file mode 100644 index 850af57a..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/db/schema/Named.java +++ /dev/null @@ -1,31 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.db.schema; - -public interface Named { - - /** - * Gets the name. - * - * @return the name - */ - public String getName(); -} diff --git a/aai-core/src/main/java/org/openecomp/aai/db/schema/ScriptDriver.java b/aai-core/src/main/java/org/openecomp/aai/db/schema/ScriptDriver.java deleted file mode 100644 index 9a90ea28..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/db/schema/ScriptDriver.java +++ /dev/null @@ -1,93 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.db.schema; - -import java.io.IOException; - -import org.codehaus.jackson.JsonGenerationException; -import org.codehaus.jackson.map.JsonMappingException; -import org.codehaus.jackson.map.ObjectMapper; - -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Version; -import org.openecomp.aai.util.AAIConfig; -import com.beust.jcommander.JCommander; -import com.beust.jcommander.Parameter; -import com.thinkaurelius.titan.core.TitanFactory; -import com.thinkaurelius.titan.core.TitanGraph; - -public class ScriptDriver { - - - /** - * The main method. - * - * @param args the arguments - * @throws AAIException the AAI exception - * @throws JsonGenerationException the json generation exception - * @throws JsonMappingException the json mapping exception - * @throws IOException Signals that an I/O exception has occurred. - */ - public static void main (String[] args) throws AAIException, IOException { - CommandLineArgs cArgs = new CommandLineArgs(); - - new JCommander(cArgs, args); - - if (cArgs.help) { - System.out.println("-c [path to graph configuration] -type [what you want to audit - oxm or graph]"); - } - String config = cArgs.config; - AAIConfig.init(); - try (TitanGraph graph = TitanFactory.open(config)) { - if (!("oxm".equals(cArgs.type) || "graph".equals(cArgs.type))) { - System.out.println("type: " + cArgs.type + " not recognized."); - System.exit(1); - } - - AuditDoc doc = null; - if ("oxm".equals(cArgs.type)) { - doc = AuditorFactory.getOXMAuditor(Version.v8).getAuditDoc(); - } else if ("graph".equals(cArgs.type)) { - doc = AuditorFactory.getGraphAuditor(graph).getAuditDoc(); - } - - ObjectMapper mapper = new ObjectMapper(); - - String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(doc); - System.out.println(json); - } - } - -} - -class CommandLineArgs { - - @Parameter(names = "--help", description = "Help") - public boolean help = false; - - @Parameter(names = "-c", description = "Configuration", required=true) - public String config; - - @Parameter(names = "-type", description = "Type", required=true) - public String type = "graph"; - - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/dbgen/DataGrooming.java b/aai-core/src/main/java/org/openecomp/aai/dbgen/DataGrooming.java deleted file mode 100644 index f2d6a4b8..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/dbgen/DataGrooming.java +++ /dev/null @@ -1,2319 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.dbgen; - -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Properties; -import java.util.Set; -import java.util.UUID; - -import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; -import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; -import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__; -import org.apache.tinkerpop.gremlin.structure.Direction; -import org.apache.tinkerpop.gremlin.structure.Edge; -import org.apache.tinkerpop.gremlin.structure.Graph; -import org.apache.tinkerpop.gremlin.structure.Property; -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.apache.tinkerpop.gremlin.structure.VertexProperty; -import org.openecomp.aai.db.props.AAIProperties; -import org.openecomp.aai.dbmap.AAIGraph; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.introspection.LoaderFactory; -import org.openecomp.aai.introspection.ModelType; -import org.openecomp.aai.introspection.exceptions.AAIUnknownObjectException; -import org.openecomp.aai.logging.ErrorLogHelper; -import org.openecomp.aai.serialization.db.AAIDirection; -import org.openecomp.aai.serialization.db.EdgeProperty; -import org.openecomp.aai.util.AAIConfig; -import org.openecomp.aai.util.AAIConstants; -import org.openecomp.aai.util.FormatDate; - -import com.att.eelf.configuration.Configuration; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.thinkaurelius.titan.core.TitanFactory; -import com.thinkaurelius.titan.core.TitanGraph; - - -public class DataGrooming { - - private static EELFLogger LOGGER; - private static final String FROMAPPID = "AAI-DB"; - private static final String TRANSID = UUID.randomUUID().toString(); - private static int dupeGrpsDeleted = 0; - - /** - * The main method. - * - * @param args the arguments - */ - public static void main(String[] args) { - - // Set the logging file properties to be used by EELFManager - Properties props = System.getProperties(); - props.setProperty(Configuration.PROPERTY_LOGGING_FILE_NAME, AAIConstants.AAI_DATA_GROOMING_LOGBACK_PROPS); - props.setProperty(Configuration.PROPERTY_LOGGING_FILE_PATH, AAIConstants.AAI_HOME_ETC_APP_PROPERTIES); - LOGGER = EELFManager.getInstance().getLogger(DataGrooming.class); - String ver = "version"; // Placeholder - Boolean doAutoFix = false; - Boolean edgesOnlyFlag = false; - Boolean dontFixOrphansFlag = false; - Boolean skipHostCheck = false; - Boolean singleCommits = false; - Boolean dupeCheckOff = false; - Boolean dupeFixOn = false; - Boolean ghost2CheckOff = false; - Boolean ghost2FixOn = false; - Boolean neverUseCache = false; - Boolean skipEdgeCheckFlag = false; - - int timeWindowMinutes = 0; // A value of 0 means that we will not have a time-window -- we will look - // at all nodes of the passed-in nodeType. - long windowStartTime = 0; // Translation of the window into a starting timestamp - - int maxRecordsToFix = AAIConstants.AAI_GROOMING_DEFAULT_MAX_FIX; - int sleepMinutes = AAIConstants.AAI_GROOMING_DEFAULT_SLEEP_MINUTES; - try { - String maxFixStr = AAIConfig.get("aai.grooming.default.max.fix"); - if( maxFixStr != null && !maxFixStr.equals("") ){ - maxRecordsToFix = Integer.parseInt(maxFixStr); - } - String sleepStr = AAIConfig.get("aai.grooming.default.sleep.minutes"); - if( sleepStr != null && !sleepStr.equals("") ){ - sleepMinutes = Integer.parseInt(sleepStr); - } - } - catch ( Exception e ){ - // Don't worry, we'll just use the defaults that we got from AAIConstants - LOGGER.warn("WARNING - could not pick up aai.grooming values from aaiconfig.properties file. "); - } - - String prevFileName = ""; - dupeGrpsDeleted = 0; - FormatDate fd = new FormatDate("yyyyMMddHHmm", "GMT"); - String dteStr = fd.getDateTime(); - String groomOutFileName = "dataGrooming." + dteStr + ".out"; - - String argString = ""; - for( int x = 0; x < args.length; x++ ) { - argString = argString + " " + args[x]; - } - LOGGER.info(" DataGrooming called with these options: [" + argString + "]"); - - if (args.length > 0) { - // They passed some arguments in that will affect processing - - for (int i = 0; i < args.length; i++) { - String thisArg = args[i]; - if (thisArg.equals("-edgesOnly")) { - edgesOnlyFlag = true; - } else if (thisArg.equals("-autoFix")) { - doAutoFix = true; - } else if (thisArg.equals("-skipHostCheck")) { - skipHostCheck = true; - } else if (thisArg.equals("-dontFixOrphans")) { - dontFixOrphansFlag = true; - } else if (thisArg.equals("-singleCommits")) { - singleCommits = true; - } else if (thisArg.equals("-dupeCheckOff")) { - dupeCheckOff = true; - } else if (thisArg.equals("-dupeFixOn")) { - dupeFixOn = true; - } else if (thisArg.equals("-ghost2CheckOff")) { - ghost2CheckOff = true; - } else if (thisArg.equals("-neverUseCache")) { - neverUseCache = true; - } else if (thisArg.equals("-ghost2FixOn")) { - ghost2FixOn = true; - } else if (thisArg.equals("-skipEdgeChecks")) { - skipEdgeCheckFlag = true; - } else if (thisArg.equals("-maxFix")) { - i++; - if (i >= args.length) { - LOGGER.error(" No value passed with -maxFix option. "); - System.exit(0); - } - String nextArg = args[i]; - try { - maxRecordsToFix = Integer.parseInt(nextArg); - } catch (Exception e) { - LOGGER.error("Bad value passed with -maxFix option: [" - + nextArg + "]"); - System.exit(0); - } - } else if (thisArg.equals("-sleepMinutes")) { - i++; - if (i >= args.length) { - LOGGER.error("No value passed with -sleepMinutes option."); - System.exit(0); - } - String nextArg = args[i]; - try { - sleepMinutes = Integer.parseInt(nextArg); - } catch (Exception e) { - LOGGER.error("Bad value passed with -sleepMinutes option: [" - + nextArg + "]"); - System.exit(0); - } - } else if (thisArg.equals("-timeWindowMinutes")) { - i++; - if (i >= args.length) { - LOGGER.error("No value passed with -timeWindowMinutes option."); - System.exit(0); - } - String nextArg = args[i]; - try { - timeWindowMinutes = Integer.parseInt(nextArg); - } catch (Exception e) { - LOGGER.error("Bad value passed with -timeWindowMinutes option: [" - + nextArg + "]"); - System.exit(0); - } - if( timeWindowMinutes > 0 ){ - // Translate the window value (ie. 30 minutes) into a unix timestamp like - // we use in the db - so we can select data created after that time. - windowStartTime = figureWindowStartTime( timeWindowMinutes ); - } - } else if (thisArg.equals("-f")) { - i++; - if (i >= args.length) { - LOGGER.error(" No value passed with -f option. "); - System.exit(0); - } - prevFileName = args[i]; - } else { - LOGGER.error(" Unrecognized argument passed to DataGrooming: [" - + thisArg + "]. "); - LOGGER.error(" Valid values are: -f -autoFix -maxFix -edgesOnly -dupeFixOn -donFixOrphans -sleepMinutes -neverUseCache"); - System.exit(0); - } - } - } - - - try { - LoaderFactory.createLoaderForVersion(ModelType.MOXY, AAIProperties.LATEST); - - } - catch (Exception ex){ - LOGGER.error("ERROR - Could not create loader", ex); - System.exit(1); - } - - - try { - if (!prevFileName.equals("")) { - // They are trying to fix some data based on a data in a - // previous file. - LOGGER.info(" Call doTheGrooming() with a previous fileName [" - + prevFileName + "] for cleanup. "); - Boolean finalShutdownFlag = true; - Boolean cacheDbOkFlag = false; - doTheGrooming(prevFileName, edgesOnlyFlag, dontFixOrphansFlag, - maxRecordsToFix, groomOutFileName, ver, singleCommits, - dupeCheckOff, dupeFixOn, ghost2CheckOff, ghost2FixOn, - finalShutdownFlag, cacheDbOkFlag, - skipEdgeCheckFlag, windowStartTime); - } else if (doAutoFix) { - // They want us to run the processing twice -- first to look for - // delete candidates, then after - // napping for a while, run it again and delete any candidates - // that were found by the first run. - // Note: we will produce a separate output file for each of the - // two runs. - LOGGER.info(" Doing an auto-fix call to Grooming. "); - LOGGER.info(" First, Call doTheGrooming() to look at what's out there. "); - Boolean finalShutdownFlag = false; - Boolean cacheDbOkFlag = true; - int fixCandCount = doTheGrooming("", edgesOnlyFlag, - dontFixOrphansFlag, maxRecordsToFix, groomOutFileName, - ver, singleCommits, dupeCheckOff, dupeFixOn, ghost2CheckOff, ghost2FixOn, - finalShutdownFlag, cacheDbOkFlag, - skipEdgeCheckFlag, windowStartTime); - if (fixCandCount == 0) { - LOGGER.info(" No fix-Candidates were found by the first pass, so no second/fix-pass is needed. "); - } else { - // We'll sleep a little and then run a fix-pass based on the - // first-run's output file. - try { - LOGGER.info("About to sleep for " + sleepMinutes - + " minutes."); - int sleepMsec = sleepMinutes * 60 * 1000; - Thread.sleep(sleepMsec); - } catch (InterruptedException ie) { - LOGGER.info("\n >>> Sleep Thread has been Interrupted <<< "); - System.exit(0); - } - - dteStr = fd.getDateTime(); - String secondGroomOutFileName = "dataGrooming." + dteStr - + ".out"; - LOGGER.info(" Now, call doTheGrooming() a second time and pass in the name of the file " - + "generated by the first pass for fixing: [" - + groomOutFileName + "]"); - finalShutdownFlag = true; - cacheDbOkFlag = false; - doTheGrooming(groomOutFileName, edgesOnlyFlag, - dontFixOrphansFlag, maxRecordsToFix, - secondGroomOutFileName, ver, singleCommits, - dupeCheckOff, dupeFixOn, ghost2CheckOff, ghost2FixOn, - finalShutdownFlag, cacheDbOkFlag, - skipEdgeCheckFlag, windowStartTime); - } - } else { - // Do the grooming - plain vanilla (no fix-it-file, no - // auto-fixing) - Boolean finalShutdownFlag = true; - LOGGER.info(" Call doTheGrooming() "); - Boolean cacheDbOkFlag = true; - if( neverUseCache ){ - // They have forbidden us from using a cached db connection. - cacheDbOkFlag = false; - } - doTheGrooming("", edgesOnlyFlag, dontFixOrphansFlag, - maxRecordsToFix, groomOutFileName, ver, singleCommits, - dupeCheckOff, dupeFixOn, ghost2CheckOff, ghost2FixOn, - finalShutdownFlag, cacheDbOkFlag, - skipEdgeCheckFlag, windowStartTime); - } - } catch (Exception ex) { - LOGGER.error("Exception while grooming data", ex); - } - - LOGGER.info(" Done! "); - System.exit(0); - - }// End of main() - - /** - * Do the grooming. - * - * @param fileNameForFixing the file name for fixing - * @param edgesOnlyFlag the edges only flag - * @param dontFixOrphansFlag the dont fix orphans flag - * @param maxRecordsToFix the max records to fix - * @param groomOutFileName the groom out file name - * @param version the version - * @param singleCommits the single commits - * @param dupeCheckOff the dupe check off - * @param dupeFixOn the dupe fix on - * @param ghost2CheckOff the ghost 2 check off - * @param ghost2FixOn the ghost 2 fix on - * @param finalShutdownFlag the final shutdown flag - * @param cacheDbOkFlag the cacheDbOk flag - * @return the int - */ - private static int doTheGrooming(String fileNameForFixing, - Boolean edgesOnlyFlag, Boolean dontFixOrphansFlag, - int maxRecordsToFix, String groomOutFileName, String version, - Boolean singleCommits, - Boolean dupeCheckOff, Boolean dupeFixOn, - Boolean ghost2CheckOff, Boolean ghost2FixOn, - Boolean finalShutdownFlag, Boolean cacheDbOkFlag, - Boolean skipEdgeCheckFlag, long windowStartTime) { - - LOGGER.debug(" Entering doTheGrooming \n"); - - int cleanupCandidateCount = 0; - BufferedWriter bw = null; - TitanGraph graph = null; - TitanGraph graph2 = null; - int deleteCount = 0; - boolean executeFinalCommit = false; - Set deleteCandidateList = new LinkedHashSet<>(); - Set processedVertices = new LinkedHashSet<>(); - Graph g = null; - Graph g2 = null; - try { - AAIConfig.init(); - String targetDir = AAIConstants.AAI_HOME + AAIConstants.AAI_FILESEP - + "logs" + AAIConstants.AAI_FILESEP + "data" - + AAIConstants.AAI_FILESEP + "dataGrooming"; - - // Make sure the target directory exists - new File(targetDir).mkdirs(); - - if (!fileNameForFixing.equals("")) { - deleteCandidateList = getDeleteList(targetDir, - fileNameForFixing, edgesOnlyFlag, dontFixOrphansFlag, - dupeFixOn); - } - - if (deleteCandidateList.size() > maxRecordsToFix) { - LOGGER.warn(" >> WARNING >> Delete candidate list size (" - + deleteCandidateList.size() - + ") is too big. The maxFix we are using is: " - + maxRecordsToFix - + ". No candidates will be deleted. "); - // Clear out the list so it won't be processed below. - deleteCandidateList = new LinkedHashSet<>(); - } - - String fullOutputFileName = targetDir + AAIConstants.AAI_FILESEP - + groomOutFileName; - File groomOutFile = new File(fullOutputFileName); - try { - groomOutFile.createNewFile(); - } catch (IOException e) { - String emsg = " Problem creating output file [" - + fullOutputFileName + "], exception=" + e.getMessage(); - throw new AAIException("AAI_6124", emsg); - } - - LOGGER.info(" Will write to " + fullOutputFileName ); - bw = new BufferedWriter(new FileWriter(groomOutFile.getAbsoluteFile())); - ErrorLogHelper.loadProperties(); - - LOGGER.info(" ---- NOTE --- about to open graph (takes a little while)--------\n"); - - if( cacheDbOkFlag ){ - // Since we're just reading (not deleting/fixing anything), we can use - // a cached connection to the DB - graph = TitanFactory.open(AAIConstants.CACHED_DB_CONFIG); - } - else { - graph = TitanFactory.open(AAIConstants.REALTIME_DB_CONFIG); - } - if (graph == null) { - String emsg = "null graph object in DataGrooming\n"; - throw new AAIException("AAI_6101", emsg); - } - - LOGGER.debug(" Got the graph object. "); - - g = graph.newTransaction(); - if (g == null) { - String emsg = "null graphTransaction object in DataGrooming\n"; - throw new AAIException("AAI_6101", emsg); - } - GraphTraversalSource source1 = g.traversal(); - - ArrayList errArr = new ArrayList<>(); - int totalNodeCount = 0; - HashMap misMatchedHash = new HashMap(); - HashMap orphanNodeHash = new HashMap(); - HashMap missingDepNodeHash = new HashMap(); - HashMap oneArmedEdgeHash = new HashMap(); - HashMap emptyVertexHash = new HashMap(); - HashMap ghostNodeHash = new HashMap(); - ArrayList dupeGroups = new ArrayList<>(); - - Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, AAIProperties.LATEST); - - Set> entrySet = loader.getAllObjects().entrySet(); - String ntList = ""; - - LOGGER.info(" Starting DataGrooming Processing "); - - if (edgesOnlyFlag) { - LOGGER.info(" NOTE >> Skipping Node processing as requested. Will only process Edges. << "); - } - else { - for (Entry entry : entrySet) { - String nType = entry.getKey(); - int thisNtCount = 0; - int thisNtDeleteCount = 0; - LOGGER.debug(" > Look at : [" + nType + "] ..."); - ntList = ntList + "," + nType; - - // Get a collection of the names of the key properties for this nodeType to use later - // Determine what the key fields are for this nodeType - Collection keyProps = entry.getValue().getKeys(); - - // Get the types of nodes that this nodetype depends on for uniqueness (if any) - Collection depNodeTypes = loader.introspectorFromName(nType).getDependentOn(); - - // Loop through all the nodes of this Node type - int lastShownForNt = 0; - ArrayList tmpList = new ArrayList <> (); - Iterator iterv = source1.V().has("aai-node-type",nType); - while (iterv.hasNext()) { - // We put the nodes into an ArrayList because the graph.query iterator can time out - tmpList.add(iterv.next()); - } - - Iterator iter = tmpList.iterator(); - while (iter.hasNext()) { - try { - thisNtCount++; - if( thisNtCount == lastShownForNt + 250 ){ - lastShownForNt = thisNtCount; - LOGGER.debug("count for " + nType + " so far = " + thisNtCount ); - } - Vertex thisVtx = iter.next(); - if( windowStartTime > 0 ){ - // We only want nodes that are created after a passed-in timestamp - Object objTimeStamp = thisVtx.property("aai-created-ts").orElse(null); - if( objTimeStamp != null ){ - long thisNodeCreateTime = (long)objTimeStamp; - if( thisNodeCreateTime < windowStartTime ){ - // It is NOT in our window, so we can pass over it - continue; - } - } - } - - String thisVid = thisVtx.id().toString(); - if (processedVertices.contains(thisVid)) { - LOGGER.debug("skipping already processed vertex: " + thisVid); - continue; - } - totalNodeCount++; - List secondGetList = new ArrayList <> (); - // ----------------------------------------------------------------------- - // For each vertex of this nodeType, we want to: - // a) make sure that it can be retrieved using it's AAI defined key - // b) make sure that it is not a duplicate - // ----------------------------------------------------------------------- - - // For this instance of this nodeType, get the key properties - HashMap propHashWithKeys = new HashMap<>(); - Iterator keyPropI = keyProps.iterator(); - while (keyPropI.hasNext()) { - String propName = keyPropI.next(); - String propVal = ""; - //delete an already deleted vertex - Object obj = thisVtx.property(propName).orElse(null); - if (obj != null) { - propVal = obj.toString(); - } - propHashWithKeys.put(propName, propVal); - } - try { - // If this node is dependent on another for uniqueness, then do the query from that parent node - // Note - all of our nodes that are dependent on others for uniqueness are - // "children" of that node. - boolean depNodeOk = true; - if( depNodeTypes.isEmpty() ){ - // This kind of node is not dependent on any other. - // Make sure we can get it back using it's key properties and that we only get one. - secondGetList = getNodeJustUsingKeyParams( TRANSID, FROMAPPID, source1, nType, - propHashWithKeys, version ); - } - else { - // This kind of node is dependent on another for uniqueness. - // Start at it's parent (the dependent vertex) and make sure we can get it - // back using it's key properties and that we only get one. - Iterator vertI2 = source1.V(thisVtx).union(__.inE().has(EdgeProperty.CONTAINS.toString(), AAIDirection.OUT.toString()).outV(), __.outE().has(EdgeProperty.CONTAINS.toString(), AAIDirection.IN.toString()).inV()); - Vertex parentVtx = null; - int pCount = 0; - while( vertI2 != null && vertI2.hasNext() ){ - parentVtx = vertI2.next(); - pCount++; - } - if( pCount <= 0 ){ - - - //List vertI2 = g.traversal().V(thisVtx).union(__.outE().has("isParent-REV",true).outV(),__.inE().has("isParent",true).inV()).toList(); - //if( vertI2.isEmpty()){ - - // It's Missing it's dependent/parent node - depNodeOk = false; - boolean zeroEdges = false; - try { - Iterator tmpEdgeIter = thisVtx.edges(Direction.BOTH); - int edgeCount = 0; - while( tmpEdgeIter.hasNext() ){ - edgeCount++; - tmpEdgeIter.next(); - } - if( edgeCount == 0 ){ - zeroEdges = true; - } - } catch (Exception ex) { - LOGGER.warn("WARNING from inside the for-each-vid-loop orphan-edges-check ", ex); - } - - if (deleteCandidateList.contains(thisVid)) { - boolean okFlag = true; - try { - processedVertices.add(thisVtx.id().toString()); - thisVtx.remove(); - deleteCount++; - thisNtDeleteCount++; - } catch (Exception e) { - okFlag = false; - LOGGER.error("ERROR trying to delete missing-dep-node VID = " + thisVid, e); - } - if (okFlag) { - LOGGER.info(" DELETED missing-dep-node VID = " + thisVid); - } - } else { - // We count nodes missing their depNodes two ways - the first if it has - // at least some edges, and the second if it has zero edges. Either - // way, they are effectively orphaned. - // NOTE - Only nodes that have dependent nodes are ever considered "orphaned". - if( zeroEdges ){ - missingDepNodeHash.put(thisVid, thisVtx); - } - else { - orphanNodeHash.put(thisVid, thisVtx); - } - } - } - else if ( pCount > 1 ){ - // Not sure how this could happen? Should we do something here? - depNodeOk = false; - } - else { - // We found the parent - so use it to do the second-look. - // NOTE --- We're just going to do the same check from the other direction - because - // there could be duplicates or the pointer going the other way could be broken - ArrayList tmpListSec = new ArrayList <> (); - - tmpListSec = getConnectedChildrenOfOneType( source1, parentVtx, nType ) ; - Iterator vIter = tmpListSec.iterator(); - while (vIter.hasNext()) { - Vertex tmpV = vIter.next(); - if( vertexHasTheseKeys(tmpV, propHashWithKeys) ){ - secondGetList.add(tmpV); - } - } - } - } - - if( depNodeOk && (secondGetList == null || secondGetList.size() == 0) ){ - // We could not get the node back using it's own key info. - // So, it's a PHANTOM - if (deleteCandidateList.contains(thisVid)) { - boolean okFlag = true; - try { - thisVtx.remove(); - deleteCount++; - thisNtDeleteCount++; - } catch (Exception e) { - okFlag = false; - LOGGER.error("ERROR trying to delete phantom VID = " + thisVid, e); - } - if (okFlag) { - LOGGER.info(" DELETED VID = " + thisVid); - } - } else { - ghostNodeHash.put(thisVid, thisVtx); - } - } - else if( (secondGetList.size() > 1) && depNodeOk && !dupeCheckOff ){ - // Found some DUPLICATES - need to process them - LOGGER.info(" - now check Dupes for this guy - "); - List tmpDupeGroups = checkAndProcessDupes( - TRANSID, FROMAPPID, g, source1, version, - nType, secondGetList, dupeFixOn, - deleteCandidateList, singleCommits, dupeGroups, loader); - Iterator dIter = tmpDupeGroups.iterator(); - while (dIter.hasNext()) { - // Add in any newly found dupes to our running list - String tmpGrp = dIter.next(); - LOGGER.info("Found set of dupes: [" + tmpGrp + "]"); - dupeGroups.add(tmpGrp); - } - } - } - catch (AAIException e1) { - LOGGER.warn(" For nodeType = " + nType + " Caught exception", e1); - errArr.add(e1.getErrorObject().toString()); - } - catch (Exception e2) { - LOGGER.warn(" For nodeType = " + nType - + " Caught exception", e2); - errArr.add(e2.getMessage()); - } - }// try block to enclose looping of a single vertex - catch (Exception exx) { - LOGGER.warn("WARNING from inside the while-verts-loop ", exx); - } - - } // while loop for each record of a nodeType - - if ( (thisNtDeleteCount > 0) && singleCommits ) { - // NOTE - the singleCommits option is not used in normal processing - g.tx().commit(); - g = AAIGraph.getInstance().getGraph().newTransaction(); - - } - thisNtDeleteCount = 0; - LOGGER.info( " Processed " + thisNtCount + " records for [" + nType + "], " + totalNodeCount + " total overall. " ); - - }// While-loop for each node type - }// end of check to make sure we weren't only supposed to do edges - - - if( !skipEdgeCheckFlag ){ - // -------------------------------------------------------------------------------------- - // Now, we're going to look for one-armed-edges. Ie. an edge that - // should have - // been deleted (because a vertex on one side was deleted) but - // somehow was not deleted. - // So the one end of it points to a vertexId -- but that vertex is - // empty. - // -------------------------------------------------------------------------------------- - - // To do some strange checking - we need a second graph object - LOGGER.debug(" ---- DEBUG --- about to open a SECOND graph (takes a little while)--------\n"); - // Note - graph2 just reads - but we want it to use a fresh connection to - // the database, so we are NOT using the CACHED DB CONFIG here. - graph2 = TitanFactory.open(AAIConstants.REALTIME_DB_CONFIG); - if (graph2 == null) { - String emsg = "null graph2 object in DataGrooming\n"; - throw new AAIException("AAI_6101", emsg); - } else { - LOGGER.debug("Got the graph2 object... \n"); - } - g2 = graph2.newTransaction(); - if (g2 == null) { - String emsg = "null graphTransaction2 object in DataGrooming\n"; - throw new AAIException("AAI_6101", emsg); - } - - ArrayList vertList = new ArrayList<>(); - Iterator vItor3 = g.traversal().V(); - // Gotta hold these in a List - or else HBase times out as you cycle - // through these - while (vItor3.hasNext()) { - Vertex v = vItor3.next(); - vertList.add(v); - } - int counter = 0; - int lastShown = 0; - Iterator vItor2 = vertList.iterator(); - LOGGER.info(" Checking for bad edges --- "); - - while (vItor2.hasNext()) { - Vertex v = null; - try { - try { - v = vItor2.next(); - } catch (Exception vex) { - LOGGER.warn(">>> WARNING trying to get next vertex on the vItor2 "); - continue; - } - - counter++; - String thisVertId = ""; - try { - thisVertId = v.id().toString(); - } catch (Exception ev) { - LOGGER.warn("WARNING when doing getId() on a vertex from our vertex list. "); - continue; - } - if (ghostNodeHash.containsKey(thisVertId)) { - // This is a phantom node, so don't try to use it - LOGGER.info(" >> Skipping edge check for edges from vertexId = " - + thisVertId - + ", since that guy is a Phantom Node"); - continue; - } - - if( windowStartTime > 0 ){ - // We only want to look at nodes that are created after a passed-in timestamp - Object objTimeStamp = v.property("aai-created-ts").orElse(null); - if( objTimeStamp != null ){ - long thisNodeCreateTime = (long)objTimeStamp; - if( thisNodeCreateTime < windowStartTime ){ - // It is NOT in our window, so we can pass over it - continue; - } - } - } - - if (counter == lastShown + 250) { - lastShown = counter; - LOGGER.info("... Checking edges for vertex # " - + counter); - } - Iterator eItor = v.edges(Direction.BOTH); - while (eItor.hasNext()) { - Edge e = null; - Vertex vIn = null; - Vertex vOut = null; - try { - e = eItor.next(); - } catch (Exception iex) { - LOGGER.warn(">>> WARNING trying to get next edge on the eItor ", iex); - continue; - } - - try { - vIn = e.inVertex(); - } catch (Exception err) { - LOGGER.warn(">>> WARNING trying to get edge's In-vertex ", err); - } - String vNtI = ""; - String vIdI = ""; - Vertex ghost2 = null; - - Boolean keysMissing = true; - Boolean cantGetUsingVid = false; - if (vIn != null) { - try { - Object ob = vIn.property("aai-node-type").orElse(null); - if (ob != null) { - vNtI = ob.toString(); - keysMissing = anyKeyFieldsMissing(vNtI, vIn, loader); - } - ob = vIn.id(); - long vIdLong = 0L; - if (ob != null) { - vIdI = ob.toString(); - vIdLong = Long.parseLong(vIdI); - } - - if( ! ghost2CheckOff ){ - Vertex connectedVert = g2.traversal().V(vIdLong).next(); - if( connectedVert == null ) { - LOGGER.warn( "GHOST2 -- got NULL when doing getVertex for vid = " + vIdLong); - cantGetUsingVid = true; - - // If we can NOT get this ghost with the SECOND graph-object, - // it is still a ghost since even though we can get data about it using the FIRST graph - // object. - try { - ghost2 = g.traversal().V(vIdLong).next(); - } - catch( Exception ex){ - LOGGER.warn( "GHOST2 -- Could not get the ghost info for a bad edge for vtxId = " + vIdLong, ex); - } - if( ghost2 != null ){ - ghostNodeHash.put(vIdI, ghost2); - } - } - }// end of the ghost2 checking - } - catch (Exception err) { - LOGGER.warn(">>> WARNING trying to get edge's In-vertex props ", err); - } - } - if (keysMissing || vIn == null || vNtI.equals("") - || cantGetUsingVid) { - // this is a bad edge because it points to a vertex - // that isn't there anymore or is corrupted - String thisEid = e.id().toString(); - if (deleteCandidateList.contains(thisEid) || deleteCandidateList.contains(vIdI)) { - boolean okFlag = true; - if (!vIdI.equals("")) { - // try to get rid of the corrupted vertex - try { - if( (ghost2 != null) && ghost2FixOn ){ - ghost2.remove(); - } - else { - vIn.remove(); - } - if (singleCommits) { - // NOTE - the singleCommits option is not used in normal processing - g.tx().commit(); - g = AAIGraph.getInstance().getGraph().newTransaction(); - } - deleteCount++; - } catch (Exception e1) { - okFlag = false; - LOGGER.warn("WARNING when trying to delete bad-edge-connected VERTEX VID = " - + vIdI, e1); - } - if (okFlag) { - LOGGER.info(" DELETED vertex from bad edge = " - + vIdI); - } - } else { - // remove the edge if we couldn't get the - // vertex - try { - e.remove(); - if (singleCommits) { - // NOTE - the singleCommits option is not used in normal processing - g.tx().commit(); - g = AAIGraph.getInstance().getGraph().newTransaction(); - } - deleteCount++; - } catch (Exception ex) { - // NOTE - often, the exception is just - // that this edge has already been - // removed - okFlag = false; - LOGGER.warn("WARNING when trying to delete edge = " - + thisEid); - } - if (okFlag) { - LOGGER.info(" DELETED edge = " + thisEid); - } - } - } else { - oneArmedEdgeHash.put(thisEid, e); - if ((vIn != null) && (vIn.id() != null)) { - emptyVertexHash.put(thisEid, vIn.id() - .toString()); - } - } - } - - try { - vOut = e.outVertex(); - } catch (Exception err) { - LOGGER.warn(">>> WARNING trying to get edge's Out-vertex "); - } - String vNtO = ""; - String vIdO = ""; - ghost2 = null; - keysMissing = true; - cantGetUsingVid = false; - if (vOut != null) { - try { - Object ob = vOut.property("aai-node-type").orElse(null); - if (ob != null) { - vNtO = ob.toString(); - keysMissing = anyKeyFieldsMissing(vNtO, - vOut, loader); - } - ob = vOut.id(); - long vIdLong = 0L; - if (ob != null) { - vIdO = ob.toString(); - vIdLong = Long.parseLong(vIdO); - } - - if( ! ghost2CheckOff ){ - Vertex connectedVert = g2.traversal().V(vIdLong).next(); - if( connectedVert == null ) { - cantGetUsingVid = true; - LOGGER.info( "GHOST2 -- got NULL when doing getVertex for vid = " + vIdLong); - // If we can get this ghost with the other graph-object, then get it -- it's still a ghost - try { - ghost2 = g.traversal().V(vIdLong).next(); - } - catch( Exception ex){ - LOGGER.warn( "GHOST2 -- Could not get the ghost info for a bad edge for vtxId = " + vIdLong, ex); - } - if( ghost2 != null ){ - ghostNodeHash.put(vIdO, ghost2); - } - } - } - } catch (Exception err) { - LOGGER.warn(">>> WARNING trying to get edge's Out-vertex props ", err); - } - } - if (keysMissing || vOut == null || vNtO.equals("") - || cantGetUsingVid) { - // this is a bad edge because it points to a vertex - // that isn't there anymore - String thisEid = e.id().toString(); - if (deleteCandidateList.contains(thisEid) || deleteCandidateList.contains(vIdO)) { - boolean okFlag = true; - if (!vIdO.equals("")) { - // try to get rid of the corrupted vertex - try { - if( (ghost2 != null) && ghost2FixOn ){ - ghost2.remove(); - } - else if (vOut != null) { - vOut.remove(); - } - if (singleCommits) { - // NOTE - the singleCommits option is not used in normal processing - g.tx().commit(); - g = AAIGraph.getInstance().getGraph().newTransaction(); - } - deleteCount++; - } catch (Exception e1) { - okFlag = false; - LOGGER.warn("WARNING when trying to delete bad-edge-connected VID = " - + vIdO, e1); - } - if (okFlag) { - LOGGER.info(" DELETED vertex from bad edge = " - + vIdO); - } - } else { - // remove the edge if we couldn't get the - // vertex - try { - e.remove(); - if (singleCommits) { - // NOTE - the singleCommits option is not used in normal processing - g.tx().commit(); - g = AAIGraph.getInstance().getGraph().newTransaction(); - } - deleteCount++; - } catch (Exception ex) { - // NOTE - often, the exception is just - // that this edge has already been - // removed - okFlag = false; - LOGGER.warn("WARNING when trying to delete edge = " - + thisEid, ex); - } - if (okFlag) { - LOGGER.info(" DELETED edge = " + thisEid); - } - } - } else { - oneArmedEdgeHash.put(thisEid, e); - if ((vOut != null) && (vOut.id() != null)) { - emptyVertexHash.put(thisEid, vOut.id() - .toString()); - } - } - } - }// End of while-edges-loop - } catch (Exception exx) { - LOGGER.warn("WARNING from in the while-verts-loop ", exx); - } - }// End of while-vertices-loop (the edge-checking) - } // end of -- if we're not skipping the edge-checking - - - deleteCount = deleteCount + dupeGrpsDeleted; - if (!singleCommits && deleteCount > 0) { - try { - LOGGER.info("About to do the commit for " - + deleteCount + " removes. "); - executeFinalCommit = true; - LOGGER.info("Commit was successful "); - } catch (Exception excom) { - LOGGER.error(" >>>> ERROR <<<< Could not commit changes. ", excom); - deleteCount = 0; - } - } - - int ghostNodeCount = ghostNodeHash.size(); - int orphanNodeCount = orphanNodeHash.size(); - int missingDepNodeCount = missingDepNodeHash.size(); - int oneArmedEdgeCount = oneArmedEdgeHash.size(); - int dupeCount = dupeGroups.size(); - - deleteCount = deleteCount + dupeGrpsDeleted; - - bw.write("\n\n ============ Summary ==============\n"); - bw.write("Ran these nodeTypes: " + ntList + "\n\n"); - bw.write("There were this many delete candidates from previous run = " - + deleteCandidateList.size() + "\n"); - if (dontFixOrphansFlag) { - bw.write(" Note - we are not counting orphan nodes since the -dontFixOrphans parameter was used. \n"); - } - bw.write("Deleted this many delete candidates = " + deleteCount - + "\n"); - bw.write("Total number of nodes looked at = " + totalNodeCount - + "\n"); - bw.write("Ghost Nodes identified = " + ghostNodeCount + "\n"); - bw.write("Orphan Nodes identified = " + orphanNodeCount + "\n"); - bw.write("Bad Edges identified = " + oneArmedEdgeCount + "\n"); - bw.write("Missing Dependent Edge (but not orphaned) node count = " - + missingDepNodeCount + "\n"); - bw.write("Duplicate Groups count = " + dupeCount + "\n"); - bw.write("MisMatching Label/aai-node-type count = " - + misMatchedHash.size() + "\n"); - - bw.write("\n ------------- Delete Candidates ---------\n"); - for (Map.Entry entry : ghostNodeHash - .entrySet()) { - String vid = entry.getKey(); - bw.write("DeleteCandidate: Phantom Vid = [" + vid + "]\n"); - cleanupCandidateCount++; - } - for (Map.Entry entry : orphanNodeHash - .entrySet()) { - String vid = entry.getKey(); - bw.write("DeleteCandidate: OrphanDepNode Vid = [" + vid + "]\n"); - if (!dontFixOrphansFlag) { - cleanupCandidateCount++; - } - } - for (Map.Entry entry : oneArmedEdgeHash.entrySet()) { - String eid = entry.getKey(); - bw.write("DeleteCandidate: Bad EDGE Edge-id = [" + eid + "]\n"); - cleanupCandidateCount++; - } - for (Map.Entry entry : missingDepNodeHash - .entrySet()) { - String vid = entry.getKey(); - bw.write("DeleteCandidate: (maybe) missingDepNode Vid = [" - + vid + "]\n"); - cleanupCandidateCount++; - } - bw.write("\n-- NOTE - To see DeleteCandidates for Duplicates, you need to look in the Duplicates Detail section below.\n"); - - bw.write("\n ------------- GHOST NODES - detail "); - for (Map.Entry entry : ghostNodeHash - .entrySet()) { - try { - String vid = entry.getKey(); - bw.write("\n ==> Phantom Vid = " + vid + "\n"); - ArrayList retArr = showPropertiesForNode( - TRANSID, FROMAPPID, entry.getValue()); - for (String info : retArr) { - bw.write(info + "\n"); - } - - retArr = showAllEdgesForNode(TRANSID, FROMAPPID, - entry.getValue()); - for (String info : retArr) { - bw.write(info + "\n"); - } - } catch (Exception dex) { - LOGGER.error("error trying to print detail info for a ghost-node: ", dex); - } - } - - bw.write("\n ------------- Missing Dependent Edge ORPHAN NODES - detail: "); - for (Map.Entry entry : orphanNodeHash - .entrySet()) { - try { - String vid = entry.getKey(); - bw.write("\n> Orphan Node Vid = " + vid + "\n"); - ArrayList retArr = showPropertiesForNode( - TRANSID, FROMAPPID, entry.getValue()); - for (String info : retArr) { - bw.write(info + "\n"); - } - - retArr = showAllEdgesForNode(TRANSID, FROMAPPID, - entry.getValue()); - for (String info : retArr) { - bw.write(info + "\n"); - } - } catch (Exception dex) { - LOGGER.error("error trying to print detail info for a Orphan Node /missing dependent edge", dex); - } - } - - bw.write("\n ------------- Missing Dependent Edge (but not orphan) NODES: "); - for (Map.Entry entry : missingDepNodeHash - .entrySet()) { - try { - String vid = entry.getKey(); - bw.write("\n> Missing edge to Dependent Node (but has edges) Vid = " - + vid + "\n"); - ArrayList retArr = showPropertiesForNode( - TRANSID, FROMAPPID, entry.getValue()); - for (String info : retArr) { - bw.write(info + "\n"); - } - - retArr = showAllEdgesForNode(TRANSID, FROMAPPID, - entry.getValue()); - for (String info : retArr) { - bw.write(info + "\n"); - } - } catch (Exception dex) { - LOGGER.error("error trying to print detail info for a node missing its dependent edge but not an orphan", dex); - } - } - - bw.write("\n ------------- EDGES pointing to empty/bad vertices: "); - for (Map.Entry entry : oneArmedEdgeHash.entrySet()) { - try { - String eid = entry.getKey(); - Edge thisE = entry.getValue(); - String badVid = emptyVertexHash.get(eid); - bw.write("\n> Edge pointing to bad vertex (Vid = " - + badVid + ") EdgeId = " + eid + "\n"); - bw.write("Label: [" + thisE.label() + "]\n"); - Iterator> pI = thisE.properties(); - while (pI.hasNext()) { - Property propKey = pI.next(); - bw.write("Prop: [" + propKey + "], val = [" - + propKey.value() + "]\n"); - } - } catch (Exception pex) { - LOGGER.error("error trying to print empty/bad vertex data: ", pex); - } - } - - bw.write("\n ------------- Duplicates: "); - Iterator dupeIter = dupeGroups.iterator(); - int dupeSetCounter = 0; - while (dupeIter.hasNext()) { - dupeSetCounter++; - String dset = (String) dupeIter.next(); - - bw.write("\n --- Duplicate Group # " + dupeSetCounter - + " Detail -----------\n"); - try { - // We expect each line to have at least two vid's, followed - // by the preferred one to KEEP - String[] dupeArr = dset.split("\\|"); - ArrayList idArr = new ArrayList<>(); - int lastIndex = dupeArr.length - 1; - for (int i = 0; i <= lastIndex; i++) { - if (i < lastIndex) { - // This is not the last entry, it is one of the - // dupes, so we want to show all its info - bw.write(" >> Duplicate Group # " - + dupeSetCounter + " Node # " + i - + " ----\n"); - String vidString = dupeArr[i]; - idArr.add(vidString); - long longVertId = Long.parseLong(vidString); - Iterator vtxIterator = g.vertices(longVertId); - Vertex vtx = null; - if (vtxIterator.hasNext()) { - vtx = vtxIterator.next(); - } - ArrayList retArr = showPropertiesForNode(TRANSID, FROMAPPID, vtx); - for (String info : retArr) { - bw.write(info + "\n"); - } - - retArr = showAllEdgesForNode(TRANSID, - FROMAPPID, vtx); - for (String info : retArr) { - bw.write(info + "\n"); - } - } else { - // This is the last entry which should tell us if we - // have a preferred keeper - String prefString = dupeArr[i]; - if (prefString.equals("KeepVid=UNDETERMINED")) { - bw.write("\n For this group of duplicates, could not tell which one to keep.\n"); - bw.write(" >>> This group needs to be taken care of with a manual/forced-delete.\n"); - } else { - // If we know which to keep, then the prefString - // should look like, "KeepVid=12345" - String[] prefArr = prefString.split("="); - if (prefArr.length != 2 - || (!prefArr[0].equals("KeepVid"))) { - throw new Exception("Bad format. Expecting KeepVid=999999"); - } else { - String keepVidStr = prefArr[1]; - if (idArr.contains(keepVidStr)) { - bw.write("\n The vertex we want to KEEP has vertexId = " - + keepVidStr); - bw.write("\n The others become delete candidates: \n"); - idArr.remove(keepVidStr); - for (int x = 0; x < idArr.size(); x++) { - cleanupCandidateCount++; - bw.write("DeleteCandidate: Duplicate Vid = [" - + idArr.get(x) + "]\n"); - } - } else { - throw new Exception("ERROR - Vertex Id to keep not found in list of dupes. dset = [" - + dset + "]"); - } - } - }// else we know which one to keep - }// else last entry - }// for each vertex in a group - } catch (Exception dex) { - LOGGER.error("error trying to print duplicate vertex data", dex); - } - - }// while - work on each group of dupes - - bw.write("\n ------------- Mis-matched Label/aai-node-type Nodes: \n "); - for (Map.Entry entry : misMatchedHash.entrySet()) { - String msg = entry.getValue(); - bw.write("MixedMsg = " + msg + "\n"); - } - - bw.write("\n ------------- Got these errors while processing: \n"); - Iterator errIter = errArr.iterator(); - while (errIter.hasNext()) { - String line = (String) errIter.next(); - bw.write(line + "\n"); - } - - bw.close(); - - LOGGER.info("\n ------------- Done doing all the checks ------------ "); - LOGGER.info("Output will be written to " + fullOutputFileName); - - if (cleanupCandidateCount > 0) { - // Technically, this is not an error -- but we're throwing this - // error so that hopefully a - // monitoring system will pick it up and do something with it. - throw new AAIException("AAI_6123", "See file: [" + fullOutputFileName - + "] and investigate delete candidates. "); - } - } catch (AAIException e) { - LOGGER.error("Caught AAIException while grooming data", e); - ErrorLogHelper.logException(e); - } catch (Exception ex) { - LOGGER.error("Caught exception while grooming data", ex); - ErrorLogHelper.logError("AAI_6128", ex.getMessage() + ", resolve and rerun dataGrooming"); - } finally { - - if (bw != null) { - try { - bw.close(); - } catch (IOException iox) { - LOGGER.warn("Got an IOException trying to close bufferedWriter() \n", iox); - } - } - - if (g != null && g.tx().isOpen()) { - // Any changes that worked correctly should have already done - // their commits. - try { - if (executeFinalCommit) { - g.tx().commit(); - } - g.tx().rollback(); - } catch (Exception ex) { - // Don't throw anything because Titan sometimes is just saying that the graph is already closed - LOGGER.warn("WARNING from final graphTransaction.rollback()", ex); - } - } - - if (g2 != null && g2.tx().isOpen()) { - // Any changes that worked correctly should have already done - // their commits. - try { - g2.tx().rollback(); - } catch (Exception ex) { - // Don't throw anything because Titan sometimes is just saying that the graph is already closed - LOGGER.warn("WARNING from final graphTransaction2.rollback()", ex); - } - } - - if( finalShutdownFlag ){ - try { - if( graph != null && graph.isOpen() ){ - graph.tx().close(); - graph.close(); - } - } catch (Exception ex) { - // Don't throw anything because Titan sometimes is just saying that the graph is already closed{ - LOGGER.warn("WARNING from final graph.shutdown()", ex); - } - - try { - if( graph2 != null && graph2.isOpen() ){ - graph2.tx().close(); - graph2.close(); - } - } catch (Exception ex) { - // Don't throw anything because Titan sometimes is just saying that the graph is already closed{ - LOGGER.warn("WARNING from final graph2.shutdown()", ex); - } - } - - } - - return cleanupCandidateCount; - - }// end of doTheGrooming() - - - /** - * Vertex has these keys. - * - * @param tmpV the tmp V - * @param propHashWithKeys the prop hash with keys - * @return the boolean - */ - private static Boolean vertexHasTheseKeys( Vertex tmpV, HashMap propHashWithKeys) { - Iterator it = propHashWithKeys.entrySet().iterator(); - while( it.hasNext() ){ - String propName = ""; - String propVal = ""; - Map.Entry propEntry = (Map.Entry)it.next(); - Object propNameObj = propEntry.getKey(); - if( propNameObj != null ){ - propName = propNameObj.toString(); - } - Object propValObj = propEntry.getValue(); - if( propValObj != null ){ - propVal = propValObj.toString(); - } - Object checkValObj = tmpV.property(propName).orElse(null); - if( checkValObj == null ) { - return false; - } - else if( !propVal.equals(checkValObj.toString()) ){ - return false; - } - } - return true; - } - - - /** - * Any key fields missing. - * - * @param nType the n type - * @param v the v - * @return the boolean - */ - private static Boolean anyKeyFieldsMissing(String nType, Vertex v, Loader loader) { - - try { - Introspector obj = null; - try { - obj = loader.introspectorFromName(nType); - } catch (AAIUnknownObjectException e) { - // They gave us a non-empty nodeType but our NodeKeyProps does - // not have data for it. Since we do not know what the - // key params are for this type of node, we will just - // return "false". - String emsg = " -- WARNING -- Unrecognized nodeType: [" + nType - + "]. We cannot determine required keys for this nType. "; - // NOTE - this will be caught below and a "false" returned - throw new AAIException("AAI_6121", emsg); - } - - // Determine what the key fields are for this nodeType - Collection keyPropNamesColl = obj.getKeys(); - Iterator keyPropI = keyPropNamesColl.iterator(); - while (keyPropI.hasNext()) { - String propName = keyPropI.next(); - Object ob = v.property(propName).orElse(null); - if (ob == null || ob.toString().equals("")) { - // It is missing a key property - return true; - } - } - } catch (AAIException e) { - // Something was wrong -- but since we weren't able to check - // the keys, we will not declare that it is missing keys. - return false; - } - return false; - } - - - /** - * Gets the delete list. - * - * @param targetDir the target dir - * @param fileName the file name - * @param edgesOnlyFlag the edges only flag - * @param dontFixOrphans the dont fix orphans - * @param dupeFixOn the dupe fix on - * @return the delete list - * @throws AAIException the AAI exception - */ - private static Set getDeleteList(String targetDir, - String fileName, Boolean edgesOnlyFlag, Boolean dontFixOrphans, - Boolean dupeFixOn) throws AAIException { - - // Look in the file for lines formated like we expect - pull out any - // Vertex Id's to delete on this run - Set delList = new LinkedHashSet<>(); - String fullFileName = targetDir + AAIConstants.AAI_FILESEP + fileName; - - try(BufferedReader br = new BufferedReader(new FileReader(fullFileName))) { - String line = br.readLine(); - while (line != null) { - if (!"".equals(line) && line.startsWith("DeleteCandidate")) { - if (edgesOnlyFlag && (!line.contains("Bad Edge"))) { - // We're not going to process edge guys - } else if (dontFixOrphans && line.contains("Orphan")) { - // We're not going to process orphans - } else if (!dupeFixOn && line.contains("Duplicate")) { - // We're not going to process Duplicates - } else { - int begIndex = line.indexOf("id = "); - int endIndex = line.indexOf("]"); - String vidVal = line.substring(begIndex + 6, endIndex); - delList.add(vidVal); - } - } - line = br.readLine(); - } - br.close(); - } catch (IOException e) { - throw new AAIException("AAI_6124", e, "Could not open input-file [" + fullFileName - + "], exception= " + e.getMessage()); - } - - return delList; - - }// end of getDeleteList - - /** - * Gets the preferred dupe. - * - * @param transId the trans id - * @param fromAppId the from app id - * @param g the g - * @param dupeVertexList the dupe vertex list - * @param ver the ver - * @return Vertex - * @throws AAIException the AAI exception - */ - public static Vertex getPreferredDupe(String transId, - String fromAppId, GraphTraversalSource g, - ArrayList dupeVertexList, String ver, Loader loader) - throws AAIException { - - // This method assumes that it is being passed a List of vertex objects - // which - // violate our uniqueness constraints. - - Vertex nullVtx = null; - - if (dupeVertexList == null) { - return nullVtx; - } - int listSize = dupeVertexList.size(); - if (listSize == 0) { - return nullVtx; - } - if (listSize == 1) { - return (dupeVertexList.get(0)); - } - - Vertex vtxPreferred = null; - Vertex currentFaveVtx = dupeVertexList.get(0); - for (int i = 1; i < listSize; i++) { - Vertex vtxB = dupeVertexList.get(i); - vtxPreferred = pickOneOfTwoDupes(transId, fromAppId, g, - currentFaveVtx, vtxB, ver, loader); - if (vtxPreferred == null) { - // We couldn't choose one - return nullVtx; - } else { - currentFaveVtx = vtxPreferred; - } - } - - return (currentFaveVtx); - - } // end of getPreferredDupe() - - /** - * Pick one of two dupes. - * - * @param transId the trans id - * @param fromAppId the from app id - * @param g the g - * @param vtxA the vtx A - * @param vtxB the vtx B - * @param ver the ver - * @return Vertex - * @throws AAIException the AAI exception - */ - public static Vertex pickOneOfTwoDupes(String transId, - String fromAppId, GraphTraversalSource g, Vertex vtxA, - Vertex vtxB, String ver, Loader loader) throws AAIException { - - Vertex nullVtx = null; - Vertex preferredVtx = null; - - Long vidA = new Long(vtxA.id().toString()); - Long vidB = new Long(vtxB.id().toString()); - - String vtxANodeType = ""; - String vtxBNodeType = ""; - Object objType = vtxA.property("aai-node-type").orElse(null); - if (objType != null) { - vtxANodeType = objType.toString(); - } - objType = vtxB.property("aai-node-type").orElse(null); - if (objType != null) { - vtxBNodeType = objType.toString(); - } - - if (vtxANodeType.equals("") || (!vtxANodeType.equals(vtxBNodeType))) { - // Either they're not really dupes or there's some bad data - so - // don't pick one - return nullVtx; - } - - // Check that node A and B both have the same key values (or else they - // are not dupes) - // (We'll check dep-node later) - // Determine what the key fields are for this nodeType - Collection keyProps = new ArrayList <>(); - try { - keyProps = loader.introspectorFromName(vtxANodeType).getKeys(); - } catch (AAIUnknownObjectException e) { - LOGGER.warn("Required property not found", e); - throw new AAIException("AAI_6105", "Required Property name(s) not found for nodeType = " + vtxANodeType + ")"); - } - - Iterator keyPropI = keyProps.iterator(); - while (keyPropI.hasNext()) { - String propName = keyPropI.next(); - String vtxAKeyPropVal = ""; - objType = vtxA.property(propName).orElse(null); - if (objType != null) { - vtxAKeyPropVal = objType.toString(); - } - String vtxBKeyPropVal = ""; - objType = vtxB.property(propName).orElse(null); - if (objType != null) { - vtxBKeyPropVal = objType.toString(); - } - - if (vtxAKeyPropVal.equals("") - || (!vtxAKeyPropVal.equals(vtxBKeyPropVal))) { - // Either they're not really dupes or they are missing some key - // data - so don't pick one - return nullVtx; - } - } - - // Collect the vid's and aai-node-types of the vertices that each vertex - // (A and B) is connected to. - ArrayList vtxIdsConn2A = new ArrayList<>(); - ArrayList vtxIdsConn2B = new ArrayList<>(); - HashMap nodeTypesConn2A = new HashMap<>(); - HashMap nodeTypesConn2B = new HashMap<>(); - - ArrayList vertListA = getConnectedNodes( g, vtxA ); - if (vertListA != null) { - Iterator iter = vertListA.iterator(); - while (iter.hasNext()) { - Vertex tvCon = iter.next(); - String conVid = tvCon.id().toString(); - String nt = ""; - objType = tvCon.property("aai-node-type").orElse(null); - if (objType != null) { - nt = objType.toString(); - } - nodeTypesConn2A.put(nt, conVid); - vtxIdsConn2A.add(conVid); - } - } - - ArrayList vertListB = getConnectedNodes( g, vtxB ); - if (vertListB != null) { - Iterator iter = vertListB.iterator(); - while (iter.hasNext()) { - Vertex tvCon = iter.next(); - String conVid = tvCon.id().toString(); - String nt = ""; - objType = tvCon.property("aai-node-type").orElse(null); - if (objType != null) { - nt = objType.toString(); - } - nodeTypesConn2B.put(nt, conVid); - vtxIdsConn2B.add(conVid); - } - } - - // 1 - If this kind of node needs a dependent node for uniqueness, then - // verify that they both nodes - // point to the same dependent node (otherwise they're not really - // duplicates) - // Note - there are sometimes more than one dependent node type since - // one nodeType can be used in - // different ways. But for a particular node, it will only have one - // dependent node that it's - // connected to. - Collection depNodeTypes = loader.introspectorFromName(vtxANodeType).getDependentOn(); - - if (depNodeTypes.isEmpty()) { - // This kind of node is not dependent on any other. That is ok. - } else { - String depNodeVtxId4A = ""; - String depNodeVtxId4B = ""; - Iterator iter = depNodeTypes.iterator(); - while (iter.hasNext()) { - String depNodeType = iter.next(); - if (nodeTypesConn2A.containsKey(depNodeType)) { - // This is the dependent node type that vertex A is using - depNodeVtxId4A = nodeTypesConn2A.get(depNodeType); - } - if (nodeTypesConn2B.containsKey(depNodeType)) { - // This is the dependent node type that vertex B is using - depNodeVtxId4B = nodeTypesConn2B.get(depNodeType); - } - } - if (depNodeVtxId4A.equals("") - || (!depNodeVtxId4A.equals(depNodeVtxId4B))) { - // Either they're not really dupes or there's some bad data - so - // don't pick either one - return nullVtx; - } - } - - if (vtxIdsConn2A.size() == vtxIdsConn2B.size()) { - // 2 - If they both have edges to all the same vertices, then return - // the one with the lower vertexId. - boolean allTheSame = true; - Iterator iter = vtxIdsConn2A.iterator(); - while (iter.hasNext()) { - String vtxIdConn2A = iter.next(); - if (!vtxIdsConn2B.contains(vtxIdConn2A)) { - allTheSame = false; - break; - } - } - - if (allTheSame) { - if (vidA < vidB) { - preferredVtx = vtxA; - } else { - preferredVtx = vtxB; - } - } - } else if (vtxIdsConn2A.size() > vtxIdsConn2B.size()) { - // 3 - VertexA is connected to more things than vtxB. - // We'll pick VtxA if its edges are a superset of vtxB's edges. - boolean missingOne = false; - Iterator iter = vtxIdsConn2B.iterator(); - while (iter.hasNext()) { - String vtxIdConn2B = iter.next(); - if (!vtxIdsConn2A.contains(vtxIdConn2B)) { - missingOne = true; - break; - } - } - if (!missingOne) { - preferredVtx = vtxA; - } - } else if (vtxIdsConn2B.size() > vtxIdsConn2A.size()) { - // 4 - VertexB is connected to more things than vtxA. - // We'll pick VtxB if its edges are a superset of vtxA's edges. - boolean missingOne = false; - Iterator iter = vtxIdsConn2A.iterator(); - while (iter.hasNext()) { - String vtxIdConn2A = iter.next(); - if (!vtxIdsConn2B.contains(vtxIdConn2A)) { - missingOne = true; - break; - } - } - if (!missingOne) { - preferredVtx = vtxB; - } - } else { - preferredVtx = nullVtx; - } - - return (preferredVtx); - - } // end of pickOneOfTwoDupes() - - /** - * Check and process dupes. - * - * @param transId the trans id - * @param fromAppId the from app id - * @param g the g - * @param version the version - * @param nType the n type - * @param passedVertList the passed vert list - * @param dupeFixOn the dupe fix on - * @param deleteCandidateList the delete candidate list - * @param singleCommits the single commits - * @param alreadyFoundDupeGroups the already found dupe groups - * @param dbMaps the db maps - * @return the array list - */ - private static List checkAndProcessDupes(String transId, - String fromAppId, Graph g, GraphTraversalSource source, String version, String nType, - List passedVertList, Boolean dupeFixOn, - Set deleteCandidateList, Boolean singleCommits, - ArrayList alreadyFoundDupeGroups, Loader loader ) { - - ArrayList returnList = new ArrayList<>(); - ArrayList checkVertList = new ArrayList<>(); - ArrayList alreadyFoundDupeVidArr = new ArrayList<>(); - Boolean noFilterList = true; - Iterator afItr = alreadyFoundDupeGroups.iterator(); - while (afItr.hasNext()) { - String dupeGrpStr = afItr.next(); - String[] dupeArr = dupeGrpStr.split("\\|"); - int lastIndex = dupeArr.length - 1; - for (int i = 0; i < lastIndex; i++) { - // Note: we don't want the last one... - String vidString = dupeArr[i]; - alreadyFoundDupeVidArr.add(vidString); - noFilterList = false; - } - } - - // For a given set of Nodes that were found with a set of KEY - // Parameters, (nodeType + key data) we will - // see if we find any duplicate nodes that need to be cleaned up. Note - - // it's legit to have more than one - // node with the same key data if the nodes depend on a parent for - // uniqueness -- as long as the two nodes - // don't hang off the same Parent. - // If we find duplicates, and we can figure out which of each set of - // duplicates is the one that we - // think should be preserved, we will record that. Whether we can tell - // which one should be - // preserved or not, we will return info about any sets of duplicates - // found. - // - // Each element in the returned arrayList might look like this: - // "1234|5678|keepVid=UNDETERMINED" (if there were 2 dupes, and we - // couldn't figure out which one to keep) - // or, "100017|200027|30037|keepVid=30037" (if there were 3 dupes and we - // thought the third one was the one that should survive) - - // Because of the way the calling code loops over stuff, we can get the - // same data multiple times - so we should - // not process any vertices that we've already seen. - - try { - Iterator pItr = passedVertList.iterator(); - while (pItr.hasNext()) { - Vertex tvx = pItr.next(); - String passedId = tvx.id().toString(); - if (noFilterList || !alreadyFoundDupeVidArr.contains(passedId)) { - // We haven't seen this one before - so we should check it. - checkVertList.add(tvx); - } - } - - if (checkVertList.size() < 2) { - // Nothing new to check. - return returnList; - } - - if (loader.introspectorFromName(nType).isTopLevel()) { - // If this was a node that does NOT depend on other nodes for - // uniqueness, and we - // found more than one node using its key -- record the found - // vertices as duplicates. - String dupesStr = ""; - for (int i = 0; i < checkVertList.size(); i++) { - dupesStr = dupesStr - + ((checkVertList.get(i))).id() - .toString() + "|"; - } - if (dupesStr != "") { - Vertex prefV = getPreferredDupe(transId, fromAppId, - source, checkVertList, version, loader); - if (prefV == null) { - // We could not determine which duplicate to keep - dupesStr = dupesStr + "KeepVid=UNDETERMINED"; - returnList.add(dupesStr); - } else { - dupesStr = dupesStr + "KeepVid=" + prefV.id(); - Boolean didRemove = false; - if (dupeFixOn) { - didRemove = deleteNonKeepersIfAppropriate(g, - dupesStr, prefV.id().toString(), - deleteCandidateList, singleCommits); - } - if (didRemove) { - dupeGrpsDeleted++; - } else { - // keep them on our list - returnList.add(dupesStr); - } - } - } - } else { - // More than one node have the same key fields since they may - // depend on a parent node for uniqueness. Since we're finding - // more than one, we want to check to see if any of the - // vertices that have this set of keys (and are the same nodeType) - // are also pointing at the same 'parent' node. - // Note: for a given set of key data, it is possible that there - // could be more than one set of duplicates. - HashMap> vertsGroupedByParentHash = groupVertsByDepNodes( - transId, fromAppId, source, version, nType, - checkVertList, loader); - for (Map.Entry> entry : vertsGroupedByParentHash - .entrySet()) { - ArrayList thisParentsVertList = entry - .getValue(); - if (thisParentsVertList.size() > 1) { - // More than one vertex found with the same key info - // hanging off the same parent/dependent node - String dupesStr = ""; - for (int i = 0; i < thisParentsVertList.size(); i++) { - dupesStr = dupesStr - + ((thisParentsVertList - .get(i))).id() + "|"; - } - if (dupesStr != "") { - Vertex prefV = getPreferredDupe(transId, - fromAppId, source, thisParentsVertList, - version, loader); - - if (prefV == null) { - // We could not determine which duplicate to - // keep - dupesStr = dupesStr + "KeepVid=UNDETERMINED"; - returnList.add(dupesStr); - } else { - Boolean didRemove = false; - dupesStr = dupesStr + "KeepVid=" - + prefV.id().toString(); - if (dupeFixOn) { - didRemove = deleteNonKeepersIfAppropriate( - g, dupesStr, prefV.id() - .toString(), - deleteCandidateList, singleCommits); - } - if (didRemove) { - dupeGrpsDeleted++; - } else { - // keep them on our list - returnList.add(dupesStr); - } - } - } - } - } - } - } catch (Exception e) { - LOGGER.warn(" >>> Threw an error in checkAndProcessDupes - just absorb this error and move on. ", e); - } - - return returnList; - - }// End of checkAndProcessDupes() - - /** - * Group verts by dep nodes. - * - * @param transId the trans id - * @param fromAppId the from app id - * @param g the g - * @param version the version - * @param nType the n type - * @param passedVertList the passed vert list - * @param dbMaps the db maps - * @return the hash map - * @throws AAIException the AAI exception - */ - private static HashMap> groupVertsByDepNodes( - String transId, String fromAppId, GraphTraversalSource g, String version, - String nType, ArrayList passedVertList, Loader loader) - throws AAIException { - // Given a list of Titan Vertices of one nodeType (see AAI-8956), group - // them together by the parent node they depend on. - // Ie. if given a list of ip address nodes (assumed to all have the - // same key info) they might sit under several different parent vertices. - // Under Normal conditions, there would only be one per parent -- but - // we're trying to find duplicates - so we - // allow for the case where more than one is under the same parent node. - - HashMap> retHash = new HashMap>(); - if (loader.introspectorFromName(nType).isTopLevel()) { - // This method really should not have been called if this is not the - // kind of node - // that depends on a parent for uniqueness, so just return the empty - // hash. - return retHash; - } - - // Find out what types of nodes the passed in nodes can depend on - ArrayList depNodeTypeL = new ArrayList<>(); - Collection depNTColl = loader.introspectorFromName(nType).getDependentOn(); - Iterator ntItr = depNTColl.iterator(); - while (ntItr.hasNext()) { - depNodeTypeL.add(ntItr.next()); - } - // For each vertex, we want find its depended-on/parent vertex so we - // can track what other vertexes that are dependent on that same guy. - if (passedVertList != null) { - Iterator iter = passedVertList.iterator(); - while (iter.hasNext()) { - Vertex thisVert = iter.next(); - Vertex tmpParentVtx = getConnectedParent( g, thisVert ); - if( tmpParentVtx != null ) { - String parentNt = null; - Object obj = tmpParentVtx.property("aai-node-type").orElse(null); - if (obj != null) { - parentNt = obj.toString(); - } - if (depNTColl.contains(parentNt)) { - // This must be the parent/dependent node - String parentVid = tmpParentVtx.id().toString(); - if (retHash.containsKey(parentVid)) { - // add this vert to the list for this parent key - retHash.get(parentVid).add(thisVert); - } else { - // This is the first one we found on this parent - ArrayList vList = new ArrayList<>(); - vList.add(thisVert); - retHash.put(parentVid, vList); - } - } - } - } - } - - return retHash; - - }// end of groupVertsByDepNodes() - - /** - * Delete non keepers if appropriate. - * - * @param g the g - * @param dupeInfoString the dupe info string - * @param vidToKeep the vid to keep - * @param deleteCandidateList the delete candidate list - * @param singleCommits the single commits - * @return the boolean - */ - private static Boolean deleteNonKeepersIfAppropriate(Graph g, - String dupeInfoString, String vidToKeep, - Set deleteCandidateList, Boolean singleCommits) { - - Boolean deletedSomething = false; - // This assumes that the dupeInfoString is in the format of - // pipe-delimited vid's followed by - // ie. "3456|9880|keepVid=3456" - if (deleteCandidateList == null || deleteCandidateList.size() == 0) { - // No vid's on the candidate list -- so no deleting will happen on - // this run - return false; - } - - String[] dupeArr = dupeInfoString.split("\\|"); - ArrayList idArr = new ArrayList<>(); - int lastIndex = dupeArr.length - 1; - for (int i = 0; i <= lastIndex; i++) { - if (i < lastIndex) { - // This is not the last entry, it is one of the dupes, - String vidString = dupeArr[i]; - idArr.add(vidString); - } else { - // This is the last entry which should tell us if we have a - // preferred keeper - String prefString = dupeArr[i]; - if (prefString.equals("KeepVid=UNDETERMINED")) { - // They sent us a bad string -- nothing should be deleted if - // no dupe could be tagged as preferred - return false; - } else { - // If we know which to keep, then the prefString should look - // like, "KeepVid=12345" - String[] prefArr = prefString.split("="); - if (prefArr.length != 2 || (!prefArr[0].equals("KeepVid"))) { - LOGGER.error("Bad format. Expecting KeepVid=999999"); - return false; - } else { - String keepVidStr = prefArr[1]; - if (idArr.contains(keepVidStr)) { - idArr.remove(keepVidStr); - - // So now, the idArr should just contain the vid's - // that we want to remove. - for (int x = 0; x < idArr.size(); x++) { - boolean okFlag = true; - String thisVid = idArr.get(x); - if (deleteCandidateList.contains(thisVid)) { - // This vid is a valid delete candidate from - // a prev. run, so we can remove it. - try { - long longVertId = Long - .parseLong(thisVid); - Vertex vtx = g - .traversal().V(longVertId).next(); - vtx.remove(); - if (singleCommits) { - // NOTE - the singleCommits option is not used in normal processing - g.tx().commit(); - g = AAIGraph.getInstance().getGraph().newTransaction(); - } - } catch (Exception e) { - okFlag = false; - LOGGER.error("ERROR trying to delete VID = " + thisVid, e); - } - if (okFlag) { - LOGGER.info(" DELETED VID = " + thisVid); - deletedSomething = true; - } - } - } - } else { - LOGGER.error("ERROR - Vertex Id to keep not found in list of dupes. dupeInfoString = [" - + dupeInfoString + "]"); - return false; - } - } - }// else we know which one to keep - }// else last entry - }// for each vertex in a group - - return deletedSomething; - - }// end of deleteNonKeepersIfAppropriate() - - - /** - * Gets the node just using key params. - * - * @param transId the trans id - * @param fromAppId the from app id - * @param graph the graph - * @param nodeType the node type - * @param keyPropsHash the key props hash - * @param apiVersion the api version - * @return the node just using key params - * @throws AAIException the AAI exception - */ - public static List getNodeJustUsingKeyParams( String transId, String fromAppId, GraphTraversalSource graph, String nodeType, - HashMap keyPropsHash, String apiVersion ) throws AAIException{ - - List retVertList = new ArrayList <> (); - - // We assume that all NodeTypes have at least one key-property defined. - // Note - instead of key-properties (the primary key properties), a user could pass - // alternate-key values if they are defined for the nodeType. - List kName = new ArrayList<>(); - List kVal = new ArrayList<>(); - if( keyPropsHash == null || keyPropsHash.isEmpty() ) { - throw new AAIException("AAI_6120", " NO key properties passed for this getNodeJustUsingKeyParams() request. NodeType = [" + nodeType + "]. "); - } - - int i = -1; - for( Map.Entry entry : keyPropsHash.entrySet() ){ - i++; - kName.add(i, entry.getKey()); - kVal.add(i, entry.getValue()); - } - int topPropIndex = i; - Vertex tiV = null; - String propsAndValuesForMsg = ""; - Iterator verts = null; - - try { - if( topPropIndex == 0 ){ - propsAndValuesForMsg = " (" + kName.get(0) + " = " + kVal.get(0) + ") "; - verts= graph.V().has(kName.get(0),kVal.get(0)).has("aai-node-type",nodeType); - } - else if( topPropIndex == 1 ){ - propsAndValuesForMsg = " (" + kName.get(0) + " = " + kVal.get(0) + ", " - + kName.get(1) + " = " + kVal.get(1) + ") "; - verts = graph.V().has(kName.get(0),kVal.get(0)).has(kName.get(1),kVal.get(1)).has("aai-node-type",nodeType); - } - else if( topPropIndex == 2 ){ - propsAndValuesForMsg = " (" + kName.get(0) + " = " + kVal.get(0) + ", " - + kName.get(1) + " = " + kVal.get(1) + ", " - + kName.get(2) + " = " + kVal.get(2) + ") "; - verts= graph.V().has(kName.get(0),kVal.get(0)).has(kName.get(1),kVal.get(1)).has(kName.get(2),kVal.get(2)).has("aai-node-type",nodeType); - } - else if( topPropIndex == 3 ){ - propsAndValuesForMsg = " (" + kName.get(0) + " = " + kVal.get(0) + ", " - + kName.get(1) + " = " + kVal.get(1) + ", " - + kName.get(2) + " = " + kVal.get(2) + ", " - + kName.get(3) + " = " + kVal.get(3) + ") "; - verts= graph.V().has(kName.get(0),kVal.get(0)).has(kName.get(1),kVal.get(1)).has(kName.get(2),kVal.get(2)).has(kName.get(3),kVal.get(3)).has("aai-node-type",nodeType); - } - else { - throw new AAIException("AAI_6114", " We only support 4 keys per nodeType for now \n"); - } - } - catch( Exception ex ){ - LOGGER.error( " ERROR trying to get node for: [" + propsAndValuesForMsg + "]", ex); - } - - if( verts != null ){ - while( verts.hasNext() ){ - tiV = verts.next(); - retVertList.add(tiV); - } - } - - if( retVertList.size() == 0 ){ - LOGGER.debug("DEBUG No node found for nodeType = [" + nodeType + - "], propsAndVal = " + propsAndValuesForMsg ); - } - - return retVertList; - - }// End of getNodeJustUsingKeyParams() - - /** - * Show all edges for node. - * - * @param transId the trans id - * @param fromAppId the from app id - * @param tVert the t vert - * @return the array list - */ - private static ArrayList showAllEdgesForNode( String transId, String fromAppId, Vertex tVert ){ - - ArrayList retArr = new ArrayList <> (); - Iterator eI = tVert.edges(Direction.IN); - if( ! eI.hasNext() ){ - retArr.add("No IN edges were found for this vertex. "); - } - while( eI.hasNext() ){ - Edge ed = eI.next(); - String lab = ed.label(); - Vertex vtx; - if (tVert.equals(ed.inVertex())) { - vtx = ed.outVertex(); - } else { - vtx = ed.inVertex(); - } - if( vtx == null ){ - retArr.add(" >>> COULD NOT FIND VERTEX on the other side of this edge edgeId = " + ed.id() + " <<< "); - } - else { - String nType = vtx.property("aai-node-type").orElse(null); - String vid = vtx.id().toString(); - retArr.add("Found an IN edge (" + lab + ") to this vertex from a [" + nType + "] node with VtxId = " + vid ); - - } - } - - eI = tVert.edges(Direction.OUT); - if( ! eI.hasNext() ){ - retArr.add("No OUT edges were found for this vertex. "); - } - while( eI.hasNext() ){ - Edge ed = eI.next(); - String lab = ed.label(); - Vertex vtx; - if (tVert.equals(ed.inVertex())) { - vtx = ed.outVertex(); - } else { - vtx = ed.inVertex(); - } - if( vtx == null ){ - retArr.add(" >>> COULD NOT FIND VERTEX on the other side of this edge edgeId = " + ed.id() + " <<< "); - } - else { - String nType = vtx.property("aai-node-type").orElse(null); - String vid = vtx.id().toString(); - retArr.add("Found an OUT edge (" + lab + ") from this vertex to a [" + nType + "] node with VtxId = " + vid ); - } - } - return retArr; - } - - - /** - * Show properties for node. - * - * @param transId the trans id - * @param fromAppId the from app id - * @param tVert the t vert - * @return the array list - */ - private static ArrayList showPropertiesForNode( String transId, String fromAppId, Vertex tVert ){ - - ArrayList retArr = new ArrayList <> (); - if( tVert == null ){ - retArr.add("null Node object passed to showPropertiesForNode()\n"); - } - else { - String nodeType = ""; - Object ob = tVert.property("aai-node-type").orElse(null); - if( ob == null ){ - nodeType = "null"; - } - else{ - nodeType = ob.toString(); - } - - retArr.add(" AAINodeType/VtxID for this Node = [" + nodeType + "/" + tVert.id() + "]"); - retArr.add(" Property Detail: "); - Iterator> pI = tVert.properties(); - while( pI.hasNext() ){ - VertexProperty tp = pI.next(); - Object val = tp.value(); - retArr.add("Prop: [" + tp.key() + "], val = [" + val + "] "); - } - } - return retArr; - } - - - private static ArrayList getConnectedNodes(GraphTraversalSource g, Vertex startVtx ) - throws AAIException { - - ArrayList retArr = new ArrayList <> (); - if( startVtx == null ){ - return retArr; - } - else { - GraphTraversal modPipe = null; - modPipe = g.V(startVtx).both(); - if( modPipe != null && modPipe.hasNext() ){ - while( modPipe.hasNext() ){ - Vertex conVert = modPipe.next(); - retArr.add(conVert); - } - } - } - return retArr; - - }// End of getConnectedNodes() - - - private static ArrayList getConnectedChildrenOfOneType( GraphTraversalSource g, - Vertex startVtx, String childNType ) throws AAIException{ - - ArrayList childList = new ArrayList <> (); - Iterator vertI = g.V(startVtx).union(__.outE().has(EdgeProperty.CONTAINS.toString(), AAIDirection.OUT.toString()).inV(), __.inE().has(EdgeProperty.CONTAINS.toString(), AAIDirection.IN.toString()).outV()); - - Vertex tmpVtx = null; - while( vertI != null && vertI.hasNext() ){ - tmpVtx = vertI.next(); - Object ob = tmpVtx.property("aai-node-type").orElse(null); - if (ob != null) { - String tmpNt = ob.toString(); - if( tmpNt.equals(childNType)){ - childList.add(tmpVtx); - } - } - } - - return childList; - - }// End of getConnectedChildrenOfOneType() - - - private static Vertex getConnectedParent( GraphTraversalSource g, - Vertex startVtx ) throws AAIException{ - - Vertex parentVtx = null; - Iterator vertI = g.V(startVtx).union(__.inE().has(EdgeProperty.CONTAINS.toString(), AAIDirection.OUT.toString()).outV(), __.outE().has(EdgeProperty.CONTAINS.toString(), AAIDirection.IN.toString()).inV()); - - while( vertI != null && vertI.hasNext() ){ - // Note - there better only be one! - parentVtx = vertI.next(); - } - - return parentVtx; - - }// End of getConnectedParent() - - - private static long figureWindowStartTime( int timeWindowMinutes ){ - // Given a window size, calculate what the start-timestamp would be. - - if( timeWindowMinutes <= 0 ){ - // This just means that there is no window... - return 0; - } - long unixTimeNow = System.currentTimeMillis(); - long windowInMillis = timeWindowMinutes * 60L * 1000; - - long startTimeStamp = unixTimeNow - windowInMillis; - - return startTimeStamp; - } // End of figureWindowStartTime() - - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/dbgen/GenTester.java b/aai-core/src/main/java/org/openecomp/aai/dbgen/GenTester.java deleted file mode 100644 index 7847d3d6..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/dbgen/GenTester.java +++ /dev/null @@ -1,143 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.dbgen; - -import com.att.eelf.configuration.Configuration; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.thinkaurelius.titan.core.TitanGraph; -import com.thinkaurelius.titan.core.schema.TitanManagement; -import org.openecomp.aai.dbmap.AAIGraph; -import org.openecomp.aai.logging.ErrorLogHelper; -import org.openecomp.aai.util.AAIConfig; -import org.openecomp.aai.util.AAIConstants; - -import java.util.Properties; - - -public class GenTester { - - private static EELFLogger LOGGER; - - /** - * The main method. - * - * @param args the arguments - */ - public static void main(String[] args) { - - TitanGraph graph = null; - - // Set the logging file properties to be used by EELFManager - Properties props = System.getProperties(); - props.setProperty(Configuration.PROPERTY_LOGGING_FILE_NAME, AAIConstants.AAI_CREATE_DB_SCHEMA_LOGBACK_PROPS); - props.setProperty(Configuration.PROPERTY_LOGGING_FILE_PATH, AAIConstants.AAI_HOME_ETC_APP_PROPERTIES); - LOGGER = EELFManager.getInstance().getLogger(GenTester.class); - boolean addDefaultCR = true; - - try { - AAIConfig.init(); - if (args != null && args.length > 0 ){ - if( "genDbRulesOnly".equals(args[0]) ){ - ErrorLogHelper.logError("AAI_3100", - " This option is no longer supported. What was in DbRules is now derived from the OXM files. "); - return; - } - else if ( "GEN_DB_WITH_NO_SCHEMA".equals(args[0]) ){ - // Note this is done to create an empty DB with no Schema so that - // an HBase copyTable can be used to set up a copy of the db. - String imsg = " ---- NOTE --- about to load a graph without doing any schema processing (takes a little while) -------- "; - System.out.println(imsg); - LOGGER.info(imsg); - graph = AAIGraph.getInstance().getGraph(); - - if( graph == null ){ - ErrorLogHelper.logError("AAI_5102", "Error creating Titan graph."); - return; - } - else { - String amsg = "Successfully loaded a Titan graph without doing any schema work. "; - System.out.println(amsg); - LOGGER.auditEvent(amsg); - return; - } - } else if ("GEN_DB_WITH_NO_DEFAULT_CR".equals(args[0])) { - addDefaultCR = false; - } - else { - ErrorLogHelper.logError("AAI_3000", "Unrecognized argument passed to GenTester.java: [" + args[0] + "]. "); - - String emsg = "Unrecognized argument passed to GenTester.java: [" + args[0] + "]. "; - System.out.println(emsg); - LOGGER.error(emsg); - - emsg = "Either pass no argument for normal processing, or use 'GEN_DB_WITH_NO_SCHEMA'."; - System.out.println(emsg); - LOGGER.error(emsg); - - return; - } - } - - //AAIConfig.init(); - ErrorLogHelper.loadProperties(); - String imsg = " ---- NOTE --- about to open graph (takes a little while)--------;"; - System.out.println(imsg); - LOGGER.info(imsg); - graph = AAIGraph.getInstance().getGraph(); - - if( graph == null ){ - ErrorLogHelper.logError("AAI_5102", "Error creating Titan graph. "); - return; - } - - // Load the propertyKeys, indexes and edge-Labels into the DB - TitanManagement graphMgt = graph.openManagement(); - - imsg = "-- Loading new schema elements into Titan --"; - System.out.println(imsg); - LOGGER.info(imsg); - SchemaGenerator.loadSchemaIntoTitan( graph, graphMgt, addDefaultCR ); - - } catch(Exception ex) { - ErrorLogHelper.logError("AAI_4000", ex.getMessage()); - } - - - if( graph != null ){ - String imsg = "-- graph commit"; - System.out.println(imsg); - LOGGER.info(imsg); - graph.tx().commit(); - - imsg = "-- graph shutdown "; - System.out.println(imsg); - LOGGER.info(imsg); - graph.close(); - } - - LOGGER.auditEvent("-- all done, if program does not exit, please kill."); - System.exit(0); - } - -} - - diff --git a/aai-core/src/main/java/org/openecomp/aai/dbgen/PropertyLimitDesc.java b/aai-core/src/main/java/org/openecomp/aai/dbgen/PropertyLimitDesc.java deleted file mode 100644 index 8d0bf7ea..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/dbgen/PropertyLimitDesc.java +++ /dev/null @@ -1,27 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.dbgen; - -public enum PropertyLimitDesc { - SHOW_NONE, - SHOW_ALL, - SHOW_NAME_AND_KEYS_ONLY -} diff --git a/aai-core/src/main/java/org/openecomp/aai/dbgen/SchemaGenerator.java b/aai-core/src/main/java/org/openecomp/aai/dbgen/SchemaGenerator.java deleted file mode 100644 index 9f85d029..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/dbgen/SchemaGenerator.java +++ /dev/null @@ -1,193 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.dbgen; - - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Optional; -import java.util.Set; - -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.openecomp.aai.db.props.AAIProperties; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.introspection.LoaderFactory; -import org.openecomp.aai.introspection.ModelType; -import org.openecomp.aai.schema.enums.PropertyMetadata; -import org.openecomp.aai.serialization.db.EdgeRule; -import org.openecomp.aai.serialization.db.EdgeRules; -import org.openecomp.aai.util.AAIConfig; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.google.common.collect.Multimap; -import com.thinkaurelius.titan.core.Cardinality; -import com.thinkaurelius.titan.core.Multiplicity; -import com.thinkaurelius.titan.core.PropertyKey; -import com.thinkaurelius.titan.core.TitanGraph; -import com.thinkaurelius.titan.core.schema.TitanManagement; - - - -public class SchemaGenerator{ - - private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(SchemaGenerator.class); - private static boolean addDefaultCR = true; - - - /** - * Load schema into titan. - * - * @param graph the graph - * @param graphMgmt the graph mgmt - * @param addDefaultCloudRegion the add default cloud region - */ - public static void loadSchemaIntoTitan(final TitanGraph graph, final TitanManagement graphMgmt, boolean addDefaultCloudRegion) { - addDefaultCR = addDefaultCloudRegion; - loadSchemaIntoTitan(graph, graphMgmt); - } - - /** - * Load schema into titan. - * - * @param graph the graph - * @param graphMgmt the graph mgmt - */ - public static void loadSchemaIntoTitan(final TitanGraph graph, final TitanManagement graphMgmt) { - - try { - AAIConfig.init(); - } - catch (Exception ex){ - LOGGER.error(" ERROR - Could not run AAIConfig.init(). ", ex); - System.out.println(" ERROR - Could not run AAIConfig.init(). "); - System.exit(1); - } - - // NOTE - Titan 0.5.3 doesn't keep a list of legal node Labels. - // They are only used when a vertex is actually being created. Titan 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 edges = null; - Set labels = new HashSet<>(); - - edges = EdgeRules.getInstance().getAllRules(); - for (EdgeRule rule : edges.values()) { - labels.add(rule.getLabel()); - } - - for( String label: labels){ - if( graphMgmt.containsRelationType(label) ) { - String dmsg = " EdgeLabel [" + label + "] already existed. "; - System.out.println(dmsg); - LOGGER.debug(dmsg); - } else { - String dmsg = "Making EdgeLabel: [" + label + "]"; - System.out.println(dmsg); - LOGGER.debug(dmsg); - graphMgmt.makeEdgeLabel(label).multiplicity(Multiplicity.valueOf("MULTI")).make(); - } - } - - Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, AAIProperties.LATEST); - Map objs = loader.getAllObjects(); - Map seenProps = new HashMap<>(); - - for (Introspector obj : objs.values()) { - for (String propName : obj.getProperties()) { - String dbPropName = propName; - Optional alias = obj.getPropertyMetadata(propName, PropertyMetadata.DB_ALIAS); - if (alias.isPresent()) { - dbPropName = alias.get(); - } - if( graphMgmt.containsRelationType(propName) ){ - String dmsg = " PropertyKey [" + propName + "] already existed in the DB. "; - System.out.println(dmsg); - 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 + "]"; - System.out.println(imsg); - 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. "; - System.out.println(dmsg); - LOGGER.debug(dmsg); - } else { - if( obj.getIndexedProperties().contains(propName) ){ - if( obj.getUniqueProperties().contains(propName) ){ - imsg = "Add Unique index for PropertyKey: [" + dbPropName + "]"; - System.out.println(imsg); - LOGGER.info(imsg); - graphMgmt.buildIndex(dbPropName,Vertex.class).addKey(propK).unique().buildCompositeIndex(); - } else { - imsg = "Add index for PropertyKey: [" + dbPropName + "]"; - System.out.println(imsg); - LOGGER.info(imsg); - graphMgmt.buildIndex(dbPropName,Vertex.class).addKey(propK).buildCompositeIndex(); - } - } else { - imsg = "No index added for PropertyKey: [" + dbPropName + "]"; - System.out.println(imsg); - LOGGER.info(imsg); - } - } - } - } - } - } - - String imsg = "-- About to call graphMgmt commit"; - System.out.println(imsg); - LOGGER.info(imsg); - - graphMgmt.commit(); - }// End of loadSchemaIntoTitan() - -} - - diff --git a/aai-core/src/main/java/org/openecomp/aai/dbmap/AAIGraph.java b/aai-core/src/main/java/org/openecomp/aai/dbmap/AAIGraph.java deleted file mode 100644 index 4921b91d..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/dbmap/AAIGraph.java +++ /dev/null @@ -1,196 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.dbmap; - -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; - -import org.apache.commons.lang.exception.ExceptionUtils; -import org.apache.tinkerpop.gremlin.structure.Graph; -import org.apache.tinkerpop.gremlin.structure.io.IoCore; -import org.openecomp.aai.dbgen.SchemaGenerator; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.util.AAIConstants; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.thinkaurelius.titan.core.TitanFactory; -import com.thinkaurelius.titan.core.TitanGraph; -import com.thinkaurelius.titan.core.schema.TitanManagement; - -/** - * Database Mapping class which acts as the middle man between the REST - * interface objects and Titan DB objects. This class provides methods to commit - * the objects received on the REST interface into the Titan graph database as - * vertices and edges. Transactions are also managed here by using a TitanGraph - * object to load, commit/rollback and shutdown for each request. The data model - * rules such as keys/required properties are handled by calling DBMeth methods - * which are driven by a specification file in json. - * - - */ -public class AAIGraph { - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(AAIGraph.class); - protected static final String COMPONENT = "aaidbmap"; - protected Map graphs = new HashMap<>(); - private final String REALTIME_DB = "realtime"; - private final String CACHED_DB = "cached"; - - - - /** - * Instantiates a new AAI graph. - */ - private AAIGraph() { - try { - String rtConfig = System.getProperty("realtime.db.config"); - String cachedConfig = System.getProperty("cached.db.config"); - if (rtConfig == null) { - rtConfig = AAIConstants.REALTIME_DB_CONFIG; - } - if (cachedConfig == null) { - cachedConfig = AAIConstants.CACHED_DB_CONFIG; - } - this.loadGraph(REALTIME_DB, rtConfig); - this.loadGraph(CACHED_DB, cachedConfig); - } catch (Exception e) { - throw new RuntimeException("Failed to instantiate graphs", e); - } - } - - private static class Helper { - private static final AAIGraph INSTANCE = new AAIGraph(); - } - - /** - * Gets the single instance of AAIGraph. - * - * @return single instance of AAIGraph - */ - public static AAIGraph getInstance() { - return Helper.INSTANCE; - } - - private void loadGraph(String name, String configPath) throws AAIException { - // Graph being opened by TitanFactory is being placed in hashmap to be used later - // These graphs shouldn't be closed until the application shutdown - TitanGraph graph = TitanFactory.open(configPath); - try (InputStream is = new FileInputStream(configPath)) { - - Properties graphProps = new Properties(); - graphProps.load(is); - - if ("inmemory".equals(graphProps.get("storage.backend"))) { - // Load the propertyKeys, indexes and edge-Labels into the DB - loadSchema(graph); - loadSnapShotToInMemoryGraph(graph, graphProps); - } - - if (graph == null) { - throw new AAIException("AAI_5102"); - } - - graphs.put(name, graph); - } catch (FileNotFoundException fnfe) { - throw new AAIException("AAI_4001"); - } catch (IOException e) { - throw new AAIException("AAI_4002"); - } - } - - private void loadSnapShotToInMemoryGraph(TitanGraph graph, Properties graphProps) { - if (logger.isDebugEnabled()) { - logger.debug("Load Snapshot to InMemory Graph"); - } - if (graphProps.containsKey("load.snapshot.file")) { - String value = graphProps.getProperty("load.snapshot.file"); - if ("true".equals(value)) { - try (Graph transaction = graph.newTransaction()) { - String location = System.getProperty("snapshot.location"); - logAndPrint(logger, "Loading snapshot to inmemory graph."); - transaction.io(IoCore.graphson()).readGraph(location); - 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" - + ExceptionUtils.getFullStackTrace(e)); - System.exit(0); - } - } - } - } - - private void loadSchema(TitanGraph graph) { - // Load the propertyKeys, indexes and edge-Labels into the DB - TitanManagement graphMgt = graph.openManagement(); - - System.out.println("-- loading schema into Titan"); - SchemaGenerator.loadSchemaIntoTitan( graph, graphMgt ); - } - - /** - * Graph shutdown. - */ - public void graphShutdown() { - graphs.get(REALTIME_DB).close(); - } - - /** - * Gets the graph. - * - * @return the graph - */ - public TitanGraph getGraph() { - return graphs.get(REALTIME_DB); - } - - public void graphShutdown(DBConnectionType connectionType) { - - graphs.get(this.getGraphName(connectionType)).close(); - } - - public TitanGraph getGraph(DBConnectionType connectionType) { - return graphs.get(this.getGraphName(connectionType)); - } - - private String getGraphName(DBConnectionType connectionType) { - String graphName = ""; - if (DBConnectionType.CACHED.equals(connectionType)) { - graphName = this.CACHED_DB; - } 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/openecomp/aai/dbmap/DBConnectionType.java b/aai-core/src/main/java/org/openecomp/aai/dbmap/DBConnectionType.java deleted file mode 100644 index 26495275..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/dbmap/DBConnectionType.java +++ /dev/null @@ -1,26 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.dbmap; - -public enum DBConnectionType { - REALTIME, - CACHED -} diff --git a/aai-core/src/main/java/org/openecomp/aai/dmaap/AAIDmaapEventJMSConsumer.java b/aai-core/src/main/java/org/openecomp/aai/dmaap/AAIDmaapEventJMSConsumer.java deleted file mode 100644 index db72d63d..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/dmaap/AAIDmaapEventJMSConsumer.java +++ /dev/null @@ -1,143 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.dmaap; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.sun.jersey.api.client.Client; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.WebResource; -import org.apache.log4j.MDC; -import org.json.JSONException; -import org.json.JSONObject; -import org.openecomp.aai.logging.ErrorLogHelper; -import org.openecomp.aai.util.AAIConstants; -import org.openecomp.aai.logging.LoggingContext; -import org.openecomp.aai.logging.LoggingContext.LoggingField; -import org.openecomp.aai.logging.LoggingContext.StatusCode; - -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageListener; -import javax.jms.TextMessage; -import javax.ws.rs.core.MediaType; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.util.Properties; - -public class AAIDmaapEventJMSConsumer implements MessageListener { - - private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(AAIDmaapEventJMSConsumer.class); - - private Client httpClient; - - private Properties aaiEventProps; - private String aaiEventUrl = ""; - - public AAIDmaapEventJMSConsumer() throws org.apache.commons.configuration.ConfigurationException { - super(); - try(FileReader reader = new FileReader(new File(AAIConstants.AAI_EVENT_DMAAP_PROPS))) { - - if (this.httpClient == null) { - aaiEventProps = new Properties(); - aaiEventProps.load(reader); - - String host = aaiEventProps.getProperty("host"); - String topic = aaiEventProps.getProperty("topic"); - String protocol = aaiEventProps.getProperty("Protocol"); - - aaiEventUrl = protocol + "://" + host + "/events/" + topic; - httpClient = Client.create(); - } - - } catch (IOException e) { - ErrorLogHelper.logError("AAI_4000", "Error updating dmaap config file for aai event."); - LOGGER.error(e.getMessage(), e); - } - - } - - @Override - public void onMessage(Message message) { - - String jsmMessageTxt = ""; - String aaiEvent = ""; - String eventName = ""; - - if (message instanceof TextMessage) { - try { - jsmMessageTxt = ((TextMessage) message).getText(); - JSONObject jo = new JSONObject(jsmMessageTxt); - - if (jo.has("aaiEventPayload")) { - aaiEvent = jo.getJSONObject("aaiEventPayload").toString(); - } else { - return; - } - if (jo.getString("transId") != null) { - MDC.put("requestId", jo.getString("transId")); - } - if (jo.getString("fromAppId") != null) { - MDC.put("partnerName", jo.getString("fromAppId")); - } - if (jo.getString("event-topic") != null) { - eventName = jo.getString("event-topic"); - } - - LOGGER.info(eventName + "|" + aaiEvent); - if ("AAI-EVENT".equals(eventName)) { - this.sentWithHttp(this.httpClient, this.aaiEventUrl, aaiEvent); - } else { - LoggingContext.statusCode(StatusCode.ERROR); - LOGGER.error(eventName + "|Event Topic invalid."); - } - } catch (java.net.SocketException e) { - if (!e.getMessage().contains("Connection reset")) { - LOGGER.error("AAI_7304 Error reaching DMaaP to send event. " + aaiEvent, e); - } - } catch (IOException e) { - LOGGER.error("AAI_7304 Error reaching DMaaP to send event. " + aaiEvent, e); - } catch (JMSException | JSONException e) { - LOGGER.error("AAI_7350 Error parsing aaievent jsm message for sending to dmaap. " + jsmMessageTxt, e); - } catch (Exception e) { - LOGGER.error("AAI_7350 Error sending message to dmaap. " + jsmMessageTxt, e); - } - } - - } - - private boolean sentWithHttp(Client client, String url, String aaiEvent) throws IOException { - - WebResource webResource = client.resource(url); - - ClientResponse response = webResource - .accept(MediaType.APPLICATION_JSON) - .type(MediaType.APPLICATION_JSON) - .post(ClientResponse.class, aaiEvent); - - if (response.getStatus() != 200) { - LOGGER.info("Failed : HTTP error code : " + response.getStatus()); - return false; - } - return true; - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/dmaap/AAIDmaapEventJMSProducer.java b/aai-core/src/main/java/org/openecomp/aai/dmaap/AAIDmaapEventJMSProducer.java deleted file mode 100644 index 89ed9348..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/dmaap/AAIDmaapEventJMSProducer.java +++ /dev/null @@ -1,49 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.dmaap; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.command.ActiveMQQueue; -import org.json.JSONObject; -import org.openecomp.aai.util.AAIConfig; -import org.springframework.jms.connection.CachingConnectionFactory; -import org.springframework.jms.core.JmsTemplate; - -public class AAIDmaapEventJMSProducer { - - private JmsTemplate jmsTemplate; - - public AAIDmaapEventJMSProducer() { - if(AAIConfig.get("aai.jms.enable", "true").equals("true")){ - this.jmsTemplate = new JmsTemplate(); - this.jmsTemplate.setConnectionFactory(new CachingConnectionFactory(new ActiveMQConnectionFactory("tcp://localhost:61447"))); - this.jmsTemplate.setDefaultDestination(new ActiveMQQueue("IN_QUEUE")); - } - } - - public void sendMessageToDefaultDestination(JSONObject finalJson) { - if(jmsTemplate != null){ - jmsTemplate.convertAndSend(finalJson.toString()); - CachingConnectionFactory ccf = (CachingConnectionFactory) this.jmsTemplate.getConnectionFactory(); - ccf.destroy(); - } - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/domain/notificationEvent/NotificationEvent.java b/aai-core/src/main/java/org/openecomp/aai/domain/notificationEvent/NotificationEvent.java deleted file mode 100644 index 865d045f..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/domain/notificationEvent/NotificationEvent.java +++ /dev/null @@ -1,564 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2016.01.06 at 05:38:00 PM EST -// - - -package org.openecomp.aai.domain.notificationEvent; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -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; - - -/** - *

    Java class for anonymous complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType>
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *       <sequence>
    - *         <element name="cambria.partition" type="{http://www.w3.org/2001/XMLSchema}string"/>
    - *         <element name="event-header" minOccurs="0">
    - *           <complexType>
    - *             <complexContent>
    - *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *                 <sequence>
    - *                   <element name="id" type="{http://www.w3.org/2001/XMLSchema}string"/>
    - *                   <element name="timestamp" type="{http://www.w3.org/2001/XMLSchema}string"/>
    - *                   <element name="source-name" type="{http://www.w3.org/2001/XMLSchema}string"/>
    - *                   <element name="domain" type="{http://www.w3.org/2001/XMLSchema}string"/>
    - *                   <element name="sequence-number" type="{http://www.w3.org/2001/XMLSchema}string"/>
    - *                   <element name="severity" type="{http://www.w3.org/2001/XMLSchema}string"/>
    - *                   <element name="event-type" type="{http://www.w3.org/2001/XMLSchema}string"/>
    - *                   <element name="version" type="{http://www.w3.org/2001/XMLSchema}string"/>
    - *                   <element name="action" type="{http://www.w3.org/2001/XMLSchema}string"/>
    - *                   <element name="entity-type" type="{http://www.w3.org/2001/XMLSchema}string"/>
    - *                   <element name="top-entity-type" type="{http://www.w3.org/2001/XMLSchema}string"/>
    - *                   <element name="entity-link" type="{http://www.w3.org/2001/XMLSchema}string"/>
    - *                   <element name="status" type="{http://www.w3.org/2001/XMLSchema}string"/>
    - *                 </sequence>
    - *               </restriction>
    - *             </complexContent>
    - *           </complexType>
    - *         </element>
    - *         <any processContents='lax' namespace='##other' minOccurs="0"/>
    - *       </sequence>
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "cambriaPartition", - "eventHeader", - "entity" -}) -@XmlRootElement(name = "NotificationEvent") -public class NotificationEvent { - - @XmlElement(name = "cambria.partition") - protected String cambriaPartition; - @XmlElement(name = "event-header") - protected NotificationEvent.EventHeader eventHeader; - @XmlAnyElement(lax = true) - protected Object entity; - - /** - * Gets the value of the eventHeader property. - * - * @return - * possible object is - * {@link NotificationEvent.EventHeader } - * - */ - public NotificationEvent.EventHeader getEventHeader() { - return eventHeader; - } - - /** - * Sets the value of the eventHeader property. - * - * @param value - * allowed object is - * {@link NotificationEvent.EventHeader } - * - */ - public void setEventHeader(NotificationEvent.EventHeader value) { - this.eventHeader = value; - } - - /** - * Gets the value of the any property. - * - * @return - * possible object is - * {@link Object } - * {@link Element } - * - */ - public Object getEntity() { - return entity; - } - - /** - * Sets the value of the any property. - * - * @param value - * allowed object is - * {@link Object } - * {@link Element } - * - */ - public void setEntity(Object value) { - this.entity = value; - } - - /** - * Gets the value of the cambriaPartition property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getCambriaPartition() { - return cambriaPartition; - } - - /** - * Sets the value of the cambriaPartition property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setCambriaPartition(String value) { - this.cambriaPartition = value; - } - - - /** - *

    Java class for anonymous complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    -     * <complexType>
    -     *   <complexContent>
    -     *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    -     *       <sequence>
    -     *         <element name="id" type="{http://www.w3.org/2001/XMLSchema}string"/>
    -     *         <element name="timestamp" type="{http://www.w3.org/2001/XMLSchema}string"/>
    -     *         <element name="source-name" type="{http://www.w3.org/2001/XMLSchema}string"/>
    -     *         <element name="domain" type="{http://www.w3.org/2001/XMLSchema}string"/>
    -     *         <element name="sequence-number" type="{http://www.w3.org/2001/XMLSchema}string"/>
    -     *         <element name="severity" type="{http://www.w3.org/2001/XMLSchema}string"/>
    -     *         <element name="event-type" type="{http://www.w3.org/2001/XMLSchema}string"/>
    -     *         <element name="version" type="{http://www.w3.org/2001/XMLSchema}string"/>
    -     *         <element name="action" type="{http://www.w3.org/2001/XMLSchema}string"/>
    -     *         <element name="entity-type" type="{http://www.w3.org/2001/XMLSchema}string"/>
    -     *         <element name="top-entity-type" type="{http://www.w3.org/2001/XMLSchema}string"/>
    -     *         <element name="entity-link" type="{http://www.w3.org/2001/XMLSchema}string"/>
    -     *         <element name="status" type="{http://www.w3.org/2001/XMLSchema}string"/>
    -     *       </sequence>
    -     *     </restriction>
    -     *   </complexContent>
    -     * </complexType>
    -     * 
    - * - * - */ - @XmlAccessorType(XmlAccessType.FIELD) - @XmlType(name = "", propOrder = { - "id", - "timestamp", - "sourceName", - "domain", - "sequenceNumber", - "severity", - "eventType", - "version", - "action", - "entityType", - "topEntityType", - "entityLink", - "status" - }) - public static class EventHeader { - - @XmlElement(required = true) - protected String id; - @XmlElement(required = true) - protected String timestamp; - @XmlElement(name = "source-name", required = true) - protected String sourceName; - @XmlElement(required = true) - protected String domain; - @XmlElement(name = "sequence-number", required = true) - protected String sequenceNumber; - @XmlElement(required = true) - protected String severity; - @XmlElement(name = "event-type", required = true) - protected String eventType; - @XmlElement(required = true) - protected String version; - @XmlElement(required = true) - protected String action; - @XmlElement(name = "entity-type", required = true) - protected String entityType; - @XmlElement(name = "top-entity-type", required = true) - protected String topEntityType; - @XmlElement(name = "entity-link", required = true) - protected String entityLink; - @XmlElement(required = true) - protected String status; - - /** - * Gets the value of the id property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getId() { - return id; - } - - /** - * Sets the value of the id property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setId(String value) { - this.id = value; - } - - /** - * Gets the value of the timestamp property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getTimestamp() { - return timestamp; - } - - /** - * Sets the value of the timestamp property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setTimestamp(String value) { - this.timestamp = value; - } - - /** - * Gets the value of the sourceName property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getSourceName() { - return sourceName; - } - - /** - * Sets the value of the sourceName property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setSourceName(String value) { - this.sourceName = value; - } - - /** - * Gets the value of the domain property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getDomain() { - return domain; - } - - /** - * Sets the value of the domain property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setDomain(String value) { - this.domain = value; - } - - /** - * Gets the value of the sequenceNumber property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getSequenceNumber() { - return sequenceNumber; - } - - /** - * Sets the value of the sequenceNumber property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setSequenceNumber(String value) { - this.sequenceNumber = value; - } - - /** - * Gets the value of the severity property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getSeverity() { - return severity; - } - - /** - * Sets the value of the severity property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setSeverity(String value) { - this.severity = value; - } - - /** - * Gets the value of the eventType property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getEventType() { - return eventType; - } - - /** - * Sets the value of the eventType property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setEventType(String value) { - this.eventType = value; - } - - /** - * Gets the value of the version property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getVersion() { - return version; - } - - /** - * Sets the value of the version property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setVersion(String value) { - this.version = value; - } - - /** - * Gets the value of the action property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getAction() { - return action; - } - - /** - * Sets the value of the action property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setAction(String value) { - this.action = value; - } - - /** - * Gets the value of the entityType property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getEntityType() { - return entityType; - } - - /** - * Sets the value of the entityType property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setEntityType(String value) { - this.entityType = value; - } - - /** - * Gets the value of the topEntityType property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getTopEntityType() { - return topEntityType; - } - - /** - * Sets the value of the topEntityType property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setTopEntityType(String value) { - this.topEntityType = value; - } - - /** - * Gets the value of the entityLink property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getEntityLink() { - return entityLink; - } - - /** - * Sets the value of the entityLink property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setEntityLink(String value) { - this.entityLink = 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; - } - - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/domain/notificationEvent/ObjectFactory.java b/aai-core/src/main/java/org/openecomp/aai/domain/notificationEvent/ObjectFactory.java deleted file mode 100644 index c331aab2..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/domain/notificationEvent/ObjectFactory.java +++ /dev/null @@ -1,77 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2016.01.06 at 05:38:00 PM EST -// - - -package org.openecomp.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.openecomp.aai.domain.notificationEvent package. - *

    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.openecomp.aai.domain.notificationEvent - * - */ - public ObjectFactory() { - } - - /** - * Create an instance of {@link NotificationEvent }. - * - * @return the notification event - */ - public NotificationEvent createNotificationEvent() { - return new NotificationEvent(); - } - - /** - * Create an instance of {@link NotificationEvent.EventHeader } - * - * @return the event header - */ - public NotificationEvent.EventHeader createNotificationEventEventHeader() { - return new NotificationEvent.EventHeader(); - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/domain/responseMessage/AAIResponseMessage.java b/aai-core/src/main/java/org/openecomp/aai/domain/responseMessage/AAIResponseMessage.java deleted file mode 100644 index b3f03247..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/domain/responseMessage/AAIResponseMessage.java +++ /dev/null @@ -1,125 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.domain.responseMessage; - -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; - -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "aaiResponseMessageCode", - "aaiResponseMessageResourceType", - "aaiResponseMessageDescription", - "aaiResponseMessageData", -}) -@XmlRootElement(name = "aai-response-message", namespace = "http://org.openecomp.aai.inventory") -public class AAIResponseMessage { - - @XmlElement(name = "aai-response-message-code", required = true) - protected String aaiResponseMessageCode; - @XmlElement(name = "aai-response-message-resource-type") - protected String aaiResponseMessageResourceType; - @XmlElement(name = "aai-response-message-description") - 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; - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/domain/responseMessage/AAIResponseMessageData.java b/aai-core/src/main/java/org/openecomp/aai/domain/responseMessage/AAIResponseMessageData.java deleted file mode 100644 index 16f9c6dd..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/domain/responseMessage/AAIResponseMessageData.java +++ /dev/null @@ -1,78 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.domain.responseMessage; - - -// -//This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 -//See http://java.sun.com/xml/jaxb -//Any modifications to this file will be lost upon recompilation of the source schema. -//Generated on: 2015.09.11 at 11:53:27 AM EDT -// - -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.XmlAnyElement; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlType; - -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "aaiResponseMessageDatum", - "any" -}) -@XmlRootElement(name = "aai-response-message-data", namespace = "http://org.openecomp.aai.inventory") -public class AAIResponseMessageData { - - @XmlElement(name = "aai-response-message-datum") - protected List aaiResponseMessageDatum; - @XmlAnyElement(lax = true) - protected List any; - - /** - * Gets the AAI response message datum. - * - * @return the AAI response message datum - */ - public List getAAIResponseMessageDatum() { - if (aaiResponseMessageDatum == null) { - aaiResponseMessageDatum = new ArrayList(); - } - return this.aaiResponseMessageDatum; - } - - /** - * Gets the any. - * - * @return the any - */ - public List getAny() { - if (any == null) { - any = new ArrayList(); - } - return this.any; - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/domain/responseMessage/AAIResponseMessageDatum.java b/aai-core/src/main/java/org/openecomp/aai/domain/responseMessage/AAIResponseMessageDatum.java deleted file mode 100644 index 8b64651f..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/domain/responseMessage/AAIResponseMessageDatum.java +++ /dev/null @@ -1,81 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.domain.responseMessage; - -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; - -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "aaiResponseMessageDatumKey", - "aaiResponseMessageDatumValue", - -}) - -@XmlRootElement(name = "aai-response-message-datum", namespace = "http://org.openecomp.aai.inventory") -public class AAIResponseMessageDatum { - - @XmlElement(name = "aai-response-message-datum-key", required = true) - 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; - } - - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/domain/responseMessage/AAIResponseMessages.java b/aai-core/src/main/java/org/openecomp/aai/domain/responseMessage/AAIResponseMessages.java deleted file mode 100644 index 41ff5610..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/domain/responseMessage/AAIResponseMessages.java +++ /dev/null @@ -1,118 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.domain.responseMessage; - - -// -//This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 -//See http://java.sun.com/xml/jaxb -//Any modifications to this file will be lost upon recompilation of the source schema. -//Generated on: 2015.09.11 at 11:53:27 AM EDT -// - -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.XmlAnyElement; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlType; - -/** - *

    Java class for anonymous complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType>
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *       <sequence>
    - *         <element name="flavor" maxOccurs="unbounded" minOccurs="0">
    - *           <complexType>
    - *             <complexContent>
    - *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *                 <sequence>
    - *                   <element name="flavor-id" type="{http://www.w3.org/2001/XMLSchema}string"/>
    - *                   <element name="flavor-name" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
    - *                   <element name="flavor-vcpus" type="{http://www.w3.org/2001/XMLSchema}short" minOccurs="0"/>
    - *                   <element name="flavor-ram" type="{http://www.w3.org/2001/XMLSchema}short" minOccurs="0"/>
    - *                   <element name="flavor-disk" type="{http://www.w3.org/2001/XMLSchema}short" minOccurs="0"/>
    - *                   <element name="flavor-ephemeral" type="{http://www.w3.org/2001/XMLSchema}short" minOccurs="0"/>
    - *                   <element name="flavor-swap" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
    - *                   <element name="flavor-is-public" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
    - *                   <element name="flavor-selflink" type="{urn:ietf:params:xml:ns:yang:ietf-inet-types}uri" minOccurs="0"/>
    - *                   <element name="flavor-disabled" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
    - *                   <any processContents='lax' namespace='##other' maxOccurs="unbounded" minOccurs="0"/>
    - *                   <element ref="{http://org.openecomp.aai.inventory/v3}relationship-list" minOccurs="0"/>
    - *                 </sequence>
    - *               </restriction>
    - *             </complexContent>
    - *           </complexType>
    - *         </element>
    - *         <any processContents='lax' namespace='##other' maxOccurs="unbounded" minOccurs="0"/>
    - *       </sequence>
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "aaiResponseMessage", - "any" -}) -@XmlRootElement(name = "aai-response-messages", namespace = "http://org.openecomp.aai.inventory") -public class AAIResponseMessages { - @XmlElement(name = "aai-response-message") - protected List aaiResponseMessage; - @XmlAnyElement(lax = true) - protected List any; - - /** - * Gets the AAI response message. - * - * @return the AAI response message - */ - public List getAAIResponseMessage() { - if (aaiResponseMessage == null) { - aaiResponseMessage = new ArrayList(); - } - return this.aaiResponseMessage; - } - - /** - * Gets the any. - * - * @return the any - */ - public List getAny() { - if (any == null) { - any = new ArrayList(); - } - return this.any; - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/domain/responseMessage/package-info.java b/aai-core/src/main/java/org/openecomp/aai/domain/responseMessage/package-info.java deleted file mode 100644 index cfb4981a..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/domain/responseMessage/package-info.java +++ /dev/null @@ -1,32 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 -// See http://java.sun.com/xml/jaxb -// 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.openecomp.aai.inventory", - elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED) -package org.openecomp.aai.domain.responseMessage; - diff --git a/aai-core/src/main/java/org/openecomp/aai/domain/restPolicyException/Fault.java b/aai-core/src/main/java/org/openecomp/aai/domain/restPolicyException/Fault.java deleted file mode 100644 index f32268b3..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/domain/restPolicyException/Fault.java +++ /dev/null @@ -1,382 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2015.02.11 at 04:54:39 PM EST -// - - -package org.openecomp.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; - - -/** - *

    Java class for anonymous complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType>
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *       <sequence>
    - *         <element name="requestError">
    - *           <complexType>
    - *             <complexContent>
    - *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *                 <sequence>
    - *                   <element name="policyException">
    - *                     <complexType>
    - *                       <complexContent>
    - *                         <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *                           <sequence>
    - *                             <element name="messageId" type="{http://www.w3.org/2001/XMLSchema}string"/>
    - *                             <element name="text" type="{http://www.w3.org/2001/XMLSchema}string"/>
    - *                             <element name="variables">
    - *                               <complexType>
    - *                                 <complexContent>
    - *                                   <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *                                     <sequence>
    - *                                       <element name="variable" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/>
    - *                                     </sequence>
    - *                                   </restriction>
    - *                                 </complexContent>
    - *                               </complexType>
    - *                             </element>
    - *                           </sequence>
    - *                         </restriction>
    - *                       </complexContent>
    - *                     </complexType>
    - *                   </element>
    - *                 </sequence>
    - *               </restriction>
    - *             </complexContent>
    - *           </complexType>
    - *         </element>
    - *       </sequence>
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "requestError" -}) -@XmlRootElement(name = "Fault") -public class Fault { - - @XmlElement(required = true) - protected Fault.RequestError requestError; - - /** - * Gets the value of the requestError property. - * - * @return - * possible object is - * {@link Fault.RequestError } - * - */ - public Fault.RequestError getRequestError() { - return requestError; - } - - /** - * Sets the value of the requestError property. - * - * @param value - * allowed object is - * {@link Fault.RequestError } - * - */ - public void setRequestError(Fault.RequestError value) { - this.requestError = value; - } - - - /** - *

    Java class for anonymous complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    -     * <complexType>
    -     *   <complexContent>
    -     *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    -     *       <sequence>
    -     *         <element name="policyException">
    -     *           <complexType>
    -     *             <complexContent>
    -     *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    -     *                 <sequence>
    -     *                   <element name="messageId" type="{http://www.w3.org/2001/XMLSchema}string"/>
    -     *                   <element name="text" type="{http://www.w3.org/2001/XMLSchema}string"/>
    -     *                   <element name="variables">
    -     *                     <complexType>
    -     *                       <complexContent>
    -     *                         <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    -     *                           <sequence>
    -     *                             <element name="variable" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/>
    -     *                           </sequence>
    -     *                         </restriction>
    -     *                       </complexContent>
    -     *                     </complexType>
    -     *                   </element>
    -     *                 </sequence>
    -     *               </restriction>
    -     *             </complexContent>
    -     *           </complexType>
    -     *         </element>
    -     *       </sequence>
    -     *     </restriction>
    -     *   </complexContent>
    -     * </complexType>
    -     * 
    - * - * - */ - @XmlAccessorType(XmlAccessType.FIELD) - @XmlType(name = "", propOrder = { - "policyException" - }) - public static class RequestError { - - @XmlElement(required = true) - protected Fault.RequestError.PolicyException policyException; - - /** - * Gets the value of the policyException property. - * - * @return - * possible object is - * {@link Fault.RequestError.PolicyException } - * - */ - public Fault.RequestError.PolicyException getPolicyException() { - return policyException; - } - - /** - * Sets the value of the policyException property. - * - * @param value - * allowed object is - * {@link Fault.RequestError.PolicyException } - * - */ - public void setPolicyException(Fault.RequestError.PolicyException value) { - this.policyException = value; - } - - - /** - *

    Java class for anonymous complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    -         * <complexType>
    -         *   <complexContent>
    -         *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    -         *       <sequence>
    -         *         <element name="messageId" type="{http://www.w3.org/2001/XMLSchema}string"/>
    -         *         <element name="text" type="{http://www.w3.org/2001/XMLSchema}string"/>
    -         *         <element name="variables">
    -         *           <complexType>
    -         *             <complexContent>
    -         *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    -         *                 <sequence>
    -         *                   <element name="variable" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/>
    -         *                 </sequence>
    -         *               </restriction>
    -         *             </complexContent>
    -         *           </complexType>
    -         *         </element>
    -         *       </sequence>
    -         *     </restriction>
    -         *   </complexContent>
    -         * </complexType>
    -         * 
    - * - * - */ - @XmlAccessorType(XmlAccessType.FIELD) - @XmlType(name = "", propOrder = { - "messageId", - "text", - "variables" - }) - public static class PolicyException { - - @XmlElement(required = true) - protected String messageId; - @XmlElement(required = true) - protected String text; - @XmlElement(required = true) - protected Fault.RequestError.PolicyException.Variables variables; - - /** - * Gets the value of the messageId property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getMessageId() { - return messageId; - } - - /** - * Sets the value of the messageId property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setMessageId(String value) { - this.messageId = value; - } - - /** - * Gets the value of the text property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getText() { - return text; - } - - /** - * Sets the value of the text property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setText(String value) { - this.text = value; - } - - /** - * Gets the value of the variables property. - * - * @return - * possible object is - * {@link Fault.RequestError.PolicyException.Variables } - * - */ - public Fault.RequestError.PolicyException.Variables getVariables() { - return variables; - } - - /** - * Sets the value of the variables property. - * - * @param value - * allowed object is - * {@link Fault.RequestError.PolicyException.Variables } - * - */ - public void setVariables(Fault.RequestError.PolicyException.Variables value) { - this.variables = value; - } - - - /** - *

    Java class for anonymous complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    -             * <complexType>
    -             *   <complexContent>
    -             *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    -             *       <sequence>
    -             *         <element name="variable" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/>
    -             *       </sequence>
    -             *     </restriction>
    -             *   </complexContent>
    -             * </complexType>
    -             * 
    - * - * - */ - @XmlAccessorType(XmlAccessType.FIELD) - @XmlType(name = "", propOrder = { - "variable" - }) - public static class Variables { - - protected List variable; - - /** - * Gets the value of the variable property. - * - *

    - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the variable property. - * - *

    - * For example, to add a new item, do as follows: - *

    -                 *    getVariable().add(newItem);
    -                 * 
    - * - * - *

    - * Objects of the following type(s) are allowed in the list - * {@link String } - * - * @return the variable - */ - public List getVariable() { - if (variable == null) { - variable = new ArrayList(); - } - return this.variable; - } - - } - - } - - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/domain/restPolicyException/ObjectFactory.java b/aai-core/src/main/java/org/openecomp/aai/domain/restPolicyException/ObjectFactory.java deleted file mode 100644 index 3cf31ed0..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/domain/restPolicyException/ObjectFactory.java +++ /dev/null @@ -1,95 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2015.02.11 at 04:54:39 PM EST -// - - -package org.openecomp.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.openecomp.aai.domain.restPolicyException package. - *

    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.openecomp.aai.domain.restPolicyException - * - */ - public ObjectFactory() { - } - - /** - * Create an instance of {@link Fault }. - * - * @return the fault - */ - public Fault createFault() { - return new Fault(); - } - - /** - * Create an instance of {@link Fault.RequestError } - * - * @return the request error - */ - public Fault.RequestError createFaultRequestError() { - return new Fault.RequestError(); - } - - /** - * Create an instance of {@link Fault.RequestError.PolicyException } - * - * @return the policy exception - */ - public Fault.RequestError.PolicyException createFaultRequestErrorPolicyException() { - return new Fault.RequestError.PolicyException(); - } - - /** - * Create an instance of {@link Fault.RequestError.PolicyException.Variables } - * - * @return the variables - */ - public Fault.RequestError.PolicyException.Variables createFaultRequestErrorPolicyExceptionVariables() { - return new Fault.RequestError.PolicyException.Variables(); - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/domain/restPolicyException/PolicyException.java b/aai-core/src/main/java/org/openecomp/aai/domain/restPolicyException/PolicyException.java deleted file mode 100644 index a55ce62e..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/domain/restPolicyException/PolicyException.java +++ /dev/null @@ -1,134 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.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; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - -@JsonInclude(JsonInclude.Include.NON_NULL) -@Generated("org.jsonschema2pojo") -@JsonPropertyOrder({ - "messageId", - "text", - "variables" -}) -public class PolicyException { - - @JsonProperty("messageId") - private String messageId; - @JsonProperty("text") - private String text; - @JsonProperty("variables") - private List variables = new ArrayList(); - @JsonIgnore - private Map additionalProperties = new HashMap(); - - /** - * Gets the message id. - * - * @return The messageId - */ - @JsonProperty("messageId") - public String getMessageId() { - return messageId; - } - - /** - * Sets the message id. - * - * @param messageId The messageId - */ - @JsonProperty("messageId") - public void setMessageId(String messageId) { - this.messageId = messageId; - } - - /** - * Gets the text. - * - * @return The text - */ - @JsonProperty("text") - public String getText() { - return text; - } - - /** - * Sets the text. - * - * @param text The text - */ - @JsonProperty("text") - public void setText(String text) { - this.text = text; - } - - /** - * Gets the variables. - * - * @return The variables - */ - @JsonProperty("variables") - public List getVariables() { - return variables; - } - - /** - * Sets the variables. - * - * @param variables The variables - */ - @JsonProperty("variables") - public void setVariables(List variables) { - this.variables = variables; - } - - /** - * Gets the additional properties. - * - * @return the additional properties - */ - @JsonAnyGetter - public Map getAdditionalProperties() { - return this.additionalProperties; - } - - /** - * Sets the additional property. - * - * @param name the name - * @param value the value - */ - @JsonAnySetter - public void setAdditionalProperty(String name, Object value) { - this.additionalProperties.put(name, value); - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/domain/restPolicyException/RESTResponse.java b/aai-core/src/main/java/org/openecomp/aai/domain/restPolicyException/RESTResponse.java deleted file mode 100644 index eb9deb27..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/domain/restPolicyException/RESTResponse.java +++ /dev/null @@ -1,86 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.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; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - -@JsonInclude(JsonInclude.Include.NON_NULL) -@Generated("org.jsonschema2pojo") -@JsonPropertyOrder({ - "requestError" -}) -public class RESTResponse { - - @JsonProperty("requestError") - private RequestError requestError; - @JsonIgnore - private Map additionalProperties = new HashMap(); - - /** - * Gets the request error. - * - * @return The requestError - */ - @JsonProperty("requestError") - public RequestError getRequestError() { - return requestError; - } - - /** - * Sets the request error. - * - * @param requestError The requestError - */ - @JsonProperty("requestError") - public void setRequestError(RequestError requestError) { - this.requestError = requestError; - } - - /** - * Gets the additional properties. - * - * @return the additional properties - */ - @JsonAnyGetter - public Map getAdditionalProperties() { - return this.additionalProperties; - } - - /** - * Sets the additional property. - * - * @param name the name - * @param value the value - */ - @JsonAnySetter - public void setAdditionalProperty(String name, Object value) { - this.additionalProperties.put(name, value); - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/domain/restPolicyException/RequestError.java b/aai-core/src/main/java/org/openecomp/aai/domain/restPolicyException/RequestError.java deleted file mode 100644 index a4d4e74e..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/domain/restPolicyException/RequestError.java +++ /dev/null @@ -1,87 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.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; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - -@JsonInclude(JsonInclude.Include.NON_NULL) -@Generated("org.jsonschema2pojo") -@JsonPropertyOrder({ - "policyException" -}) -public class RequestError { - - @JsonProperty("policyException") - private PolicyException policyException; - @JsonIgnore - private Map additionalProperties = new HashMap(); - - /** - * Gets the policy exception. - * - * @return The policyException - */ - @JsonProperty("policyException") - public PolicyException getPolicyException() { - return policyException; - } - - /** - * Sets the policy exception. - * - * @param policyException The policyException - */ - @JsonProperty("policyException") - public void setPolicyException(PolicyException policyException) { - this.policyException = policyException; - } - - /** - * Gets the additional properties. - * - * @return the additional properties - */ - @JsonAnyGetter - public Map getAdditionalProperties() { - return this.additionalProperties; - } - - /** - * Sets the additional property. - * - * @param name the name - * @param value the value - */ - @JsonAnySetter - public void setAdditionalProperty(String name, Object value) { - this.additionalProperties.put(name, value); - } - -} - diff --git a/aai-core/src/main/java/org/openecomp/aai/domain/restResponseInfo/Info.java b/aai-core/src/main/java/org/openecomp/aai/domain/restResponseInfo/Info.java deleted file mode 100644 index 6a1f8e4a..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/domain/restResponseInfo/Info.java +++ /dev/null @@ -1,385 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2015.10.28 at 05:53:17 PM EDT -// - - -package org.openecomp.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; - - -/** - *

    Java class for anonymous complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType>
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *       <sequence>
    - *         <element name="responseMessages" minOccurs="0">
    - *           <complexType>
    - *             <complexContent>
    - *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *                 <sequence>
    - *                   <element name="responseMessage" maxOccurs="unbounded" minOccurs="0">
    - *                     <complexType>
    - *                       <complexContent>
    - *                         <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *                           <sequence>
    - *                             <element name="messageId" type="{http://www.w3.org/2001/XMLSchema}string"/>
    - *                             <element name="text" type="{http://www.w3.org/2001/XMLSchema}string"/>
    - *                             <element name="variables">
    - *                               <complexType>
    - *                                 <complexContent>
    - *                                   <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *                                     <sequence>
    - *                                       <element name="variable" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/>
    - *                                     </sequence>
    - *                                   </restriction>
    - *                                 </complexContent>
    - *                               </complexType>
    - *                             </element>
    - *                           </sequence>
    - *                         </restriction>
    - *                       </complexContent>
    - *                     </complexType>
    - *                   </element>
    - *                 </sequence>
    - *               </restriction>
    - *             </complexContent>
    - *           </complexType>
    - *         </element>
    - *       </sequence>
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "responseMessages" -}) -@XmlRootElement(name = "Info") -public class Info { - - protected Info.ResponseMessages responseMessages; - - /** - * Gets the value of the responseMessages property. - * - * @return - * possible object is - * {@link Info.ResponseMessages } - * - */ - public Info.ResponseMessages getResponseMessages() { - return responseMessages; - } - - /** - * Sets the value of the responseMessages property. - * - * @param value - * allowed object is - * {@link Info.ResponseMessages } - * - */ - public void setResponseMessages(Info.ResponseMessages value) { - this.responseMessages = value; - } - - - /** - *

    Java class for anonymous complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    -     * <complexType>
    -     *   <complexContent>
    -     *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    -     *       <sequence>
    -     *         <element name="responseMessage" maxOccurs="unbounded" minOccurs="0">
    -     *           <complexType>
    -     *             <complexContent>
    -     *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    -     *                 <sequence>
    -     *                   <element name="messageId" type="{http://www.w3.org/2001/XMLSchema}string"/>
    -     *                   <element name="text" type="{http://www.w3.org/2001/XMLSchema}string"/>
    -     *                   <element name="variables">
    -     *                     <complexType>
    -     *                       <complexContent>
    -     *                         <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    -     *                           <sequence>
    -     *                             <element name="variable" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/>
    -     *                           </sequence>
    -     *                         </restriction>
    -     *                       </complexContent>
    -     *                     </complexType>
    -     *                   </element>
    -     *                 </sequence>
    -     *               </restriction>
    -     *             </complexContent>
    -     *           </complexType>
    -     *         </element>
    -     *       </sequence>
    -     *     </restriction>
    -     *   </complexContent>
    -     * </complexType>
    -     * 
    - * - * - */ - @XmlAccessorType(XmlAccessType.FIELD) - @XmlType(name = "", propOrder = { - "responseMessage" - }) - public static class ResponseMessages { - - protected List responseMessage; - - /** - * Gets the value of the responseMessage property. - * - *

    - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the responseMessage property. - * - *

    - * For example, to add a new item, do as follows: - *

    -         *    getResponseMessage().add(newItem);
    -         * 
    - * - * - *

    - * Objects of the following type(s) are allowed in the list - * {@link Info.ResponseMessages.ResponseMessage } - * - * @return the response message - */ - public List getResponseMessage() { - if (responseMessage == null) { - responseMessage = new ArrayList(); - } - return this.responseMessage; - } - - - /** - *

    Java class for anonymous complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    -         * <complexType>
    -         *   <complexContent>
    -         *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    -         *       <sequence>
    -         *         <element name="messageId" type="{http://www.w3.org/2001/XMLSchema}string"/>
    -         *         <element name="text" type="{http://www.w3.org/2001/XMLSchema}string"/>
    -         *         <element name="variables">
    -         *           <complexType>
    -         *             <complexContent>
    -         *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    -         *                 <sequence>
    -         *                   <element name="variable" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/>
    -         *                 </sequence>
    -         *               </restriction>
    -         *             </complexContent>
    -         *           </complexType>
    -         *         </element>
    -         *       </sequence>
    -         *     </restriction>
    -         *   </complexContent>
    -         * </complexType>
    -         * 
    - * - * - */ - @XmlAccessorType(XmlAccessType.FIELD) - @XmlType(name = "", propOrder = { - "messageId", - "text", - "variables" - }) - public static class ResponseMessage { - - @XmlElement(required = true) - protected String messageId; - @XmlElement(required = true) - protected String text; - @XmlElement(required = true) - protected Info.ResponseMessages.ResponseMessage.Variables variables; - - /** - * Gets the value of the messageId property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getMessageId() { - return messageId; - } - - /** - * Sets the value of the messageId property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setMessageId(String value) { - this.messageId = value; - } - - /** - * Gets the value of the text property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getText() { - return text; - } - - /** - * Sets the value of the text property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setText(String value) { - this.text = value; - } - - /** - * Gets the value of the variables property. - * - * @return - * possible object is - * {@link Info.ResponseMessages.ResponseMessage.Variables } - * - */ - public Info.ResponseMessages.ResponseMessage.Variables getVariables() { - return variables; - } - - /** - * Sets the value of the variables property. - * - * @param value - * allowed object is - * {@link Info.ResponseMessages.ResponseMessage.Variables } - * - */ - public void setVariables(Info.ResponseMessages.ResponseMessage.Variables value) { - this.variables = value; - } - - - /** - *

    Java class for anonymous complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    -             * <complexType>
    -             *   <complexContent>
    -             *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    -             *       <sequence>
    -             *         <element name="variable" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/>
    -             *       </sequence>
    -             *     </restriction>
    -             *   </complexContent>
    -             * </complexType>
    -             * 
    - * - * - */ - @XmlAccessorType(XmlAccessType.FIELD) - @XmlType(name = "", propOrder = { - "variable" - }) - public static class Variables { - - protected List variable; - - /** - * Gets the value of the variable property. - * - *

    - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the variable property. - * - *

    - * For example, to add a new item, do as follows: - *

    -                 *    getVariable().add(newItem);
    -                 * 
    - * - * - *

    - * Objects of the following type(s) are allowed in the list - * {@link String } - * - * @return the variable - */ - public List getVariable() { - if (variable == null) { - variable = new ArrayList(); - } - return this.variable; - } - - } - - } - - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/domain/restResponseInfo/ObjectFactory.java b/aai-core/src/main/java/org/openecomp/aai/domain/restResponseInfo/ObjectFactory.java deleted file mode 100644 index 70449586..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/domain/restResponseInfo/ObjectFactory.java +++ /dev/null @@ -1,95 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2015.10.28 at 05:53:17 PM EDT -// - - -package org.openecomp.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.openecomp.aai.domain.restResponseInfo package. - *

    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.openecomp.aai.domain.restResponseInfo - * - */ - public ObjectFactory() { - } - - /** - * Create an instance of {@link Info }. - * - * @return the info - */ - public Info createInfo() { - return new Info(); - } - - /** - * Create an instance of {@link Info.ResponseMessages } - * - * @return the response messages - */ - public Info.ResponseMessages createInfoResponseMessages() { - return new Info.ResponseMessages(); - } - - /** - * Create an instance of {@link Info.ResponseMessages.ResponseMessage } - * - * @return the response message - */ - public Info.ResponseMessages.ResponseMessage createInfoResponseMessagesResponseMessage() { - return new Info.ResponseMessages.ResponseMessage(); - } - - /** - * Create an instance of {@link Info.ResponseMessages.ResponseMessage.Variables } - * - * @return the variables - */ - public Info.ResponseMessages.ResponseMessage.Variables createInfoResponseMessagesResponseMessageVariables() { - return new Info.ResponseMessages.ResponseMessage.Variables(); - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/domain/restServiceException/Fault.java b/aai-core/src/main/java/org/openecomp/aai/domain/restServiceException/Fault.java deleted file mode 100644 index 3356a54f..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/domain/restServiceException/Fault.java +++ /dev/null @@ -1,382 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2015.02.11 at 04:54:29 PM EST -// - - -package org.openecomp.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; - - -/** - *

    Java class for anonymous complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType>
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *       <sequence>
    - *         <element name="requestError">
    - *           <complexType>
    - *             <complexContent>
    - *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *                 <sequence>
    - *                   <element name="serviceException">
    - *                     <complexType>
    - *                       <complexContent>
    - *                         <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *                           <sequence>
    - *                             <element name="messageId" type="{http://www.w3.org/2001/XMLSchema}string"/>
    - *                             <element name="text" type="{http://www.w3.org/2001/XMLSchema}string"/>
    - *                             <element name="variables">
    - *                               <complexType>
    - *                                 <complexContent>
    - *                                   <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *                                     <sequence>
    - *                                       <element name="variable" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/>
    - *                                     </sequence>
    - *                                   </restriction>
    - *                                 </complexContent>
    - *                               </complexType>
    - *                             </element>
    - *                           </sequence>
    - *                         </restriction>
    - *                       </complexContent>
    - *                     </complexType>
    - *                   </element>
    - *                 </sequence>
    - *               </restriction>
    - *             </complexContent>
    - *           </complexType>
    - *         </element>
    - *       </sequence>
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "requestError" -}) -@XmlRootElement(name = "Fault") -public class Fault { - - @XmlElement(required = true) - protected Fault.RequestError requestError; - - /** - * Gets the value of the requestError property. - * - * @return - * possible object is - * {@link Fault.RequestError } - * - */ - public Fault.RequestError getRequestError() { - return requestError; - } - - /** - * Sets the value of the requestError property. - * - * @param value - * allowed object is - * {@link Fault.RequestError } - * - */ - public void setRequestError(Fault.RequestError value) { - this.requestError = value; - } - - - /** - *

    Java class for anonymous complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    -     * <complexType>
    -     *   <complexContent>
    -     *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    -     *       <sequence>
    -     *         <element name="serviceException">
    -     *           <complexType>
    -     *             <complexContent>
    -     *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    -     *                 <sequence>
    -     *                   <element name="messageId" type="{http://www.w3.org/2001/XMLSchema}string"/>
    -     *                   <element name="text" type="{http://www.w3.org/2001/XMLSchema}string"/>
    -     *                   <element name="variables">
    -     *                     <complexType>
    -     *                       <complexContent>
    -     *                         <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    -     *                           <sequence>
    -     *                             <element name="variable" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/>
    -     *                           </sequence>
    -     *                         </restriction>
    -     *                       </complexContent>
    -     *                     </complexType>
    -     *                   </element>
    -     *                 </sequence>
    -     *               </restriction>
    -     *             </complexContent>
    -     *           </complexType>
    -     *         </element>
    -     *       </sequence>
    -     *     </restriction>
    -     *   </complexContent>
    -     * </complexType>
    -     * 
    - * - * - */ - @XmlAccessorType(XmlAccessType.FIELD) - @XmlType(name = "", propOrder = { - "serviceException" - }) - public static class RequestError { - - @XmlElement(required = true) - protected Fault.RequestError.ServiceException serviceException; - - /** - * Gets the value of the serviceException property. - * - * @return - * possible object is - * {@link Fault.RequestError.ServiceException } - * - */ - public Fault.RequestError.ServiceException getServiceException() { - return serviceException; - } - - /** - * Sets the value of the serviceException property. - * - * @param value - * allowed object is - * {@link Fault.RequestError.ServiceException } - * - */ - public void setServiceException(Fault.RequestError.ServiceException value) { - this.serviceException = value; - } - - - /** - *

    Java class for anonymous complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    -         * <complexType>
    -         *   <complexContent>
    -         *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    -         *       <sequence>
    -         *         <element name="messageId" type="{http://www.w3.org/2001/XMLSchema}string"/>
    -         *         <element name="text" type="{http://www.w3.org/2001/XMLSchema}string"/>
    -         *         <element name="variables">
    -         *           <complexType>
    -         *             <complexContent>
    -         *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    -         *                 <sequence>
    -         *                   <element name="variable" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/>
    -         *                 </sequence>
    -         *               </restriction>
    -         *             </complexContent>
    -         *           </complexType>
    -         *         </element>
    -         *       </sequence>
    -         *     </restriction>
    -         *   </complexContent>
    -         * </complexType>
    -         * 
    - * - * - */ - @XmlAccessorType(XmlAccessType.FIELD) - @XmlType(name = "", propOrder = { - "messageId", - "text", - "variables" - }) - public static class ServiceException { - - @XmlElement(required = true) - protected String messageId; - @XmlElement(required = true) - protected String text; - @XmlElement(required = true) - protected Fault.RequestError.ServiceException.Variables variables; - - /** - * Gets the value of the messageId property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getMessageId() { - return messageId; - } - - /** - * Sets the value of the messageId property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setMessageId(String value) { - this.messageId = value; - } - - /** - * Gets the value of the text property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getText() { - return text; - } - - /** - * Sets the value of the text property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setText(String value) { - this.text = value; - } - - /** - * Gets the value of the variables property. - * - * @return - * possible object is - * {@link Fault.RequestError.ServiceException.Variables } - * - */ - public Fault.RequestError.ServiceException.Variables getVariables() { - return variables; - } - - /** - * Sets the value of the variables property. - * - * @param value - * allowed object is - * {@link Fault.RequestError.ServiceException.Variables } - * - */ - public void setVariables(Fault.RequestError.ServiceException.Variables value) { - this.variables = value; - } - - - /** - *

    Java class for anonymous complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    -             * <complexType>
    -             *   <complexContent>
    -             *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    -             *       <sequence>
    -             *         <element name="variable" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/>
    -             *       </sequence>
    -             *     </restriction>
    -             *   </complexContent>
    -             * </complexType>
    -             * 
    - * - * - */ - @XmlAccessorType(XmlAccessType.FIELD) - @XmlType(name = "", propOrder = { - "variable" - }) - public static class Variables { - - protected List variable; - - /** - * Gets the value of the variable property. - * - *

    - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the variable property. - * - *

    - * For example, to add a new item, do as follows: - *

    -                 *    getVariable().add(newItem);
    -                 * 
    - * - * - *

    - * Objects of the following type(s) are allowed in the list - * {@link String } - * - * @return the variable - */ - public List getVariable() { - if (variable == null) { - variable = new ArrayList(); - } - return this.variable; - } - - } - - } - - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/domain/restServiceException/ObjectFactory.java b/aai-core/src/main/java/org/openecomp/aai/domain/restServiceException/ObjectFactory.java deleted file mode 100644 index 09c59b3c..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/domain/restServiceException/ObjectFactory.java +++ /dev/null @@ -1,95 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2015.02.11 at 04:54:29 PM EST -// - - -package org.openecomp.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.openecomp.aai.domain.restServiceException package. - *

    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.openecomp.aai.domain.restServiceException - * - */ - public ObjectFactory() { - } - - /** - * Create an instance of {@link Fault }. - * - * @return the fault - */ - public Fault createFault() { - return new Fault(); - } - - /** - * Create an instance of {@link Fault.RequestError } - * - * @return the request error - */ - public Fault.RequestError createFaultRequestError() { - return new Fault.RequestError(); - } - - /** - * Create an instance of {@link Fault.RequestError.ServiceException } - * - * @return the service exception - */ - public Fault.RequestError.ServiceException createFaultRequestErrorServiceException() { - return new Fault.RequestError.ServiceException(); - } - - /** - * Create an instance of {@link Fault.RequestError.ServiceException.Variables } - * - * @return the variables - */ - public Fault.RequestError.ServiceException.Variables createFaultRequestErrorServiceExceptionVariables() { - return new Fault.RequestError.ServiceException.Variables(); - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/domain/restServiceException/RESTResponse.java b/aai-core/src/main/java/org/openecomp/aai/domain/restServiceException/RESTResponse.java deleted file mode 100644 index 9aa55f44..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/domain/restServiceException/RESTResponse.java +++ /dev/null @@ -1,86 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.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; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - -@JsonInclude(JsonInclude.Include.NON_NULL) -@Generated("org.jsonschema2pojo") -@JsonPropertyOrder({ - "requestError" -}) -public class RESTResponse { - - @JsonProperty("requestError") - private RequestError requestError; - @JsonIgnore - private Map additionalProperties = new HashMap(); - - /** - * Gets the request error. - * - * @return The requestError - */ - @JsonProperty("requestError") - public RequestError getRequestError() { - return requestError; - } - - /** - * Sets the request error. - * - * @param requestError The requestError - */ - @JsonProperty("requestError") - public void setRequestError(RequestError requestError) { - this.requestError = requestError; - } - - /** - * Gets the additional properties. - * - * @return the additional properties - */ - @JsonAnyGetter - public Map getAdditionalProperties() { - return this.additionalProperties; - } - - /** - * Sets the additional property. - * - * @param name the name - * @param value the value - */ - @JsonAnySetter - public void setAdditionalProperty(String name, Object value) { - this.additionalProperties.put(name, value); - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/domain/restServiceException/RequestError.java b/aai-core/src/main/java/org/openecomp/aai/domain/restServiceException/RequestError.java deleted file mode 100644 index edc465e8..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/domain/restServiceException/RequestError.java +++ /dev/null @@ -1,86 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.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; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - -@JsonInclude(JsonInclude.Include.NON_NULL) -@Generated("org.jsonschema2pojo") -@JsonPropertyOrder({ - "serviceException" -}) -public class RequestError { - - @JsonProperty("serviceException") - private ServiceException serviceException; - @JsonIgnore - private Map additionalProperties = new HashMap(); - - /** - * Gets the service exception. - * - * @return The serviceException - */ - @JsonProperty("serviceException") - public ServiceException getServiceException() { - return serviceException; - } - - /** - * Sets the service exception. - * - * @param serviceException The serviceException - */ - @JsonProperty("serviceException") - public void setServiceException(ServiceException serviceException) { - this.serviceException = serviceException; - } - - /** - * Gets the additional properties. - * - * @return the additional properties - */ - @JsonAnyGetter - public Map getAdditionalProperties() { - return this.additionalProperties; - } - - /** - * Sets the additional property. - * - * @param name the name - * @param value the value - */ - @JsonAnySetter - public void setAdditionalProperty(String name, Object value) { - this.additionalProperties.put(name, value); - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/domain/restServiceException/ServiceException.java b/aai-core/src/main/java/org/openecomp/aai/domain/restServiceException/ServiceException.java deleted file mode 100644 index 56872696..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/domain/restServiceException/ServiceException.java +++ /dev/null @@ -1,134 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.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; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - -@JsonInclude(JsonInclude.Include.NON_NULL) -@Generated("org.jsonschema2pojo") -@JsonPropertyOrder({ - "messageId", - "text", - "variables" -}) -public class ServiceException { - - @JsonProperty("messageId") - private String messageId; - @JsonProperty("text") - private String text; - @JsonProperty("variables") - private List variables = new ArrayList(); - @JsonIgnore - private Map additionalProperties = new HashMap(); - - /** - * Gets the message id. - * - * @return The messageId - */ - @JsonProperty("messageId") - public String getMessageId() { - return messageId; - } - - /** - * Sets the message id. - * - * @param messageId The messageId - */ - @JsonProperty("messageId") - public void setMessageId(String messageId) { - this.messageId = messageId; - } - - /** - * Gets the text. - * - * @return The text - */ - @JsonProperty("text") - public String getText() { - return text; - } - - /** - * Sets the text. - * - * @param text The text - */ - @JsonProperty("text") - public void setText(String text) { - this.text = text; - } - - /** - * Gets the variables. - * - * @return The variables - */ - @JsonProperty("variables") - public List getVariables() { - return variables; - } - - /** - * Sets the variables. - * - * @param variables The variables - */ - @JsonProperty("variables") - public void setVariables(List variables) { - this.variables = variables; - } - - /** - * Gets the additional properties. - * - * @return the additional properties - */ - @JsonAnyGetter - public Map getAdditionalProperties() { - return this.additionalProperties; - } - - /** - * Sets the additional property. - * - * @param name the name - * @param value the value - */ - @JsonAnySetter - public void setAdditionalProperty(String name, Object value) { - this.additionalProperties.put(name, value); - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/domain/translog/TransactionLogEntries.java b/aai-core/src/main/java/org/openecomp/aai/domain/translog/TransactionLogEntries.java deleted file mode 100644 index 83f5b356..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/domain/translog/TransactionLogEntries.java +++ /dev/null @@ -1,131 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2015.03.20 at 09:46:47 AM CDT -// - - -package org.openecomp.aai.domain.translog; - -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.XmlRootElement; -import javax.xml.bind.annotation.XmlType; - - -/** - *

    Java class for anonymous complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType>
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *       <sequence>
    - *         <element name="update" minOccurs="0">
    - *           <complexType>
    - *             <complexContent>
    - *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *                 <sequence>
    - *                   <element name="update-node-type" type="{http://www.w3.org/2001/XMLSchema}string"/>
    - *                   <element name="update-node-key" maxOccurs="unbounded" minOccurs="0">
    - *                     <complexType>
    - *                       <complexContent>
    - *                         <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *                           <sequence>
    - *                             <element name="key-name" type="{http://www.w3.org/2001/XMLSchema}string"/>
    - *                             <element name="key-value" type="{http://www.w3.org/2001/XMLSchema}string"/>
    - *                             <any processContents='lax' namespace='##other' maxOccurs="unbounded" minOccurs="0"/>
    - *                           </sequence>
    - *                         </restriction>
    - *                       </complexContent>
    - *                     </complexType>
    - *                   </element>
    - *                   <element name="action" maxOccurs="unbounded" minOccurs="0">
    - *                     <complexType>
    - *                       <complexContent>
    - *                         <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *                           <sequence>
    - *                             <element name="action-type" type="{http://www.w3.org/2001/XMLSchema}string"/>
    - *                             <element name="action-data" maxOccurs="unbounded" minOccurs="0">
    - *                               <complexType>
    - *                                 <complexContent>
    - *                                   <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *                                     <sequence>
    - *                                       <element name="property-name" type="{http://www.w3.org/2001/XMLSchema}string"/>
    - *                                       <element name="property-value" type="{http://www.w3.org/2001/XMLSchema}string"/>
    - *                                       <any processContents='lax' namespace='##other' maxOccurs="unbounded" minOccurs="0"/>
    - *                                     </sequence>
    - *                                   </restriction>
    - *                                 </complexContent>
    - *                               </complexType>
    - *                             </element>
    - *                             <any processContents='lax' namespace='##other' maxOccurs="unbounded" minOccurs="0"/>
    - *                           </sequence>
    - *                         </restriction>
    - *                       </complexContent>
    - *                     </complexType>
    - *                   </element>
    - *                   <any processContents='lax' namespace='##other' maxOccurs="unbounded" minOccurs="0"/>
    - *                 </sequence>
    - *               </restriction>
    - *             </complexContent>
    - *           </complexType>
    - *         </element>
    - *         <any processContents='lax' namespace='##other' maxOccurs="unbounded" minOccurs="0"/>
    - *       </sequence>
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "transactionLogEntries" -}) -@XmlRootElement(name = "transaction-log-entries", namespace = "http://org.openecomp.aai.inventory") -public class TransactionLogEntries { - - protected List transactionLogEntries; - - /** - * Gets the transaction log entries. - * - * @return the transaction log entries - */ - public List getTransactionLogEntries() { - if (transactionLogEntries == null) { - transactionLogEntries = new ArrayList(); - } - return this.transactionLogEntries; - } - - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/domain/translog/TransactionLogEntry.java b/aai-core/src/main/java/org/openecomp/aai/domain/translog/TransactionLogEntry.java deleted file mode 100644 index c3724e34..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/domain/translog/TransactionLogEntry.java +++ /dev/null @@ -1,438 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.domain.translog; - -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; - -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" -}) -@XmlRootElement(name = "transaction-log-entry", namespace = "http://org.openecomp.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; - } - - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/exceptions/AAIException.java b/aai-core/src/main/java/org/openecomp/aai/exceptions/AAIException.java deleted file mode 100644 index e3bce33d..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/exceptions/AAIException.java +++ /dev/null @@ -1,146 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.exceptions; - -import java.util.Collection; -import java.util.LinkedList; - -import org.openecomp.aai.logging.ErrorLogHelper; -import org.openecomp.aai.logging.ErrorObject; -import org.openecomp.aai.logging.ErrorObjectNotFoundException; - -public class AAIException extends Exception { - - public static final String DEFAULT_EXCEPTION_CODE = "AAI_4000"; - private static final long serialVersionUID = 1L; - - private final String code; - private final ErrorObject errorObject; - private final Collection templateVars; - - /** - * Instantiates a new AAI exception. - */ - public AAIException() { - super(); - this.code = DEFAULT_EXCEPTION_CODE; - this.templateVars = new LinkedList (); - - try { - this.errorObject = ErrorLogHelper.getErrorObject(getCode()); - } catch (ErrorObjectNotFoundException e) { - throw new RuntimeException("Failed to instantiate AAIException with code=" + getCode() - + " - update error.properties before using this exception code"); - } - } - - /** - * Instantiates a new AAI exception. - * - * @param code the code - */ - public AAIException(String code) { - super(); - - this.code = code; - this.templateVars = new LinkedList (); - - try { - this.errorObject = ErrorLogHelper.getErrorObject(getCode()); - } catch (ErrorObjectNotFoundException e) { - throw new RuntimeException("Failed to instantiate AAIException with code=" + getCode() - + " - update error.properties before using this exception code"); - } - } - - /** - * Instantiates a new AAI exception. - * - * @param code the code - * @param details the details - */ - public AAIException(String code, String details) { - super(details); - - this.code = code; - this.templateVars = new LinkedList (); - - try { - this.errorObject = ErrorLogHelper.getErrorObject(getCode()); - } catch (ErrorObjectNotFoundException e) { - throw new RuntimeException("Failed to instantiate AAIException with code=" + getCode() - + " - update error.properties before using this exception code"); - } - } - - /** - * Instantiates a new AAI exception. - * - * @param code the code - * @param cause the cause - */ - public AAIException(String code, Throwable cause) { - super(cause); - - this.code = code; - this.templateVars = new LinkedList (); - - try { - this.errorObject = ErrorLogHelper.getErrorObject(getCode()); - } catch (ErrorObjectNotFoundException e) { - throw new RuntimeException("Failed to instantiate AAIException with code=" + getCode() - + " - update error.properties before using this exception code"); - } - } - - /** - * Instantiates a new AAI exception. - * - * @param code the code - * @param cause the cause - * @param details the details - */ - public AAIException(String code, Throwable cause, String details) { - super(details, cause); - - this.code = code; - this.templateVars = new LinkedList (); - - try { - this.errorObject = ErrorLogHelper.getErrorObject(getCode()); - } catch (ErrorObjectNotFoundException e) { - throw new RuntimeException("Failed to instantiate AAIException with code=" + getCode() - + " - update error.properties before using this exception code"); - } - } - - public String getCode() { - return code; - } - - public ErrorObject getErrorObject() { - return errorObject; - } - - public Collection getTemplateVars() { - return templateVars; - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/exceptions/AAIExceptionWithInfo.java b/aai-core/src/main/java/org/openecomp/aai/exceptions/AAIExceptionWithInfo.java deleted file mode 100644 index f1b15396..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/exceptions/AAIExceptionWithInfo.java +++ /dev/null @@ -1,134 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.exceptions; - -import java.util.HashMap; - -public class AAIExceptionWithInfo extends AAIException { - - HashMap infoHash; - String info; - - /** - * Instantiates a new AAI exception with info. - * - * @param infoHash the info hash - * @param info the info - */ - public AAIExceptionWithInfo(HashMap 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 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 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 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 infoHash, String info) { - super(code, cause, details); - setInfoHash(infoHash); - setInfo(info); - } - - /** - * Gets the info hash. - * - * @return the info hash - */ - public HashMap getInfoHash() { - return infoHash; - } - - /** - * Sets the info hash. - * - * @param infoHash the info hash - */ - public void setInfoHash(HashMap infoHash) { - this.infoHash = infoHash; - } - - /** - * 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; - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/extensions/AAIExtensionMap.java b/aai-core/src/main/java/org/openecomp/aai/extensions/AAIExtensionMap.java deleted file mode 100644 index 11a8920a..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/extensions/AAIExtensionMap.java +++ /dev/null @@ -1,825 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.extensions; - -import org.apache.tinkerpop.gremlin.structure.Graph; -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext; -import org.openecomp.aai.domain.responseMessage.AAIResponseMessages; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.rest.db.DBRequest; -import org.openecomp.aai.rest.db.HttpEntry; -import org.openecomp.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 (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.openecomp.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 | com.thinkaurelius.titan.core.TitanGraph (RW) - // ----------------------------------------------------------------------- - // objectFromResponse | Object - // ----------------------------------------------------------------------- - // precheckAddedList | java.util.HashMap - // ----------------------------------------------------------------------- - // precheckResponseMessages | org.openecomp.aai.extensions.AAIResponseMessages - // ======================================================================= - - private String message; - private ArrayList 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 lookupHashMap; - private HashMap> precheckAddedList; - private AAIResponseMessages precheckResponseMessages; - private HashMap topology; - private HashMap 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 _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 getTemplateVars() { - if (this.templateVars == null) { - this.templateVars = new ArrayList(); - } - 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 getLookupHashMap() { - if (this.lookupHashMap == null) { - this.lookupHashMap = new HashMap(); - } - return this.lookupHashMap; - } - - /** - * Sets the lookup hash map. - * - * @param lookupHashMap the lookup hash map - */ - public void setLookupHashMap(HashMap lookupHashMap) { - this.lookupHashMap = lookupHashMap; - } - - /** - * Gets the precheck added list. - * - * @return the precheck added list - */ - public HashMap> getPrecheckAddedList() { - if (this.precheckAddedList == null) { - this.precheckAddedList = new HashMap>(); - } - return precheckAddedList; - } - - /** - * Sets the precheck added list. - * - * @param precheckAddedList the precheck added list - */ - public void setPrecheckAddedList(HashMap> 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 getTopology() { - if (this.topology == null) { - this.topology = new HashMap(); - } - return topology; - } - - /** - * Gets the vertex cache. - * - * @return the vertex cache - */ - public HashMap getVertexCache() { - if (this.vertexCache == null) { - this.vertexCache = new HashMap(); - } - 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/openecomp/aai/extensions/ExtensionController.java b/aai-core/src/main/java/org/openecomp/aai/extensions/ExtensionController.java deleted file mode 100644 index cea0e9b7..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/extensions/ExtensionController.java +++ /dev/null @@ -1,145 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.extensions; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.util.AAIConfig; - -import java.lang.reflect.Method; - -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.openecomp.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/openecomp/aai/ingestModel/CreateWidgetModels.java b/aai-core/src/main/java/org/openecomp/aai/ingestModel/CreateWidgetModels.java deleted file mode 100644 index 885f2854..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/ingestModel/CreateWidgetModels.java +++ /dev/null @@ -1,144 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.ingestModel; - -import java.io.File; -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.List; -import java.util.Map.Entry; -import java.util.UUID; - -import javax.xml.transform.stream.StreamSource; - -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.introspection.LoaderFactory; -import org.openecomp.aai.introspection.ModelType; -import org.openecomp.aai.introspection.Version; -import org.openecomp.aai.util.AAIConfig; -import org.openecomp.aai.util.AAIConstants; - -/** - * 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); - } - - - Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.valueOf(_apiVersion)); - - // iterate the collection of resources - - ArrayList processedWidgets = new ArrayList(); - for (Entry 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; - } - 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 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/openecomp/aai/introspection/Introspector.java b/aai-core/src/main/java/org/openecomp/aai/introspection/Introspector.java deleted file mode 100644 index 1c8baa10..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/Introspector.java +++ /dev/null @@ -1,617 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.introspection; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.google.common.base.CaseFormat; -import org.apache.commons.lang.ClassUtils; -import org.eclipse.persistence.exceptions.DynamicException; -import org.openecomp.aai.introspection.exceptions.AAIUnknownObjectException; -import org.openecomp.aai.logging.ErrorLogHelper; -import org.openecomp.aai.restcore.MediaType; -import org.openecomp.aai.schema.enums.ObjectMetadata; -import org.openecomp.aai.schema.enums.PropertyMetadata; -import org.openecomp.aai.workarounds.NamingExceptions; - -import java.io.UnsupportedEncodingException; -import java.lang.reflect.InvocationTargetException; -import java.util.*; - -public abstract class Introspector implements Cloneable { - - 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 uniqueProperties = null; - private Set indexedProperties = null; - private Set allKeys = null; - protected Introspector(Object obj) { - } - - public abstract boolean hasProperty(String name); - - protected String convertPropertyName (String name) { - return CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, 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 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) { - - } - } - - 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) { - - } - } - if (value != null) { - return IntrospectorFactory.newInstance(this.getModelType(), value); - } else { - //no value - return null; - } - - } - - public List getWrappedListValue(String name) { - String convertedName = convertPropertyName(name); - Object value = null; - List 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) { - - } - } - - List valueList = (List)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 castValueAccordingToSchema(String name, List objs) { - List 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) throws IllegalArgumentException { - 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 getProperties(); - - public Set getProperties(PropertyPredicate p) { - final Set temp = new LinkedHashSet<>(); - this.getProperties().stream().filter(item -> { - return p.test(this, item); - }).forEach(item -> { - temp.add(item); - }); - final Set result = Collections.unmodifiableSet(temp); - - return result; - - } - /** - * - * @return a list of the required properties on the object - */ - public abstract Set getRequiredProperties(); - /** - * - * @return a list of the properties that can be used to query the object in the db - */ - public abstract Set getKeys(); - /** - * - * @return a list of the all key properties for this object - */ - public Set getAllKeys() { - Set result = null; - if (this.allKeys == null) { - Set 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 getIndexedProperties() { - Set result = null; - - if (this.indexedProperties == null) { - result = new LinkedHashSet<>(); - Set 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 getUniqueProperties() { - Set 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 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 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)", 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 clone(); - - 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 getPropertyMetadata(String propName); - public Optional getPropertyMetadata(String propName, PropertyMetadata metadataName) { - final String resultValue = this.getPropertyMetadata(propName).getOrDefault(metadataName, ""); - Optional result = Optional.empty(); - - if (!resultValue.isEmpty()) { - result = Optional.of(resultValue); - } - return result; - - } - - public abstract Version 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/openecomp/aai/introspection/IntrospectorFactory.java b/aai-core/src/main/java/org/openecomp/aai/introspection/IntrospectorFactory.java deleted file mode 100644 index 760f3a68..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/IntrospectorFactory.java +++ /dev/null @@ -1,65 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.introspection; - -public class IntrospectorFactory { - - /** - * New instance. - * - * @param type the type - * @param o the o - * @param llBuilder the ll builder - * @return the introspector - */ - public static Introspector newInstance(ModelType type, Object o) { - - if (type.equals(ModelType.MOXY)) { - return new MoxyStrategy(o); - } else if (type.equals(ModelType.POJO)) { - return new PojoStrategy(o); - } else if (type.equals(ModelType.JSON)) { - return new JSONStrategy(o); - } else { - throw new IllegalArgumentException("Unknown class type: " + type); - } - - } - - /** - * New instance. - * - * @param type the type - * @param o the o - * @param namedType the named type - * @param llBuilder the ll builder - * @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/openecomp/aai/introspection/IntrospectorWalker.java b/aai-core/src/main/java/org/openecomp/aai/introspection/IntrospectorWalker.java deleted file mode 100644 index 8eddac3b..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/IntrospectorWalker.java +++ /dev/null @@ -1,193 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.introspection; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.exceptions.AAIUnknownObjectException; - -import java.util.HashSet; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Set; - -public class IntrospectorWalker { - - private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(IntrospectorWalker.class); - - private Wanderer w = null; - private Set blacklist = null; - private boolean preventCycles = false; - private final PropertyPredicate 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 p) { - this.w = w; - this.blacklist = new HashSet<>(); - this.propVisibility = p; - } - - - /** - * Sets the blacklist. - * - * @param list the new blacklist - */ - public void setBlacklist(List 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 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 visited) throws AAIException { - boolean stopRecursion = false; - Set 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 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 listReference = obj.getValue(prop); - boolean isComplexType = obj.isComplexGenericType(prop); - if (isComplexType) { - List 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)", 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)", 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)", 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/openecomp/aai/introspection/JSONStrategy.java b/aai-core/src/main/java/org/openecomp/aai/introspection/JSONStrategy.java deleted file mode 100644 index 7dae20ee..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/JSONStrategy.java +++ /dev/null @@ -1,359 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.introspection; - -import org.json.simple.JSONObject; -import org.openecomp.aai.schema.enums.ObjectMetadata; -import org.openecomp.aai.schema.enums.PropertyMetadata; - -import java.io.UnsupportedEncodingException; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.UUID; - -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 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 getProperties() { - Set result = json.keySet(); - return result; - } - - @Override - public Set getRequiredProperties() { - //unknowable - - return this.getProperties(); - } - - @Override - public Set getKeys() { - //unknowable - return this.getProperties(); - } - - @Override - public Set 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 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 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 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 Version getVersion() { - // TODO Auto-generated method stub - return null; - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/Loader.java b/aai-core/src/main/java/org/openecomp/aai/introspection/Loader.java deleted file mode 100644 index b5a029ed..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/Loader.java +++ /dev/null @@ -1,112 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.introspection; - -import org.openecomp.aai.introspection.exceptions.AAIUnknownObjectException; -import org.openecomp.aai.introspection.exceptions.AAIUnmarshallingException; -import org.openecomp.aai.restcore.MediaType; - -import java.util.Map; - -public abstract class Loader { - - private final Version version; - private final ModelType modelType; - - /** - * Instantiates a new loader. - * - * @param version the version - * @param modelType the model type - * @param llBuilder the ll builder - */ - public Loader (Version version, ModelType modelType) { - this.version = version; - this.modelType = modelType; - } - - /** - * Process. - * - * @param version the version - */ - protected abstract void process(Version version); - - /** - * Object from name. - * - * @param name the name - * @return the object - * @throws AAIUnknownObjectException - */ - public abstract Object objectFromName(String name) throws AAIUnknownObjectException; - - /** - * 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 - * @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 version. - * - * @return the version - */ - public Version getVersion() { - return this.version; - } - - public abstract Map getAllObjects(); -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/LoaderFactory.java b/aai-core/src/main/java/org/openecomp/aai/introspection/LoaderFactory.java deleted file mode 100644 index 23b762d5..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/LoaderFactory.java +++ /dev/null @@ -1,44 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.introspection; - -public class LoaderFactory { - - /** - * Creates a new Loader object. - * - * @param type the type - * @param version the version - * @param llBuilder the ll builder - * @return the loader - */ - public static Loader createLoaderForVersion(ModelType type, Version version) { - - if (type.equals(ModelType.MOXY)) { - return new MoxyLoader(version); - } else if (type.equals(ModelType.POJO)) { - return new PojoLoader(version); - } - - return null; - - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/MarshallerProperties.java b/aai-core/src/main/java/org/openecomp/aai/introspection/MarshallerProperties.java deleted file mode 100644 index 8b9ee2d7..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/MarshallerProperties.java +++ /dev/null @@ -1,139 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.introspection; - -import org.openecomp.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); - } - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/ModelInjestor.java b/aai-core/src/main/java/org/openecomp/aai/introspection/ModelInjestor.java deleted file mode 100644 index c6503a69..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/ModelInjestor.java +++ /dev/null @@ -1,173 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.introspection; - -import org.eclipse.persistence.dynamic.DynamicType; -import org.eclipse.persistence.jaxb.JAXBContextProperties; -import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext; -import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContextFactory; -import org.openecomp.aai.util.AAIConstants; - -import javax.xml.bind.JAXBException; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.InputStream; -import java.util.HashMap; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class ModelInjestor { - - private Map versionContextMap = new HashMap<>(); - private static final Pattern classNamePattern = Pattern.compile("\\.(v\\d+)\\."); - private static final Pattern uriPattern = Pattern.compile("(v\\d+)\\/"); - - - /** - * Instantiates a new model injestor. - */ - private ModelInjestor() { - try { - injestModels(); - } catch (FileNotFoundException | JAXBException e) { - throw new RuntimeException(e); - } - } - - private static class Helper { - private static final ModelInjestor INSTANCE = new ModelInjestor(); - } - - /** - * Gets the single instance of ModelInjestor. - * - * @return single instance of ModelInjestor - */ - public synchronized static ModelInjestor getInstance() { - return Helper.INSTANCE; - } - - /** - * Injest models. - * - * @throws FileNotFoundException the file not found exception - * @throws JAXBException the JAXB exception - */ - private void injestModels() throws FileNotFoundException, JAXBException { - - for (Version version : Version.values()) { - this.injestModel(version); - } - } - - /** - * Injest model. - * - * @param version the version - * @throws JAXBException the JAXB exception - * @throws FileNotFoundException the file not found exception - */ - private void injestModel (Version version) throws JAXBException, FileNotFoundException { - String fileName = this.getOXMFileName(version); - InputStream iStream = new FileInputStream(new File(fileName)); - Map properties = new HashMap(); - properties.put(JAXBContextProperties.OXM_METADATA_SOURCE, iStream); - final DynamicJAXBContext jaxbContext = DynamicJAXBContextFactory.createContextFromOXM(this.getClass().getClassLoader(), properties); - versionContextMap.put(version, jaxbContext); - } - - /** - * Gets the version from class name. - * - * @param classname the classname - * @return the version from class name - */ - public Version getVersionFromClassName (String classname) { - Matcher m = classNamePattern.matcher(classname); - String version = "v2"; //for the OXM, only the v2 ones don't include a model name, hence this default - if (m.find()) { - version = m.group(1); - } - - return Version.valueOf(version); - } - - /** - * Gets the context for URI. - * - * @param uri the uri - * @return the context for URI - */ - public DynamicJAXBContext getContextForURI(String uri) { - DynamicJAXBContext result = null; - Matcher m = uriPattern.matcher(uri); - Version version = null; - if (m.find()) { - version = Version.valueOf(m.group(1)); - result = versionContextMap.get(version); - } - - return result; - } - - /** - * Gets the context for version. - * - * @param version the version - * @return the context for version - */ - public DynamicJAXBContext getContextForVersion(Version version) { - DynamicJAXBContext result = null; - - result = versionContextMap.get(version); - - - return result; - } - - /** - * Gets the dynamic type for class name. - * - * @param classname the classname - * @return the dynamic type for class name - */ - public DynamicType getDynamicTypeForClassName(String classname) { - DynamicType result = null; - DynamicJAXBContext context = null; - - Version version = this.getVersionFromClassName(classname); - - context = versionContextMap.get(version); - - if (context != null) { - result = context.getDynamicType(classname); - } - - return result; - } - - public String getOXMFileName(Version v) { - return AAIConstants.AAI_HOME_ETC_OXM + "aai_oxm_" + v.toString() + ".xml"; - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/ModelType.java b/aai-core/src/main/java/org/openecomp/aai/introspection/ModelType.java deleted file mode 100644 index 132b754b..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/ModelType.java +++ /dev/null @@ -1,25 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.introspection; - -public enum ModelType { - MOXY, POJO, JSON -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/MoxyLoader.java b/aai-core/src/main/java/org/openecomp/aai/introspection/MoxyLoader.java deleted file mode 100644 index 80b05aee..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/MoxyLoader.java +++ /dev/null @@ -1,195 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.introspection; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.google.common.base.CaseFormat; -import com.google.common.collect.ImmutableMap; -import org.eclipse.persistence.dynamic.DynamicEntity; -import org.eclipse.persistence.jaxb.UnmarshallerProperties; -import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.exceptions.AAIUnknownObjectException; -import org.openecomp.aai.introspection.exceptions.AAIUnmarshallingException; -import org.openecomp.aai.logging.ErrorLogHelper; -import org.openecomp.aai.restcore.MediaType; -import org.openecomp.aai.workarounds.NamingExceptions; -import org.w3c.dom.Document; -import org.w3c.dom.NodeList; -import org.xml.sax.SAXException; - -import javax.xml.XMLConstants; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Unmarshaller; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.stream.StreamSource; -import java.io.IOException; -import java.io.StringReader; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -public class MoxyLoader extends Loader { - - private DynamicJAXBContext jaxbContext = null; - private EELFLogger LOGGER = EELFManager.getInstance().getLogger(MoxyLoader.class); - private Map allObjs = null; - - /** - * Instantiates a new moxy loader. - * - * @param version the version - * @param llBuilder the ll builder - */ - protected MoxyLoader(Version version) { - super(version, ModelType.MOXY); - process(version); - } - - /** - * {@inheritDoc} - * @throws AAIUnknownObjectException - */ - @Override - public Introspector introspectorFromName(String name) throws AAIUnknownObjectException { - - return IntrospectorFactory.newInstance(ModelType.MOXY, objectFromName(name)); - } - - /** - * {@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 (name.matches(".*[A-Z].*")) { - upperCamel = sanitizedName; - } else { - upperCamel = 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(Version version) { - ModelInjestor injestor = ModelInjestor.getInstance(); - jaxbContext = injestor.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 getAllObjects() { - if (this.allObjs != null) { - return allObjs; - } else { - ImmutableMap.Builder map = new ImmutableMap.Builder(); - Set 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()", e); - } - } - allObjs = map.build(); - return allObjs; - } - } - - private Set objectsInVersion() { - final Set result = new HashSet<>(); - - try { - final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); - final String fileName = ModelInjestor.getInstance().getOXMFileName(getVersion()); - - docFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); - - final DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); - final Document doc = docBuilder.parse(fileName); - final NodeList list = doc.getElementsByTagName("java-type"); - - for (int i = 0; i < list.getLength(); i++) { - result.add(list.item(i).getAttributes().getNamedItem("name").getNodeValue()); - } - } catch (ParserConfigurationException | SAXException | IOException e) { - LOGGER.warn("Exception while enumerating objects for API version " + getVersion() + " (returning partial results)", e); - } - - //result.remove("EdgePropNames"); - return result; - } - - public DynamicJAXBContext getJAXBContext() { - return this.jaxbContext; - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/MoxyStrategy.java b/aai-core/src/main/java/org/openecomp/aai/introspection/MoxyStrategy.java deleted file mode 100644 index b3cda8d3..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/MoxyStrategy.java +++ /dev/null @@ -1,385 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.introspection; - -import com.google.common.base.CaseFormat; -import com.google.common.base.Joiner; -import org.eclipse.persistence.descriptors.ClassDescriptor; -import org.eclipse.persistence.dynamic.DynamicEntity; -import org.eclipse.persistence.dynamic.DynamicType; -import org.eclipse.persistence.exceptions.DynamicException; -import org.eclipse.persistence.jaxb.UnmarshallerProperties; -import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext; -import org.eclipse.persistence.mappings.DatabaseMapping; -import org.eclipse.persistence.oxm.XMLField; -import org.eclipse.persistence.oxm.mappings.XMLCompositeCollectionMapping; -import org.eclipse.persistence.oxm.mappings.XMLCompositeDirectCollectionMapping; -import org.openecomp.aai.restcore.MediaType; -import org.openecomp.aai.schema.enums.ObjectMetadata; -import org.openecomp.aai.schema.enums.PropertyMetadata; -import org.springframework.web.util.UriUtils; - -import javax.xml.bind.JAXBException; -import javax.xml.bind.Marshaller; -import javax.xml.bind.Unmarshaller; -import javax.xml.transform.stream.StreamSource; -import java.io.StringReader; -import java.io.StringWriter; -import java.io.UnsupportedEncodingException; -import java.util.*; -import java.util.Map.Entry; - -public class MoxyStrategy extends Introspector { - - private DynamicEntity internalObject = null; - private DynamicType internalType = null; - private DynamicJAXBContext jaxbContext = null; - private ClassDescriptor cd = null; - private Marshaller marshaller = null; - private Unmarshaller unmarshaller = null; - private Version version = null; - private Set properties = null; - private Set keys = null; - private Set 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; - ModelInjestor injestor = ModelInjestor.getInstance(); - version = injestor.getVersionFromClassName(internalObject.getClass().getName()); - jaxbContext = injestor.getContextForVersion(version); - super.loader = LoaderFactory.createLoaderForVersion(getModelType(), version); - String simpleName = internalObject.getClass().getName(); - internalType = jaxbContext.getDynamicType(simpleName); - cd = internalType.getDescriptor(); - try { - marshaller = jaxbContext.createMarshaller(); - unmarshaller = jaxbContext.createUnmarshaller(); - } catch (JAXBException e) { - - } - - } - - private void init() { - isInitialized = true; - - Set props = new LinkedHashSet<>(); - for (String s : internalType.getPropertiesNames()) { - props.add(CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_HYPHEN, s)); - - } - props = Collections.unmodifiableSet(props); - this.properties = props; - - Set requiredProps = new LinkedHashSet<>(); - requiredProps = new LinkedHashSet<>(); - for (DatabaseMapping dm : cd.getMappings()) { - if (dm.getField() instanceof XMLField) { - XMLField x = (XMLField)dm.getField(); - if (x != null) { - if (x.isRequired()) { - requiredProps.add(this.removeXPathDescriptor(x.getName())); - } - } - } - } - requiredProps = Collections.unmodifiableSet(requiredProps); - this.requiredProperties = requiredProps; - - Set 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) throws IllegalArgumentException { - - internalObject.set(name, obj); - } - - @Override - public Set getProperties() { - - if(!isInitialized){ - init(); - } - - return this.properties; - - } - - @Override - public Set getRequiredProperties() { - - if(!isInitialized){ - init(); - } - - return this.requiredProperties; - } - - @Override - public Set getKeys() { - - if(!isInitialized){ - init(); - } - - return this.keys; - } - - @Override - public Map getPropertyMetadata(String prop) { - String propName = this.convertPropertyName(prop); - DatabaseMapping mapping = cd.getMappingForAttributeName(propName); - Map result = new HashMap<>(); - if (mapping != null) { - Set 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 = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, className); - - if (this.isContainer()) { - lowerHyphen = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN,this.getGenericTypeClass(this.getProperties().iterator().next()).getSimpleName()); - } - - return lowerHyphen; - } - - @Override - public String getName() { - String className = internalObject.getClass().getSimpleName(); - String lowerHyphen = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, className); - /* - if (this.isContainer()) { - lowerHyphen = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN,this.getGenericTypeClass(this.getProperties().get(0)).getSimpleName()); - }*/ - - - return lowerHyphen; - } - - @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 keys = null; - keys = this.getKeys(); - List results = new ArrayList<>(); - for (String key : keys) { - if (this.getType(key).toLowerCase().contains("long")) { - key = ((Long)this.getValue(key)).toString(); - } else { - key = (String)this.getValue(key); - } - key = UriUtils.encode(key, "UTF-8"); - - results.add(key); - } - - return Joiner.on("/").join(results); - } - - @Override - public String preProcessKey (String key) { - String result = ""; - //String trimmedRestURI = restURI.replaceAll("/[\\w\\-]+?/[\\w\\-]+?$", ""); - 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 { - 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) { - //e.printStackTrace(); - } - - return result.toString(); - } - - @Override - public Object clone() { - Object result = null; - try { - unmarshaller = jaxbContext.createUnmarshaller(); - - unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); - unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); - unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); - - result = unmarshaller.unmarshal(new StreamSource(new StringReader(this.marshal(true))), this.internalObject.getClass()).getValue(); - } catch (JAXBException e) { - // TODO Auto-generated catch block - //e.printStackTrace(); - } - result = IntrospectorFactory.newInstance(getModelType(), result); - return result; - } - @Override - public ModelType getModelType() { - return ModelType.MOXY; - } - - private String removeXPathDescriptor(String name) { - - return name.replaceAll("/text\\(\\)", ""); - } - - @Override - public String getMetadata(ObjectMetadata name) { - - return (String)cd.getProperty(name.toString()); - } - - @Override - public Version getVersion() { - - return this.version; - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/PojoInjestor.java b/aai-core/src/main/java/org/openecomp/aai/introspection/PojoInjestor.java deleted file mode 100644 index 3eea2420..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/PojoInjestor.java +++ /dev/null @@ -1,67 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.introspection; - -import org.eclipse.persistence.jaxb.JAXBContextFactory; -import org.openecomp.aai.db.props.AAIProperties; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class PojoInjestor { - - private String POJO_CLASSPATH = "org.openecomp.aai.domain.yang"; - private final Pattern classNamePattern = Pattern.compile("\\.(v\\d+)\\."); - - public PojoInjestor() { - } - - public JAXBContext getContextForVersion(Version v) { - JAXBContext context = null; - try { - if (!v.equals(AAIProperties.LATEST)) { - POJO_CLASSPATH += "." + v; - } - context = JAXBContextFactory.createContext(POJO_CLASSPATH, this.getClass().getClassLoader()); - } catch (JAXBException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - return context; - } - public Version getVersion (String classname) { - Matcher m = classNamePattern.matcher(classname); - String version; - if (m.find()) { - version = m.group(1); - } else { - //only POJOs of old versions have the version number in their classnames - //so if we can't find a version, default to the latest - version = AAIProperties.LATEST.toString(); - } - - return Version.valueOf(version); - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/PojoLoader.java b/aai-core/src/main/java/org/openecomp/aai/introspection/PojoLoader.java deleted file mode 100644 index 927ac4bc..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/PojoLoader.java +++ /dev/null @@ -1,137 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.introspection; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.google.common.base.CaseFormat; -import org.eclipse.persistence.jaxb.JAXBContextFactory; -import org.eclipse.persistence.jaxb.UnmarshallerProperties; -import org.openecomp.aai.db.props.AAIProperties; -import org.openecomp.aai.introspection.exceptions.AAIUnknownObjectException; -import org.openecomp.aai.introspection.exceptions.AAIUnmarshallingException; -import org.openecomp.aai.logging.ErrorLogHelper; -import org.openecomp.aai.restcore.MediaType; -import org.openecomp.aai.workarounds.NamingExceptions; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Unmarshaller; -import javax.xml.transform.stream.StreamSource; -import java.io.StringReader; -import java.util.Map; - -public class PojoLoader extends Loader { - - private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(PojoLoader.class); - private static final String POJO_BASE_PACKAGE_NAME = "org.openecomp.aai.domain.yang"; - - protected JAXBContext context; - private final String pojoPackageName; - - protected PojoLoader(Version version) { - super(version, ModelType.POJO); - - if (!version.equals(AAIProperties.LATEST)) { - pojoPackageName = POJO_BASE_PACKAGE_NAME + "." + version; - } else { - pojoPackageName = POJO_BASE_PACKAGE_NAME; - } - - try { - context = JAXBContextFactory.createContext(pojoPackageName, this.getClass().getClassLoader()); - } catch (JAXBException e) { - LOGGER.error("JAXBException while instantiation contect for PojoLoader", e); - } - } - - @Override - public Introspector introspectorFromName(String name) throws AAIUnknownObjectException { - return IntrospectorFactory.newInstance(ModelType.POJO, objectFromName(name)); - } - - @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 (sanitizedName.matches(".*[A-Z].*")) { - upperCamel = sanitizedName; - } else { - upperCamel = CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, sanitizedName); - } - - final String objectClassName; - - if (!upperCamel.contains(pojoPackageName)) { - objectClassName = pojoPackageName + "." + upperCamel; - } else { - objectClassName = upperCamel; - } - - try { - return Class.forName(objectClassName).newInstance(); - } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) { - throw new AAIUnknownObjectException("Unrecognized AAI object " + name); - } - } - - @Override - protected void process(Version version) { - LOGGER.warn("PojoLoader.process(Version) has not been implemented"); - } - - @Override - public Introspector unmarshal(String type, String json, MediaType mediaType) throws AAIUnmarshallingException { - - try { - final Unmarshaller unmarshaller = context.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 Object clazz = objectFromName(type); - final Object obj = unmarshaller.unmarshal(new StreamSource(new StringReader(json)), clazz.getClass()).getValue(); - - return IntrospectorFactory.newInstance(ModelType.POJO, obj); - } catch (JAXBException e) { - ErrorLogHelper.logError("AAI_4007", "Could not unmarshall: " + e.getMessage()); - throw new AAIUnmarshallingException("Could not unmarshall: " + e.getMessage()); - } catch (AAIUnknownObjectException e) { - throw new AAIUnmarshallingException("Could not unmarshall: " + e.getMessage(), e); - } - } - - @Override - public Map getAllObjects() { - //TODO - return null; - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/PojoStrategy.java b/aai-core/src/main/java/org/openecomp/aai/introspection/PojoStrategy.java deleted file mode 100644 index 7f114bd3..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/PojoStrategy.java +++ /dev/null @@ -1,376 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.introspection; - -import com.google.common.base.CaseFormat; -import com.google.common.base.Joiner; -import com.google.common.collect.Multimap; -import org.eclipse.persistence.jaxb.UnmarshallerProperties; -import org.openecomp.aai.annotations.Metadata; -import org.openecomp.aai.logging.ErrorLogHelper; -import org.openecomp.aai.restcore.MediaType; -import org.openecomp.aai.schema.enums.ObjectMetadata; -import org.openecomp.aai.schema.enums.PropertyMetadata; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Marshaller; -import javax.xml.bind.Unmarshaller; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.transform.stream.StreamSource; -import java.io.StringReader; -import java.io.StringWriter; -import java.lang.reflect.*; -import java.util.*; - -public class PojoStrategy extends Introspector { - - private Object internalObject = null; - private PojoInjestor injestor = null; - private Multimap keyProps = null; - private Metadata classLevelMetadata = null; - private Version version; - private JAXBContext jaxbContext; - private Marshaller marshaller; - private Unmarshaller unmarshaller; - private Set properties = null; - private Set keys = null; - private Set requiredProperties = null; - - private boolean isInitialized = false; - - protected PojoStrategy(Object obj) { - super(obj); - className = PojoStrategy.class.getSimpleName(); - this.internalObject = obj; - injestor = new PojoInjestor(); - classLevelMetadata = obj.getClass().getAnnotation(Metadata.class); - - version = injestor.getVersion(obj.getClass().getName()); - jaxbContext = injestor.getContextForVersion(version); - super.loader = LoaderFactory.createLoaderForVersion(getModelType(), version); - try { - marshaller = jaxbContext.createMarshaller(); - unmarshaller = jaxbContext.createUnmarshaller(); - } catch (JAXBException e) { - - } - - } - - private void init() { - - isInitialized = true; - - Set properties = new LinkedHashSet<>(); - Set keys = new LinkedHashSet<>(); - Set required = new LinkedHashSet<>(); - - Field[] fields = this.internalObject.getClass().getDeclaredFields(); - - for (Field field : fields) { - if (!field.getName().equals("any")) { - properties.add(covertFieldToOutputFormat(field.getName())); - Metadata annotation = field.getAnnotation(Metadata.class); - XmlElement xmlAnnotation = field.getAnnotation(XmlElement.class); - if (annotation != null) { - if (annotation.isKey()) { - keys.add(covertFieldToOutputFormat(field.getName())); - } - } - if (xmlAnnotation != null) { - if (xmlAnnotation.required()) { - required.add(covertFieldToOutputFormat(field.getName())); - } - } - } - } - properties = Collections.unmodifiableSet(properties); - this.properties = properties; - - keys = Collections.unmodifiableSet(keys); - this.keys = keys; - - required = Collections.unmodifiableSet(required); - this.requiredProperties = required; - - } - private String covertFieldToOutputFormat(String propName) { - return CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_HYPHEN, propName); - } - - @Override - public boolean hasProperty(String name) { - //TODO - return true; - } - - @Override - /** - * Gets the value of the property via reflection - */ - public Object get(String name) { - String getMethodName = "get" + CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, name); - try { - return this.internalObject.getClass().getDeclaredMethod(getMethodName).invoke(this.internalObject); - } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { - return null; - } - } - - @Override - public void set(String name, Object value) { - String setMethodName = "set" + CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, name); - try { - this.internalObject.getClass().getDeclaredMethod(setMethodName, value.getClass()).invoke(this.internalObject, value); - } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { - ErrorLogHelper.logError("AAI_4017", "Error setting name/value pair on POJO: " + e.getMessage()); - } - } - - @Override - public Set getProperties() { - - if(!isInitialized){ - this.init(); - } - return this.properties; - } - - - @Override - public Set getRequiredProperties() { - - if(!isInitialized) { - this.init(); - } - return this.requiredProperties; - } - - @Override - public Set getKeys() { - - if(!isInitialized){ - this.init(); - } - return this.keys; - } - - public Class getClass(String name) { - - Field field = null; - try { - field = this.internalObject.getClass().getDeclaredField(CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, name)); - } catch (NoSuchFieldException | SecurityException e) { - - return null; - } - - return field.getType(); - } - - public Class getGenericTypeClass(String name) { - - try { - String getMethodName = "get" + CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, name); - Method method = internalObject.getClass().getDeclaredMethod(getMethodName); - Type t = method.getGenericReturnType(); - if(t instanceof ParameterizedType) { - ParameterizedType pt = (ParameterizedType)t; - return ((Class)pt.getActualTypeArguments()[0]); - } else { - return null; - } - - } catch (Exception e) { - return null; - } - } - - @Override - public String getJavaClassName() { - return internalObject.getClass().getName(); - } - - @Override - public Object getUnderlyingObject() { - return this.internalObject; - } - - @Override - public String getName() { - String className = internalObject.getClass().getSimpleName(); - - return CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, className); - } - - @Override - protected String findKey() { - Set keys = null; - keys = this.getKeys(); - List results = new ArrayList<>(); - for (String key : keys) { - if (this.getType(key).toLowerCase().contains("long")) { - key = ((Long)this.getValue(key)).toString(); - } else { - key = (String)this.getValue(key); - } - results.add(key); - } - - return Joiner.on("/").join(results); - } - - @Override - public String marshal(MarshallerProperties properties) { - StringWriter result = new StringWriter(); - try { - 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(Marshaller.JAXB_FORMATTED_OUTPUT, properties.getFormatted()); - marshaller.marshal(this.internalObject, result); - } catch (JAXBException e) { - //e.printStackTrace(); - } - - return result.toString(); - } - - @Override - public Object clone() { - Object result = null; - try { - unmarshaller = jaxbContext.createUnmarshaller(); - - unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); - unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); - unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); - - result = unmarshaller.unmarshal(new StreamSource(new StringReader(this.marshal(true))), this.internalObject.getClass()).getValue(); - } catch (JAXBException e) { - // TODO Auto-generated catch block - //e.printStackTrace(); - } - result = IntrospectorFactory.newInstance(getModelType(), result); - return result; - } - - @Override - public String preProcessKey (String key) { - String result = ""; - //String trimmedRestURI = restURI.replaceAll("/[\\w\\-]+?/[\\w\\-]+?$", ""); - String[] split = key.split("/"); - int i = 0; - for (i = split.length-1; i >= 0; i--) { - - if (keyProps.containsKey(split[i])) { - break; - - } - - } - result = Joiner.on("/").join(Arrays.copyOfRange(split, 0, i)); - - return result; - - } - - @Override - public ModelType getModelType() { - return ModelType.POJO; - } - - @Override - public String getChildName() { - String className = internalObject.getClass().getSimpleName(); - String lowerHyphen = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, className); - - if (this.isContainer()) { - lowerHyphen = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN,this.getGenericTypeClass(this.getProperties().iterator().next()).getSimpleName()); - } - - return lowerHyphen; - } - - @Override - public Map getPropertyMetadata(String prop) { - Field f; - Map result = new HashMap<>(); - try { - f = internalObject.getClass().getField(prop); - Metadata m = f.getAnnotation(Metadata.class); - if (m != null) { - Field[] fields = m.getClass().getFields(); - String fieldName; - for (Field field : fields) { - fieldName = field.getName(); - if (fieldName.equals("isAbstract")) { - fieldName = "abstract"; - } else if (fieldName.equals("extendsFrom")) { - fieldName = "extends"; - } - fieldName = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, fieldName); - result.put(PropertyMetadata.valueOf(fieldName), (String)field.get(m)); - } - } - } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) { - // TODO Auto-generated catch block - } - - return result; - } - - @Override - public String getObjectId() { - // TODO Auto-generated method stub - return null; - } - - @Override - public String getMetadata(ObjectMetadata metadataName) { - String value = null; - String methodName; - if (ObjectMetadata.ABSTRACT.equals(metadataName)) { - methodName = "isAbstract"; - } else if (ObjectMetadata.EXTENDS.equals(metadataName)) { - methodName = "extendsFrom"; - } else { - methodName = metadataName.toString(); - } - - try { - value = (String)this.classLevelMetadata.getClass().getMethod(methodName).invoke(classLevelMetadata); - } catch (IllegalArgumentException | IllegalAccessException | SecurityException | InvocationTargetException | NoSuchMethodException e) { - //TODO - } - - return value; - } - - @Override - public Version getVersion() { - // TODO Auto-generated method stub - return null; - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/PropertyPredicate.java b/aai-core/src/main/java/org/openecomp/aai/introspection/PropertyPredicate.java deleted file mode 100644 index 38bdf82c..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/PropertyPredicate.java +++ /dev/null @@ -1,27 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.introspection; - -import java.util.function.BiPredicate; - -public interface PropertyPredicate extends BiPredicate { - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/PropertyPredicates.java b/aai-core/src/main/java/org/openecomp/aai/introspection/PropertyPredicates.java deleted file mode 100644 index c7bbb0c0..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/PropertyPredicates.java +++ /dev/null @@ -1,77 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.introspection; - -import org.openecomp.aai.schema.enums.PropertyMetadata; - -import java.util.Map; -import java.util.Set; - -public final class PropertyPredicates { - - private PropertyPredicates() { - - } - - public static PropertyPredicate includeInTestGeneration() { - return (obj, prop) -> { - final Map 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 isVisible() { - return (obj, prop) -> { - final Map map = obj.getPropertyMetadata(prop); - if (map.containsKey(PropertyMetadata.VISIBILITY)) { - return !Visibility.internal.equals(Visibility.valueOf(map.get(PropertyMetadata.VISIBILITY))); - } - return true; - }; - } - - public static PropertyPredicate includeInExamples() { - return (obj, prop) -> { - final Map 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 isIndexed() { - return (obj, prop) -> { - Set indexed = obj.getIndexedProperties(); - return indexed.contains(prop); - }; - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/Version.java b/aai-core/src/main/java/org/openecomp/aai/introspection/Version.java deleted file mode 100644 index 9e1fab2a..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/Version.java +++ /dev/null @@ -1,36 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.introspection; - -public enum Version { - v8, - v9, - v10, - v11; - - public static boolean isLatest(Version v) { - return (Version.v11.equals(v)); //TODO update when we increment the version, or find a better way of doing this - } - - public static Version getLatest(){ - return Version.v11; //TODO update when we increment the version, or find a better way of doing this - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/Visibility.java b/aai-core/src/main/java/org/openecomp/aai/introspection/Visibility.java deleted file mode 100644 index 4c467a50..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/Visibility.java +++ /dev/null @@ -1,29 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.introspection; - -public enum Visibility { - - internal, - external, - deployment, - all -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/Wanderer.java b/aai-core/src/main/java/org/openecomp/aai/introspection/Wanderer.java deleted file mode 100644 index 5429d999..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/Wanderer.java +++ /dev/null @@ -1,83 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.introspection; - -import org.openecomp.aai.exceptions.AAIException; - -import java.util.List; - -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 list, List 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/openecomp/aai/introspection/exceptions/AAIUnknownObjectException.java b/aai-core/src/main/java/org/openecomp/aai/introspection/exceptions/AAIUnknownObjectException.java deleted file mode 100644 index e8ed4e8a..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/exceptions/AAIUnknownObjectException.java +++ /dev/null @@ -1,42 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.introspection.exceptions; - -import org.openecomp.aai.exceptions.AAIException; - -public class AAIUnknownObjectException extends AAIException { - - private static final long serialVersionUID = -504200228742133774L; - - public AAIUnknownObjectException() {} - - public AAIUnknownObjectException(String message) { - super("AAI_3000", message); - } - - public AAIUnknownObjectException(Throwable cause) { - super("AAI_3000", cause); - } - - public AAIUnknownObjectException(String message, Throwable cause) { - super("AAI_3000", cause, message); - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/exceptions/AAIUnmarshallingException.java b/aai-core/src/main/java/org/openecomp/aai/introspection/exceptions/AAIUnmarshallingException.java deleted file mode 100644 index bbbcdd67..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/exceptions/AAIUnmarshallingException.java +++ /dev/null @@ -1,42 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.introspection.exceptions; - -import org.openecomp.aai.exceptions.AAIException; - -public class AAIUnmarshallingException extends AAIException { - - private static final long serialVersionUID = -5615651557821878103L; - - public AAIUnmarshallingException() {} - - public AAIUnmarshallingException(String message) { - super("AAI_3000", message); - } - - public AAIUnmarshallingException(Throwable cause) { - super("AAI_3000",cause); - } - - public AAIUnmarshallingException(String message, Throwable cause) { - super("AAI_3000", cause, message); - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/generator/CreateExample.java b/aai-core/src/main/java/org/openecomp/aai/introspection/generator/CreateExample.java deleted file mode 100644 index 1b3444fd..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/generator/CreateExample.java +++ /dev/null @@ -1,166 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.introspection.generator; - -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.*; - -import java.security.SecureRandom; -import java.util.ArrayList; -import java.util.List; - -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 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 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 list, List 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/openecomp/aai/introspection/sideeffect/DataCopy.java b/aai-core/src/main/java/org/openecomp/aai/introspection/sideeffect/DataCopy.java deleted file mode 100644 index 53c85013..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/sideeffect/DataCopy.java +++ /dev/null @@ -1,89 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.introspection.sideeffect; - -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.sideeffect.exceptions.AAIMissingRequiredPropertyException; -import org.openecomp.aai.introspection.sideeffect.exceptions.AAIMultiplePropertiesException; -import org.openecomp.aai.parsers.query.QueryParser; -import org.openecomp.aai.restcore.util.URITools; -import org.openecomp.aai.schema.enums.PropertyMetadata; -import org.openecomp.aai.serialization.db.DBSerializer; -import org.openecomp.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); - } - - @Override - protected void processURI(Optional completeUri, Entry entry) throws URISyntaxException, UnsupportedEncodingException, AAIException { - if (completeUri.isPresent()) { - URI uri = new URI(completeUri.get()); - MultivaluedMap map = URITools.getQueryMap(uri); - QueryParser uriQuery = dbEngine.getQueryBuilder(this.latestLoader).createQueryFromURI(uri, map); - List 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 boolean replaceWithWildcard() { - return false; - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/sideeffect/DataLinkReader.java b/aai-core/src/main/java/org/openecomp/aai/introspection/sideeffect/DataLinkReader.java deleted file mode 100644 index 89b03eab..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/sideeffect/DataLinkReader.java +++ /dev/null @@ -1,97 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.introspection.sideeffect; - -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.openecomp.aai.db.props.AAIProperties; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.sideeffect.exceptions.AAIMissingRequiredPropertyException; -import org.openecomp.aai.parsers.query.QueryParser; -import org.openecomp.aai.restcore.util.URITools; -import org.openecomp.aai.schema.enums.PropertyMetadata; -import org.openecomp.aai.serialization.db.DBSerializer; -import org.openecomp.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; - } - - @Override - protected void processURI(Optional completeUri, Entry entry) - throws URISyntaxException, UnsupportedEncodingException, AAIException { - - if (completeUri.isPresent()) { - URI uri = new URI(completeUri.get()); - MultivaluedMap map = URITools.getQueryMap(uri); - QueryParser uriQuery = dbEngine.getQueryBuilder(this.latestLoader).createQueryFromURI(uri, map); - List results = uriQuery.getQueryBuilder().getVerticesByProperty(AAIProperties.LINKED, true).toList(); - if (results.size() == 1) { - if (results.get(0).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 findProperties(Introspector obj, String uriString) throws AAIMissingRequiredPropertyException { - - final Map 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/openecomp/aai/introspection/sideeffect/DataLinkWriter.java b/aai-core/src/main/java/org/openecomp/aai/introspection/sideeffect/DataLinkWriter.java deleted file mode 100644 index 6e93098d..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/sideeffect/DataLinkWriter.java +++ /dev/null @@ -1,109 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.introspection.sideeffect; - -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.openecomp.aai.db.props.AAIProperties; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.sideeffect.exceptions.AAIMultiplePropertiesException; -import org.openecomp.aai.parsers.query.QueryParser; -import org.openecomp.aai.parsers.uri.URIToObject; -import org.openecomp.aai.restcore.util.URITools; -import org.openecomp.aai.schema.enums.PropertyMetadata; -import org.openecomp.aai.serialization.db.DBSerializer; -import org.openecomp.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); - } - - @Override - protected PropertyMetadata getPropertyMetadata() { - return PropertyMetadata.DATA_LINK; - } - - @Override - protected void processURI(Optional completeUri, Entry entry) - throws URISyntaxException, UnsupportedEncodingException, AAIException { - if (completeUri.isPresent()) { - URI uri = new URI(completeUri.get()); - MultivaluedMap map = URITools.getQueryMap(uri); - QueryParser uriQuery = dbEngine.getQueryBuilder(this.latestLoader).createQueryFromURI(uri, map); - List results = uriQuery.getQueryBuilder().toList(); - if (results.size() == 1) { - if (results.get(0).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 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); - } - - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/sideeffect/SideEffect.java b/aai-core/src/main/java/org/openecomp/aai/introspection/sideeffect/SideEffect.java deleted file mode 100644 index 95da72f3..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/sideeffect/SideEffect.java +++ /dev/null @@ -1,128 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.introspection.sideeffect; - -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.openecomp.aai.db.props.AAIProperties; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.introspection.LoaderFactory; -import org.openecomp.aai.introspection.ModelType; -import org.openecomp.aai.introspection.sideeffect.exceptions.AAIMissingRequiredPropertyException; -import org.openecomp.aai.schema.enums.PropertyMetadata; -import org.openecomp.aai.serialization.db.DBSerializer; -import org.openecomp.aai.serialization.engines.TransactionalGraphEngine; - -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("\\{(.*?)\\}"); - protected final Introspector obj; - protected final TransactionalGraphEngine dbEngine; - protected final DBSerializer serializer; - protected final Loader latestLoader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, AAIProperties.LATEST); - protected final Vertex self; - public SideEffect (Introspector obj, Vertex self, TransactionalGraphEngine dbEngine, DBSerializer serializer) { - this.obj = obj; - this.dbEngine = dbEngine; - this.serializer = serializer; - this.self = self; - } - - protected void execute() throws UnsupportedEncodingException, URISyntaxException, AAIException { - final Map properties = this.findPopertiesWithMetadata(obj, this.getPropertyMetadata()); - for (Entry entry : properties.entrySet()) { - Optional populatedUri = this.replaceTemplates(obj, entry.getValue()); - Optional completeUri = this.resolveRelativePath(populatedUri); - this.processURI(completeUri, entry); - } - } - - protected Map findPopertiesWithMetadata(Introspector obj, PropertyMetadata metadata) { - final Map result = new HashMap<>(); - for (String prop : obj.getProperties()) { - final Map map = obj.getPropertyMetadata(prop); - if (map.containsKey(metadata)) { - result.put(prop, map.get(metadata)); - } - } - return result; - } - - protected Map findProperties(Introspector obj, String uriString) throws AAIMissingRequiredPropertyException { - - final Map result = new HashMap<>(); - final Set 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; - } - - private Optional replaceTemplates(Introspector obj, String uriString) throws AAIMissingRequiredPropertyException { - String result = uriString; - final Map propMap = this.findProperties(obj, uriString); - if (propMap.isEmpty()) { - return Optional.empty(); - } - for (Entry entry : propMap.entrySet()) { - result = result.replaceAll("\\{" + entry.getKey() + "\\}", entry.getValue()); - } - //drop out wildcards if they exist - result = result.replaceFirst("/[^/]+?(?:/\\*)+", ""); - return Optional.of(result); - } - - private Optional resolveRelativePath(Optional 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 completeUri, Entry entry) throws URISyntaxException, UnsupportedEncodingException, AAIException; -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/sideeffect/SideEffectRunner.java b/aai-core/src/main/java/org/openecomp/aai/introspection/sideeffect/SideEffectRunner.java deleted file mode 100644 index 3b33be1f..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/sideeffect/SideEffectRunner.java +++ /dev/null @@ -1,99 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.introspection.sideeffect; - -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.serialization.db.DBSerializer; -import org.openecomp.aai.serialization.engines.TransactionalGraphEngine; - -import java.io.UnsupportedEncodingException; -import java.lang.reflect.InvocationTargetException; -import java.net.URISyntaxException; -import java.util.LinkedHashSet; -import java.util.Set; - -public class SideEffectRunner { - - protected final TransactionalGraphEngine dbEngine; - protected final DBSerializer serializer; - protected final Set> 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 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> sideEffects; - - public Builder(final TransactionalGraphEngine dbEngine, final DBSerializer serializer) { - this.dbEngine = dbEngine; - this.serializer = serializer; - this.sideEffects = new LinkedHashSet<>(); - } - - public Builder addSideEffect(Class se) { - sideEffects.add(se); - return this; - } - - public Builder addSideEffects(Class... sideEffects) { - for (Class 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> getSideEffects() { - return sideEffects; - } - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/sideeffect/SideEffectRunnerHelper.java b/aai-core/src/main/java/org/openecomp/aai/introspection/sideeffect/SideEffectRunnerHelper.java deleted file mode 100644 index d94cd4a1..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/sideeffect/SideEffectRunnerHelper.java +++ /dev/null @@ -1,85 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.introspection.sideeffect; - -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Wanderer; -import org.openecomp.aai.serialization.db.DBSerializer; -import org.openecomp.aai.serialization.engines.TransactionalGraphEngine; - -import java.io.UnsupportedEncodingException; -import java.lang.reflect.InvocationTargetException; -import java.net.URISyntaxException; -import java.util.List; -import java.util.Set; - -class SideEffectRunnerHelper implements Wanderer { - - - protected final TransactionalGraphEngine dbEngine; - protected final DBSerializer serializer; - protected final Set> sideEffects; - protected SideEffectRunnerHelper(final TransactionalGraphEngine dbEngine, final DBSerializer serializer, final Set> sideEffects) { - this.dbEngine = dbEngine; - this.serializer = serializer; - this.sideEffects = sideEffects; - } - - private void runSideEffects(Introspector obj) throws AAIException { - for (Class 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 list, List listReference, Introspector parent, - Introspector child) { - // TODO Auto-generated method stub - - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/sideeffect/exceptions/AAIMissingRequiredPropertyException.java b/aai-core/src/main/java/org/openecomp/aai/introspection/sideeffect/exceptions/AAIMissingRequiredPropertyException.java deleted file mode 100644 index aca299c7..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/sideeffect/exceptions/AAIMissingRequiredPropertyException.java +++ /dev/null @@ -1,45 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.introspection.sideeffect.exceptions; - -import org.openecomp.aai.exceptions.AAIException; - -public class AAIMissingRequiredPropertyException extends AAIException { - - - private static final long serialVersionUID = -8907079650472014019L; - - public AAIMissingRequiredPropertyException() {} - - public AAIMissingRequiredPropertyException(String message) { - super("AAI_5107", message); - } - - public AAIMissingRequiredPropertyException(Throwable cause) { - super("AAI_5107",cause); - } - - public AAIMissingRequiredPropertyException(String message, Throwable cause) { - super("AAI_5107", cause, message); - } - - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/sideeffect/exceptions/AAIMultiplePropertiesException.java b/aai-core/src/main/java/org/openecomp/aai/introspection/sideeffect/exceptions/AAIMultiplePropertiesException.java deleted file mode 100644 index 91bb8168..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/sideeffect/exceptions/AAIMultiplePropertiesException.java +++ /dev/null @@ -1,44 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.introspection.sideeffect.exceptions; - -import org.openecomp.aai.exceptions.AAIException; - -public class AAIMultiplePropertiesException extends AAIException { - - private static final long serialVersionUID = 2098371383166008345L; - - public AAIMultiplePropertiesException() {} - - public AAIMultiplePropertiesException(String message) { - super("AAI_6136", message); - } - - public AAIMultiplePropertiesException(Throwable cause) { - super("AAI_6136",cause); - } - - public AAIMultiplePropertiesException(String message, Throwable cause) { - super("AAI_6136", cause, message); - } - - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/tools/CreateUUID.java b/aai-core/src/main/java/org/openecomp/aai/introspection/tools/CreateUUID.java deleted file mode 100644 index f88a099c..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/tools/CreateUUID.java +++ /dev/null @@ -1,49 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.introspection.tools; - -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.schema.enums.PropertyMetadata; - -import java.util.Map; -import java.util.UUID; - -public class CreateUUID implements IssueResolver { - - /** - * {@inheritDoc} - */ - @Override - public boolean resolveIssue(Issue issue) { - - Introspector obj = issue.getIntrospector(); - if (issue.getType().equals(IssueType.MISSING_KEY_PROP)) { - Map 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; - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/tools/DefaultFields.java b/aai-core/src/main/java/org/openecomp/aai/introspection/tools/DefaultFields.java deleted file mode 100644 index c242d983..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/tools/DefaultFields.java +++ /dev/null @@ -1,48 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.introspection.tools; - -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.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 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/openecomp/aai/introspection/tools/InjectKeysFromURI.java b/aai-core/src/main/java/org/openecomp/aai/introspection/tools/InjectKeysFromURI.java deleted file mode 100644 index d9aea008..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/tools/InjectKeysFromURI.java +++ /dev/null @@ -1,69 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.introspection.tools; - -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.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; - } - - /** - * {@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; - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/tools/IntrospectorValidator.java b/aai-core/src/main/java/org/openecomp/aai/introspection/tools/IntrospectorValidator.java deleted file mode 100644 index cf77a3be..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/tools/IntrospectorValidator.java +++ /dev/null @@ -1,318 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.introspection.tools; - -import org.openecomp.aai.db.props.AAIProperties; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.IntrospectorWalker; -import org.openecomp.aai.introspection.Visibility; -import org.openecomp.aai.introspection.Wanderer; -import org.openecomp.aai.schema.enums.PropertyMetadata; - -import java.util.*; - -public class IntrospectorValidator implements Wanderer { - - - private List issues = null; - private List issueResolvers = null; - private boolean validateRequired = true; - private final int maximumDepth; - private int currentDepth = 0; - - private final Set 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 getIssues() { - return this.issues; - } - - /** - * Sets the issue resolvers. - * - * @param resolvers the new issue resolvers - */ - public void setIssueResolvers(List 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 requiredProps = obj.getRequiredProperties(); - Set keys = obj.getKeys(); - Set 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 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 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 list, List 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 issueResolvers = null; - private int maximumDepth = AAIProperties.MAXIMUM_DEPTH; - /** - * Instantiates a new builder. - * - * @param llBuilder the ll builder - */ - public Builder() { - issueResolvers = new ArrayList(); - } - - /** - * 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 getResolvers() { - return this.issueResolvers; - } - - public int getMaximumDepth() { - return this.maximumDepth; - } - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/tools/Issue.java b/aai-core/src/main/java/org/openecomp/aai/introspection/tools/Issue.java deleted file mode 100644 index 173d1f77..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/tools/Issue.java +++ /dev/null @@ -1,144 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.introspection.tools; - -import org.openecomp.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; - } - - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/tools/IssueResolver.java b/aai-core/src/main/java/org/openecomp/aai/introspection/tools/IssueResolver.java deleted file mode 100644 index e62e9b72..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/tools/IssueResolver.java +++ /dev/null @@ -1,33 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.introspection.tools; - -public interface IssueResolver { - - - /** - * Resolve issue. - * - * @param issue the issue - * @return true, if successful - */ - public boolean resolveIssue(Issue issue); -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/tools/IssueType.java b/aai-core/src/main/java/org/openecomp/aai/introspection/tools/IssueType.java deleted file mode 100644 index 5606926c..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/tools/IssueType.java +++ /dev/null @@ -1,25 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.introspection.tools; - -public enum IssueType { - 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/openecomp/aai/introspection/tools/RemoveNonVisibleProperty.java b/aai-core/src/main/java/org/openecomp/aai/introspection/tools/RemoveNonVisibleProperty.java deleted file mode 100644 index 4de0fa60..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/tools/RemoveNonVisibleProperty.java +++ /dev/null @@ -1,36 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.introspection.tools; - -public class RemoveNonVisibleProperty implements IssueResolver { - - @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; - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/tools/Severity.java b/aai-core/src/main/java/org/openecomp/aai/introspection/tools/Severity.java deleted file mode 100644 index 14501794..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/tools/Severity.java +++ /dev/null @@ -1,27 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.introspection.tools; - -public enum Severity { - WARNING, - ERROR, - CRITICAL -} diff --git a/aai-core/src/main/java/org/openecomp/aai/logging/CNName.java b/aai-core/src/main/java/org/openecomp/aai/logging/CNName.java deleted file mode 100644 index 4c152e3c..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/logging/CNName.java +++ /dev/null @@ -1,93 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.logging; - -import ch.qos.logback.access.pattern.AccessConverter; -import ch.qos.logback.access.spi.IAccessEvent; - -import javax.security.auth.x500.X500Principal; -import javax.servlet.http.HttpServletRequest; -import java.security.cert.X509Certificate; - -import static java.util.Base64.getDecoder; - -public class CNName extends AccessConverter { - - /** - * 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){ - - HttpServletRequest request = accessEvent.getRequest(); - - 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 ":" - // 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 ", ""); - byte[] userCredentials = getDecoder().decode(credentials.getBytes("utf-8")); - credentials = new String(userCredentials); - - int codePoint = credentials.indexOf(':'); - - 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 ex){ - return "-"; - } - } else { - return "-"; - } - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/logging/CustomLogPatternLayout.java b/aai-core/src/main/java/org/openecomp/aai/logging/CustomLogPatternLayout.java deleted file mode 100644 index 7a8bbd92..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/logging/CustomLogPatternLayout.java +++ /dev/null @@ -1,28 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.logging; - -public class CustomLogPatternLayout extends ch.qos.logback.access.PatternLayout { - static { - defaultConverterMap.put("z", CNName.class.getName()); - defaultConverterMap.put("y", DME2RestFlag.class.getName()); - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/logging/CustomLogPatternLayoutEncoder.java b/aai-core/src/main/java/org/openecomp/aai/logging/CustomLogPatternLayoutEncoder.java deleted file mode 100644 index a34c6cc6..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/logging/CustomLogPatternLayoutEncoder.java +++ /dev/null @@ -1,40 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.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(); - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/logging/DME2RestFlag.java b/aai-core/src/main/java/org/openecomp/aai/logging/DME2RestFlag.java deleted file mode 100644 index f97f1843..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/logging/DME2RestFlag.java +++ /dev/null @@ -1,55 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.logging; - -import ch.qos.logback.access.pattern.AccessConverter; -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"; - } - - 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"; - } - - return flag; - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/logging/EcompElapsedTime.java b/aai-core/src/main/java/org/openecomp/aai/logging/EcompElapsedTime.java deleted file mode 100644 index f56a6fe5..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/logging/EcompElapsedTime.java +++ /dev/null @@ -1,67 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.logging; - -import org.openecomp.aai.logging.LoggingContext.LoggingField; - -import ch.qos.logback.classic.pattern.ClassicConverter; -import ch.qos.logback.classic.spi.ILoggingEvent; - -public class EcompElapsedTime extends ClassicConverter { - - private static final String DEFAULT_ELAPSED_TIME_FORMAT = "%d"; - - private String ELAPSED_TIME_FORMAT; - - @Override - public void start() { - ELAPSED_TIME_FORMAT = getFirstOption(); - } - - @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())) - ); - } - - final long start = LogFormatTools.toTimestamp(event.getMDCPropertyMap().get(LoggingField.START_TIME.toString())); - - return format(end - start); - } - - private String format(long elapsedTime) { - if (ELAPSED_TIME_FORMAT == null) { - return format(DEFAULT_ELAPSED_TIME_FORMAT, elapsedTime); - } - - return format (ELAPSED_TIME_FORMAT, elapsedTime); - } - - private String format(String format, long elapsedTime) { - return String.format(format, elapsedTime); - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/logging/EcompEncoder.java b/aai-core/src/main/java/org/openecomp/aai/logging/EcompEncoder.java deleted file mode 100644 index 396e51c3..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/logging/EcompEncoder.java +++ /dev/null @@ -1,38 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.logging; - -import ch.qos.logback.classic.PatternLayout; -import ch.qos.logback.classic.encoder.PatternLayoutEncoder; - -public class EcompEncoder extends PatternLayoutEncoder { - - @Override - public void start() { - PatternLayout patternLayout = new EcompPatternLayout(); - patternLayout.setContext(context); - patternLayout.setPattern(getPattern()); - patternLayout.setOutputPatternAsHeader(outputPatternAsHeader); - patternLayout.start(); - this.layout = patternLayout; - super.start(); - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/logging/EcompPatternLayout.java b/aai-core/src/main/java/org/openecomp/aai/logging/EcompPatternLayout.java deleted file mode 100644 index bbf32793..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/logging/EcompPatternLayout.java +++ /dev/null @@ -1,31 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.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()); - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/logging/EcompStartTime.java b/aai-core/src/main/java/org/openecomp/aai/logging/EcompStartTime.java deleted file mode 100644 index c08b273a..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/logging/EcompStartTime.java +++ /dev/null @@ -1,39 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.logging; - -import org.openecomp.aai.logging.LoggingContext.LoggingField; - -import ch.qos.logback.classic.pattern.ClassicConverter; -import ch.qos.logback.classic.spi.ILoggingEvent; - -public class EcompStartTime extends ClassicConverter { - - @Override - public String convert(ILoggingEvent event) { - - if (!event.getMDCPropertyMap().containsKey(LoggingField.START_TIME.toString())) { - return LogFormatTools.toDate(event.getTimeStamp()); - } - - return event.getMDCPropertyMap().get(LoggingField.START_TIME.toString()); - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/logging/EelfClassOfCaller.java b/aai-core/src/main/java/org/openecomp/aai/logging/EelfClassOfCaller.java deleted file mode 100644 index bc745d38..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/logging/EelfClassOfCaller.java +++ /dev/null @@ -1,43 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.logging; - -import ch.qos.logback.classic.pattern.NamedConverter; -import ch.qos.logback.classic.spi.CallerData; -import ch.qos.logback.classic.spi.ILoggingEvent; - -public class EelfClassOfCaller extends NamedConverter { - protected String getFullyQualifiedName(ILoggingEvent event) { - - 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 "com.att.eelf.configuration.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(); - } else { - return CallerData.NA; - } - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/logging/ErrorLogHelper.java b/aai-core/src/main/java/org/openecomp/aai/logging/ErrorLogHelper.java deleted file mode 100644 index 23e4f606..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/logging/ErrorLogHelper.java +++ /dev/null @@ -1,605 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.logging; - -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.StringWriter; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Properties; - -import javax.ws.rs.core.MediaType; -import javax.xml.bind.JAXBContext; -import javax.xml.bind.Marshaller; - -import org.apache.commons.lang.StringUtils; -import org.slf4j.MDC; - -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.logging.LoggingContext.StatusCode; -import org.openecomp.aai.util.AAIConfig; -import org.openecomp.aai.util.AAIConstants; -import org.openecomp.aai.util.MapperUtil; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -/** - * - * This classes loads the application error properties file - * 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 ERROR_OBJECTS = new HashMap (); - - 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 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 variables) { - List acceptHeaders = new ArrayList(); - 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 acceptHeadersOrig, AAIException are, ArrayList variables) { - - - StringBuilder text = new StringBuilder(); - String response = null; - - List acceptHeaders = new ArrayList(); - // 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(); - } - - 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.openecomp.aai.domain.restPolicyException.Fault.class); - Marshaller m = context.createMarshaller(); - m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); - m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); - - org.openecomp.aai.domain.restPolicyException.ObjectFactory factory = new org.openecomp.aai.domain.restPolicyException.ObjectFactory(); - org.openecomp.aai.domain.restPolicyException.Fault fault = factory.createFault(); - org.openecomp.aai.domain.restPolicyException.Fault.RequestError requestError = factory.createFaultRequestError(); - org.openecomp.aai.domain.restPolicyException.Fault.RequestError.PolicyException policyException = factory.createFaultRequestErrorPolicyException(); - org.openecomp.aai.domain.restPolicyException.Fault.RequestError.PolicyException.Variables polvariables = factory.createFaultRequestErrorPolicyExceptionVariables(); - - policyException.setMessageId("POL" + eo.getRESTErrorCode()); - policyException.setText(text.toString()); - for (int i=0;i acceptHeadersOrig, AAIException are, ArrayList variables) { - String response = ErrorLogHelper.getRESTAPIErrorResponse(acceptHeadersOrig, are, variables); - - LOGGER.error(are.getMessage(), 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 acceptHeaders, HashMap> areList) { - - Object respObj = null; - - org.openecomp.aai.domain.restResponseInfo.ObjectFactory factory = new org.openecomp.aai.domain.restResponseInfo.ObjectFactory(); - org.openecomp.aai.domain.restResponseInfo.Info info = factory.createInfo(); - org.openecomp.aai.domain.restResponseInfo.Info.ResponseMessages responseMessages = factory.createInfoResponseMessages(); - Iterator>> it = areList.entrySet().iterator(); - - while (it.hasNext()) { - Map.Entry> pair = (Map.Entry>)it.next(); - AAIException are = pair.getKey(); - ArrayList 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(); - } - - 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.openecomp.aai.domain.restResponseInfo.Info.ResponseMessages.ResponseMessage responseMessage = factory.createInfoResponseMessagesResponseMessage(); - org.openecomp.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) { - - 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(); - } - - 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.openecomp.aai.domain.restPolicyException.Fault.class); - Marshaller m = context.createMarshaller(); - m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); - m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); - - org.openecomp.aai.domain.restPolicyException.ObjectFactory factory = new org.openecomp.aai.domain.restPolicyException.ObjectFactory(); - org.openecomp.aai.domain.restPolicyException.Fault fault = factory.createFault(); - org.openecomp.aai.domain.restPolicyException.Fault.RequestError requestError = factory.createFaultRequestError(); - org.openecomp.aai.domain.restPolicyException.Fault.RequestError.PolicyException policyException = factory.createFaultRequestErrorPolicyException(); - org.openecomp.aai.domain.restPolicyException.Fault.RequestError.PolicyException.Variables polvariables = factory.createFaultRequestErrorPolicyExceptionVariables(); - - policyException.setMessageId("POL" + eo.getRESTErrorCode()); - policyException.setText(text.toString()); - for (int i=0;i 0 && sevCode <= 3 ) - { - LoggingContext.severity(sevCode); - } - } - - final String errorMessage = new StringBuilder() - .append(errorObject.getErrorText()) - .append(":") - .append(errorObject.getRESTErrorCode()) - .append(":") - .append(errorObject.getHTTPResponseCode()) - .append(":") - .append(e.getMessage()) - .toString(); - - LoggingContext.responseCode(Integer.toString(errorObject.getHTTPResponseCode().getStatusCode())); - LoggingContext.responseDescription(errorMessage); - LoggingContext.statusCode(StatusCode.ERROR); - - if (errorObject.getSeverity().equalsIgnoreCase("WARN")) - LOGGER.warn(errorMessage, e); - else if (errorObject.getSeverity().equalsIgnoreCase("ERROR")) - LOGGER.error(errorMessage, e); - else if (errorObject.getSeverity().equalsIgnoreCase("FATAL")) - LOGGER.error(errorMessage, e); - else if (errorObject.getSeverity().equals("INFO")) - LOGGER.info(errorMessage + ", " + e.getMessage()); - } - - 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/openecomp/aai/logging/ErrorObject.java b/aai-core/src/main/java/org/openecomp/aai/logging/ErrorObject.java deleted file mode 100644 index 50822f68..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/logging/ErrorObject.java +++ /dev/null @@ -1,331 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.logging; - -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; - - /** - * 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 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/openecomp/aai/logging/ErrorObjectFormatException.java b/aai-core/src/main/java/org/openecomp/aai/logging/ErrorObjectFormatException.java deleted file mode 100644 index 5e3e7464..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/logging/ErrorObjectFormatException.java +++ /dev/null @@ -1,30 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.logging; - -public class ErrorObjectFormatException extends Exception { - - private static final long serialVersionUID = 3732705544448553685L; - - public ErrorObjectFormatException() { - super(); - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/logging/ErrorObjectNotFoundException.java b/aai-core/src/main/java/org/openecomp/aai/logging/ErrorObjectNotFoundException.java deleted file mode 100644 index fcf72039..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/logging/ErrorObjectNotFoundException.java +++ /dev/null @@ -1,51 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.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 - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/logging/LogFormatTools.java b/aai-core/src/main/java/org/openecomp/aai/logging/LogFormatTools.java deleted file mode 100644 index a07fdc73..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/logging/LogFormatTools.java +++ /dev/null @@ -1,45 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.logging; - -import java.time.Instant; -import java.time.ZoneOffset; -import java.time.ZonedDateTime; -import java.time.format.DateTimeFormatter; - -public class LogFormatTools { - - private static final String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; - private static final DateTimeFormatter DTF = DateTimeFormatter.ofPattern(DATE_FORMAT) - .withZone(ZoneOffset.UTC); - - public static String getCurrentDateTime() { - return DTF.format(ZonedDateTime.now()); - } - - 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(); - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/logging/LoggingContext.java b/aai-core/src/main/java/org/openecomp/aai/logging/LoggingContext.java deleted file mode 100644 index 9a2d5914..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/logging/LoggingContext.java +++ /dev/null @@ -1,374 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.logging; - -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.UUID; -import java.util.concurrent.TimeUnit; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -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"; - - //ECOMP 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"), - - //ECOMP Specific Metric Log Event Fields - TARGET_ENTITY("targetEntity"), - - //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(); - } - - private 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()); - LOGGER.warn("Unable to use UUID " + requestId + " (Not formatted properly). Using generated UUID=" + generatedRequestUuid); - } - } - - 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(LoggingContext.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)); - } - - 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 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 keys = previousContext.keys(); - - while (keys.hasNext()) { - final String key = keys.next(); - - 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) - } - } - - MDC.put(PREVIOUS_CONTEXTS_KEY, removeLast(previousContexts).toString()); - } catch (JSONException e) { - //Ignore, the previousContext is serialized from a JSONObject - } - } - - /** - * 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 . Had they put it into the 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 getCopy() { - final Map copy = new HashMap (); - - 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/openecomp/aai/logging/LoggingContextNotExistsException.java b/aai-core/src/main/java/org/openecomp/aai/logging/LoggingContextNotExistsException.java deleted file mode 100644 index d2149b49..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/logging/LoggingContextNotExistsException.java +++ /dev/null @@ -1,26 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.logging; - -public class LoggingContextNotExistsException extends RuntimeException { - - private static final long serialVersionUID = -4965807709525739623L; -} diff --git a/aai-core/src/main/java/org/openecomp/aai/logging/StopWatch.java b/aai-core/src/main/java/org/openecomp/aai/logging/StopWatch.java deleted file mode 100644 index 0aa6f0d1..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/logging/StopWatch.java +++ /dev/null @@ -1,41 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.logging; - -import org.openecomp.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 clear() { - LoggingContext.remove(LoggingField.STOP_WATCH_START.toString()); - LoggingContext.remove(LoggingField.ELAPSED_TIME.toString()); - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/logging/StopWatchNotStartedException.java b/aai-core/src/main/java/org/openecomp/aai/logging/StopWatchNotStartedException.java deleted file mode 100644 index 89c59924..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/logging/StopWatchNotStartedException.java +++ /dev/null @@ -1,42 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.logging; - -public class StopWatchNotStartedException extends RuntimeException { - - private static final long serialVersionUID = -4540164295822859408L; - - public StopWatchNotStartedException() { - super(); - } - - public StopWatchNotStartedException(String message) { - super(message); - } - - public StopWatchNotStartedException(Throwable cause) { - super(cause); - } - - public StopWatchNotStartedException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/parsers/exceptions/AAIIdentityMapParseException.java b/aai-core/src/main/java/org/openecomp/aai/parsers/exceptions/AAIIdentityMapParseException.java deleted file mode 100644 index bfc35406..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/parsers/exceptions/AAIIdentityMapParseException.java +++ /dev/null @@ -1,41 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.parsers.exceptions; - -import org.openecomp.aai.exceptions.AAIException; - -public class AAIIdentityMapParseException extends AAIException { - - private static final long serialVersionUID = -888876613879411865L; - - public AAIIdentityMapParseException(String message) { - super("AAI_3000", message); - } - - public AAIIdentityMapParseException(Throwable cause) { - super("AAI_3000",cause); - } - - public AAIIdentityMapParseException(String message, Throwable cause) { - super("AAI_3000", cause, message); - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/parsers/exceptions/AmbiguousMapAAIException.java b/aai-core/src/main/java/org/openecomp/aai/parsers/exceptions/AmbiguousMapAAIException.java deleted file mode 100644 index 4917c14f..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/parsers/exceptions/AmbiguousMapAAIException.java +++ /dev/null @@ -1,41 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.parsers.exceptions; - -import org.openecomp.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); - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/parsers/exceptions/DoesNotStartWithValidNamespaceException.java b/aai-core/src/main/java/org/openecomp/aai/parsers/exceptions/DoesNotStartWithValidNamespaceException.java deleted file mode 100644 index 8911f944..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/parsers/exceptions/DoesNotStartWithValidNamespaceException.java +++ /dev/null @@ -1,42 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.parsers.exceptions; - -import org.openecomp.aai.exceptions.AAIException; - -public class DoesNotStartWithValidNamespaceException extends AAIException { - - private static final long serialVersionUID = -888876613879411865L; - - public DoesNotStartWithValidNamespaceException(String message) { - super("AAI_3000", 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/openecomp/aai/parsers/query/LegacyQueryParser.java b/aai-core/src/main/java/org/openecomp/aai/parsers/query/LegacyQueryParser.java deleted file mode 100644 index 5679fc90..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/parsers/query/LegacyQueryParser.java +++ /dev/null @@ -1,227 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.parsers.query; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.introspection.exceptions.AAIUnknownObjectException; -import org.openecomp.aai.parsers.uri.Parsable; -import org.openecomp.aai.parsers.uri.URIParser; -import org.openecomp.aai.parsers.uri.URIToObject; -import org.openecomp.aai.query.builder.QueryBuilder; -import org.openecomp.aai.restcore.util.URITools; -import org.openecomp.aai.schema.enums.PropertyMetadata; -import org.openecomp.aai.serialization.db.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 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 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 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)", e); - } - } - - this.resultResource = obj.getChildDBName(); - this.containerResource = obj.getName(); - } - } - private void handleUriKeys(Introspector obj, MultivaluedMap 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 values = uriKeys.get(key); - String dbPropertyName = key; - Map linkedProperties = new HashMap<>(); - final Map 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 uriKeys, Map linkedProperties) throws AAIException { - - QueryBuilder[] builders = new QueryBuilder[linkedProperties.keySet().size()]; - Set> entrySet = linkedProperties.entrySet(); - int i = 0; - Iterator> itr = entrySet.iterator(); - - while (itr.hasNext()) { - Entry 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 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/openecomp/aai/parsers/query/ObjectNameQueryParser.java b/aai-core/src/main/java/org/openecomp/aai/parsers/query/ObjectNameQueryParser.java deleted file mode 100644 index a1d8f740..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/parsers/query/ObjectNameQueryParser.java +++ /dev/null @@ -1,36 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -/** - * - */ -package org.openecomp.aai.parsers.query; - -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.query.builder.QueryBuilder; - -public class ObjectNameQueryParser extends QueryParser { - - public ObjectNameQueryParser(Loader loader, QueryBuilder queryBuilder, String objName) { - super(loader, queryBuilder); - this.resultResource = objName; - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/parsers/query/QueryParser.java b/aai-core/src/main/java/org/openecomp/aai/parsers/query/QueryParser.java deleted file mode 100644 index ee4e3941..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/parsers/query/QueryParser.java +++ /dev/null @@ -1,146 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.parsers.query; - -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.openecomp.aai.db.props.AAIProperties; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.introspection.LoaderFactory; -import org.openecomp.aai.query.builder.QueryBuilder; - -import java.net.URI; - -/** - * The Class QueryParser. - */ -public abstract class QueryParser { - - protected Loader loader = null; - protected Loader latestLoader = null; - protected QueryBuilder queryBuilder = null; - - protected QueryBuilder 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 queryBuilder, URI uri) { - this.uri = uri; - this.queryBuilder = queryBuilder; - this.loader = loader; - this.latestLoader = LoaderFactory.createLoaderForVersion(loader.getModelType(), AAIProperties.LATEST); - } - - /** - * Instantiates a new query parser. - * - * @param loader the loader - * @param queryBuilder the query builder - */ - protected QueryParser(Loader loader, QueryBuilder queryBuilder) { - this.queryBuilder = queryBuilder; - this.loader = loader; - this.latestLoader = LoaderFactory.createLoaderForVersion(loader.getModelType(), AAIProperties.LATEST); - } - - /** - * 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 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 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/openecomp/aai/parsers/query/QueryParserStrategy.java b/aai-core/src/main/java/org/openecomp/aai/parsers/query/QueryParserStrategy.java deleted file mode 100644 index b0e6cc23..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/parsers/query/QueryParserStrategy.java +++ /dev/null @@ -1,91 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.parsers.query; - -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.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 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 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/openecomp/aai/parsers/query/RelationshipQueryParser.java b/aai-core/src/main/java/org/openecomp/aai/parsers/query/RelationshipQueryParser.java deleted file mode 100644 index fb4200e5..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/parsers/query/RelationshipQueryParser.java +++ /dev/null @@ -1,65 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.parsers.query; - -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.introspection.ModelType; -import org.openecomp.aai.parsers.relationship.RelationshipToURI; -import org.openecomp.aai.parsers.uri.URIParser; -import org.openecomp.aai.query.builder.QueryBuilder; -import org.openecomp.aai.serialization.db.EdgeRules; - -import java.io.UnsupportedEncodingException; - -/** - * The Class RelationshipQueryParser. - */ -public class RelationshipQueryParser extends LegacyQueryParser { - - private Introspector relationship = null; - - private ModelType modelType = null; - - private EdgeRules 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(); - this.edgeRules = EdgeRules.getInstance(); - RelationshipToURI rToUri = new RelationshipToURI(loader, obj); - this.uri = rToUri.getUri(); - URIParser parser = new URIParser(loader, uri); - parser.parse(this); - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/parsers/query/TraversalStrategy.java b/aai-core/src/main/java/org/openecomp/aai/parsers/query/TraversalStrategy.java deleted file mode 100644 index 41064597..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/parsers/query/TraversalStrategy.java +++ /dev/null @@ -1,82 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.parsers.query; - -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.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); - } - - /** - * @{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, MultivaluedMap 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/openecomp/aai/parsers/query/UniqueRelationshipQueryParser.java b/aai-core/src/main/java/org/openecomp/aai/parsers/query/UniqueRelationshipQueryParser.java deleted file mode 100644 index 4739aa47..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/parsers/query/UniqueRelationshipQueryParser.java +++ /dev/null @@ -1,57 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.parsers.query; - -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.parsers.relationship.RelationshipToURI; -import org.openecomp.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(); - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/parsers/query/UniqueStrategy.java b/aai-core/src/main/java/org/openecomp/aai/parsers/query/UniqueStrategy.java deleted file mode 100644 index 5668036f..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/parsers/query/UniqueStrategy.java +++ /dev/null @@ -1,81 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.parsers.query; - -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.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); - } - - /** - * @{inheritDoc} - */ - @Override - public QueryParser buildRelationshipParser(Introspector obj) throws UnsupportedEncodingException, AAIException { - return new UniqueRelationshipQueryParser(loader, builder, obj); - } - - /** - * @{inheritDoc} - */ - @Override - public QueryParser buildURIParser(URI uri, MultivaluedMap 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/openecomp/aai/parsers/query/UniqueURIQueryParser.java b/aai-core/src/main/java/org/openecomp/aai/parsers/query/UniqueURIQueryParser.java deleted file mode 100644 index 64fc3df2..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/parsers/query/UniqueURIQueryParser.java +++ /dev/null @@ -1,164 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.parsers.query; - -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.parsers.uri.Parsable; -import org.openecomp.aai.parsers.uri.URIParser; -import org.openecomp.aai.parsers.uri.URIToDBKey; -import org.openecomp.aai.query.builder.QueryBuilder; -import org.openecomp.aai.serialization.db.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 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 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/openecomp/aai/parsers/relationship/RelationshipToURI.java b/aai-core/src/main/java/org/openecomp/aai/parsers/relationship/RelationshipToURI.java deleted file mode 100644 index 873f7211..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/parsers/relationship/RelationshipToURI.java +++ /dev/null @@ -1,281 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.parsers.relationship; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.apache.tinkerpop.gremlin.structure.Direction; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.*; -import org.openecomp.aai.introspection.exceptions.AAIUnknownObjectException; -import org.openecomp.aai.parsers.exceptions.AAIIdentityMapParseException; -import org.openecomp.aai.parsers.exceptions.AmbiguousMapAAIException; -import org.openecomp.aai.parsers.uri.URIParser; -import org.openecomp.aai.schema.enums.ObjectMetadata; -import org.openecomp.aai.serialization.db.AAIDirection; -import org.openecomp.aai.serialization.db.EdgeRule; -import org.openecomp.aai.serialization.db.EdgeRules; -import org.openecomp.aai.serialization.db.EdgeType; -import org.openecomp.aai.workarounds.LegacyURITransformer; - -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 EdgeRules edgeRules = null; - - private URI uri = null; - - private LegacyURITransformer urlTransform = null; - - /** - * 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.edgeRules = EdgeRules.getInstance(); - this.loader = loader; - this.urlTransform = LegacyURITransformer.getInstance(); - - this.parse(); - - } - - /** - * 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 result; - try { - if (loader.getVersion().compareTo(Version.v10) >= 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 processRelationshipData() throws AAIException, UnsupportedEncodingException { - Optional result = Optional.empty(); - StringBuilder uriBuilder = new StringBuilder(); - List data = (List)relationship.getValue("relationship-data"); - Introspector wrapper; - String key; - String value; - String objectType; - String propertyName; - String topLevelType = null; - String[] split; - HashMap 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); - } - - 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 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 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; - } - - private Optional processRelatedLink(String relatedLink) throws URISyntaxException, UnsupportedEncodingException, AAIIdentityMapParseException { - Optional 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 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.getEdgeRule(EdgeType.TREE, startType, objectType); - 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 e) { - //ignore exceptions generated - continue; - } - } - - - return false; - } - - /** - * Gets the uri. - * - * @return the uri - */ - public URI getUri() { - return uri; - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/parsers/uri/Parsable.java b/aai-core/src/main/java/org/openecomp/aai/parsers/uri/Parsable.java deleted file mode 100644 index 2488980e..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/parsers/uri/Parsable.java +++ /dev/null @@ -1,72 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.parsers.uri; - -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.serialization.db.EdgeType; - -import javax.ws.rs.core.MultivaluedMap; - -/** - * The Interface Parsable. - */ -public interface Parsable { - - /** - * - * @param obj - * @param type - * @param uriKeys - * @throws AAIException - */ - public void processObject(Introspector obj, EdgeType type, MultivaluedMap 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 - */ - public void processContainer(Introspector obj, EdgeType type, MultivaluedMap uriKeys, boolean isFinalContainer) throws AAIException; - - /** - * Process namespace. - * - * @param obj the obj - */ - public void processNamespace(Introspector obj); - - /** - * Gets the cloud region transform. - * - * @return the cloud region transform - */ - public String getCloudRegionTransform(); - - /** - * Use original loader. - * - * @return true, if successful - */ - public boolean useOriginalLoader(); -} diff --git a/aai-core/src/main/java/org/openecomp/aai/parsers/uri/URIParser.java b/aai-core/src/main/java/org/openecomp/aai/parsers/uri/URIParser.java deleted file mode 100644 index 4df650de..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/parsers/uri/URIParser.java +++ /dev/null @@ -1,278 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.parsers.uri; - -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.introspection.LoaderFactory; -import org.openecomp.aai.introspection.Version; -import org.openecomp.aai.logging.ErrorLogHelper; -import org.openecomp.aai.parsers.exceptions.DoesNotStartWithValidNamespaceException; -import org.openecomp.aai.rest.RestTokens; -import org.openecomp.aai.schema.enums.ObjectMetadata; -import org.openecomp.aai.serialization.db.EdgeType; -import org.openecomp.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 queryParams = null; - - - /** - * Instantiates a new URI parser. - * - * @param loader the loader - * @param uri the uri - */ - public URIParser(Loader loader, URI uri) { - this.uri = uri; - - String currentVersion = "v7"; - this.originalLoader = loader; - try { - currentVersion = AAIConfig.get("aai.default.api.version"); - } catch (AAIException e) { - ErrorLogHelper.logException(e); - } - - //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 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 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 uriKeys = new MultivaluedHashMap<>(); - if (i == parts.length-2 && queryParams != null) { - Set queryKeys = queryParams.keySet(); - for (String key : queryKeys) { - uriKeys.put(key, queryParams.get(key)); - - } - } - if (introspector.isContainer()) { - boolean isFinalContainer = i == parts.length-2; - p.processContainer(introspector, EdgeType.COUSIN, uriKeys, isFinalContainer); - } - previousObj = introspector; - type = EdgeType.COUSIN; - 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 uriKeys = new MultivaluedHashMap<>(); - i++; - if (i == parts.length && queryParams != null) { - Set 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 uriKeys = new MultivaluedHashMap<>(); - - if (isFinalContainer && queryParams != null) { - Set 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); - } - - result = result.replaceFirst("aai/v\\d+/", ""); - - return UriBuilder.fromPath(result).build(); - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/parsers/uri/URIToDBKey.java b/aai-core/src/main/java/org/openecomp/aai/parsers/uri/URIToDBKey.java deleted file mode 100644 index 6aa28e27..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/parsers/uri/URIToDBKey.java +++ /dev/null @@ -1,122 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.parsers.uri; - -import com.google.common.base.Joiner; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.serialization.db.EdgeType; - -import javax.ws.rs.core.MultivaluedMap; -import java.io.UnsupportedEncodingException; -import java.net.URI; -import java.util.ArrayList; -import java.util.List; - -/** - * Creates a Unique database key from a URI - * - * The key is of the form node-type/key(s). - */ -public class URIToDBKey implements Parsable { - - - private List 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); - } - /* - public URIToDBKey(Version version, String uri) throws IllegalArgumentException { - - super(version, uri); - try { - context = ModelInjestor.getInstance().getContextForVersion(version); - if (context == null) { - throw new IllegalArgumentException("could not find a context for version: " + version); - } - this.parse(); - } catch (Exception e) { - throw new IllegalArgumentException("uri not valid against our model: " + uri); - } - }*/ - - /** - * @{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 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 uriKeys, - boolean isFinalContainer) throws AAIException { - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/parsers/uri/URIToExtensionInformation.java b/aai-core/src/main/java/org/openecomp/aai/parsers/uri/URIToExtensionInformation.java deleted file mode 100644 index d32facfa..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/parsers/uri/URIToExtensionInformation.java +++ /dev/null @@ -1,164 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.parsers.uri; - -import com.google.common.base.CaseFormat; -import com.google.common.base.Joiner; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.restcore.HttpMethod; -import org.openecomp.aai.serialization.db.EdgeType; - -import javax.ws.rs.core.MultivaluedMap; -import java.io.UnsupportedEncodingException; -import java.net.URI; -import java.util.ArrayList; -import java.util.List; - -/** - * The Class URIToExtensionInformation. - */ -public class URIToExtensionInformation implements Parsable { - - private String namespace = ""; - - private String methodName = ""; - - private String topObject = ""; - - private List 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)) { - result += "Add"; - } 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 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 uriKeys, - boolean isFinalContainer) throws AAIException { - pieces.add(toUpperCamel(obj.getName())); - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/parsers/uri/URIToObject.java b/aai-core/src/main/java/org/openecomp/aai/parsers/uri/URIToObject.java deleted file mode 100644 index decd803f..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/parsers/uri/URIToObject.java +++ /dev/null @@ -1,220 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.parsers.uri; - -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.introspection.Version; -import org.openecomp.aai.schema.enums.ObjectMetadata; -import org.openecomp.aai.serialization.db.EdgeType; - -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. - * - * It populates the keys in the order they are listed in the model. - * - - * - */ -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 parentList = null; - - private Version version = null; - private Loader loader = null; - private final HashMap 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 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 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 Version getObjectVersion() { - return this.loader.getVersion(); - } - public Loader getLoader() { - return this.loader; - } - @Override - public void processObject(Introspector obj, EdgeType type, MultivaluedMap uriKeys) - throws AAIException { - - if (this.entityName == null) { - this.topEntityName = obj.getDbName(); - this.topEntity = obj; - } - this.entityName = obj.getDbName(); - this.entity = obj; - this.parentList = (List)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 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/openecomp/aai/parsers/uri/URIToRelationshipObject.java b/aai-core/src/main/java/org/openecomp/aai/parsers/uri/URIToRelationshipObject.java deleted file mode 100644 index a5429000..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/parsers/uri/URIToRelationshipObject.java +++ /dev/null @@ -1,169 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.parsers.uri; - -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.introspection.Version; -import org.openecomp.aai.introspection.exceptions.AAIUnknownObjectException; -import org.openecomp.aai.serialization.db.EdgeType; -import org.openecomp.aai.util.AAIApiServerURLBase; -import org.openecomp.aai.workarounds.LegacyURITransformer; - -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 LegacyURITransformer uriTransformer = null; - - private Version 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; - uriTransformer = LegacyURITransformer.getInstance(); - originalVersion = loader.getVersion(); - - try { - relationship = loader.introspectorFromName("relationship"); - } catch (AAIUnknownObjectException e1) { - throw new RuntimeException("Fatal error - could not load relationship object!", e1); - } - - this.baseURL = AAIApiServerURLBase.get(originalVersion); - 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); - this.relationship.setValue("related-link", relatedLink); - if (this.originalVersion.compareTo(Version.v10) >= 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 uriKeys) - throws AAIException { - 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)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 uriKeys, - boolean isFinalContainer) throws AAIException { - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/parsers/uri/URIValidate.java b/aai-core/src/main/java/org/openecomp/aai/parsers/uri/URIValidate.java deleted file mode 100644 index b7c0958c..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/parsers/uri/URIValidate.java +++ /dev/null @@ -1,63 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.parsers.uri; - -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.serialization.db.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 uriKeys) - throws AAIException { - //NO-OP - //just want to make sure this URI has valid tokens - } - - @Override - public void processContainer(Introspector obj, EdgeType type, MultivaluedMap 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/openecomp/aai/query/builder/GraphTraversalBuilder.java b/aai-core/src/main/java/org/openecomp/aai/query/builder/GraphTraversalBuilder.java deleted file mode 100644 index ecaadba2..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/query/builder/GraphTraversalBuilder.java +++ /dev/null @@ -1,655 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.query.builder; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Optional; -import java.util.Set; - -import org.apache.tinkerpop.gremlin.process.traversal.P; -import org.apache.tinkerpop.gremlin.process.traversal.Traversal; -import org.apache.tinkerpop.gremlin.process.traversal.Traversal.Admin; -import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; -import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; -import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__; -import org.apache.tinkerpop.gremlin.process.traversal.util.TraversalHelper; -import org.apache.tinkerpop.gremlin.structure.Direction; -import org.apache.tinkerpop.gremlin.structure.Edge; -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.openecomp.aai.db.props.AAIProperties; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.schema.enums.ObjectMetadata; -import org.openecomp.aai.schema.enums.PropertyMetadata; -import org.openecomp.aai.serialization.db.EdgeRule; -import org.openecomp.aai.serialization.db.EdgeRules; -import org.openecomp.aai.serialization.db.EdgeType; -import org.openecomp.aai.serialization.db.exceptions.NoEdgeRuleFoundException; - -/** - * The Class GraphTraversalBuilder. - */ -public abstract class GraphTraversalBuilder extends QueryBuilder { - - protected GraphTraversal traversal = null; - protected Admin completeTraversal = null; - private EdgeRules edgeRules = EdgeRules.getInstance(); - - protected int parentStepIndex = 0; - protected int containerStepIndex = 0; - protected int stepIndex = 0; - - /** - * Instantiates a new graph traversal builder. - * - * @param loader the loader - */ - public GraphTraversalBuilder(Loader loader, GraphTraversalSource source) { - super(loader, source); - - traversal = (GraphTraversal) __.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) __.__(start); - - } - - /** - * @{inheritDoc} - */ - @Override - public QueryBuilder getVerticesByIndexedProperty(String key, Object value) { - - return this.getVerticesByProperty(key, value); - } - - /** - * @{inheritDoc} - */ - @Override - public QueryBuilder getVerticesByIndexedProperty(String key, List values) { - return this.getVerticesByProperty(key, values); - } - - /** - * @{inheritDoc} - */ - @Override - public QueryBuilder getVerticesByProperty(String key, Object value) { - - //this is because the index is registered as an Integer - value = this.correctObjectType(value); - - traversal.has(key, value); - - stepIndex++; - return (QueryBuilder) this; - } - - /** - * @{inheritDoc} - */ - @Override - public QueryBuilder getVerticesByProperty(final String key, final List values) { - - //this is because the index is registered as an Integer - List correctedValues = new ArrayList<>(); - for (Object item : values) { - correctedValues.add(this.correctObjectType(item)); - } - - traversal.has(key, P.within(correctedValues)); - - stepIndex++; - return (QueryBuilder) this; - } - - /** - * @{inheritDoc} - */ - @Override - public QueryBuilder getChildVerticesFromParent(String parentKey, String parentValue, String childType) { - traversal.has(parentKey, parentValue).has(AAIProperties.NODE_TYPE, childType); - stepIndex++; - return (QueryBuilder) this; - } - - /** - * @{inheritDoc} - */ - @Override - public QueryBuilder getTypedVerticesByMap(String type, LinkedHashMap map) { - - for (String key : map.keySet()) { - traversal.has(key, map.get(key)); - stepIndex++; - } - traversal.has(AAIProperties.NODE_TYPE, type); - stepIndex++; - return (QueryBuilder) this; - } - - /** - * @{inheritDoc} - */ - @Override - public QueryBuilder createDBQuery(Introspector obj) { - this.createKeyQuery(obj); - this.createContainerQuery(obj); - return (QueryBuilder) this; - } - - /** - * @{inheritDoc} - */ - @Override - public QueryBuilder createKeyQuery(Introspector obj) { - Set keys = obj.getKeys(); - Object val; - for (String key : keys) { - val = obj.getValue(key); - Optional 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) this; - } - - @Override - public QueryBuilder exactMatchQuery(Introspector obj) { - this.createKeyQuery(obj); - allPropertiesQuery(obj); - this.createContainerQuery(obj); - return (QueryBuilder) this; - } - - private void allPropertiesQuery(Introspector obj) { - Set props = obj.getProperties(); - Set keys = obj.getKeys(); - Object val; - for (String prop : props) { - if (obj.isSimpleType(prop) && !keys.contains(prop)) { - val = obj.getValue(prop); - if (val != null) { - Optional 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 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) this; - } - - /** - * @throws NoEdgeRuleFoundException - * @throws AAIException - * @{inheritDoc} - */ - @Override - public QueryBuilder createEdgeTraversal(EdgeType type, Introspector parent, Introspector child) throws AAIException, NoEdgeRuleFoundException { - String isAbstractType = parent.getMetadata(ObjectMetadata.ABSTRACT); - if ("true".equals(isAbstractType)) { - markParentBoundary(); - traversal.union(handleAbstractEdge(type, parent, child)); - stepIndex += 1; - } else { - this.edgeQueryToVertex(type, parent, child); - } - return (QueryBuilder) this; - - } - - private Traversal[] handleAbstractEdge(EdgeType type, Introspector abstractParent, Introspector child) throws AAIException, NoEdgeRuleFoundException { - String childName = child.getDbName(); - String inheritorMetadata = abstractParent.getMetadata(ObjectMetadata.INHERITORS); - String[] inheritors = inheritorMetadata.split(","); - Traversal[] unionTraversals = new Traversal[inheritors.length]; - int traversalIndex = 0; - for (int i = 0; i < inheritors.length; i++) { - String inheritor = inheritors[i]; - if (edgeRules.hasEdgeRule(inheritor, childName) || edgeRules.hasEdgeRule(childName, inheritor)) { - EdgeRule rule = edgeRules.getEdgeRule(type, inheritor, childName); - GraphTraversal innerTraversal = __.start(); - if (rule.getDirection().equals(Direction.OUT)) { - innerTraversal.out(rule.getLabel()); - } else { - innerTraversal.in(rule.getLabel()); - } - innerTraversal.has(AAIProperties.NODE_TYPE, childName); - unionTraversals[traversalIndex] = innerTraversal; - traversalIndex++; - } - } - if (traversalIndex < inheritors.length) { - Traversal[] temp = Arrays.copyOfRange(unionTraversals, 0, traversalIndex); - unionTraversals = temp; - } - return unionTraversals; - } - /** - * @throws NoEdgeRuleFoundException - * @throws AAIException - * @{inheritDoc} - */ - @Override - public QueryBuilder createEdgeTraversal(EdgeType type, Vertex parent, Introspector child) throws AAIException, NoEdgeRuleFoundException { - - String nodeType = parent.property(AAIProperties.NODE_TYPE).orElse(null); - Introspector parentObj = loader.introspectorFromName(nodeType); - this.edgeQueryToVertex(type, parentObj, child); - return (QueryBuilder) this; - - } - - @Override - public QueryBuilder getEdgesBetween(EdgeType type, String outNodeType, String inNodeType) throws AAIException { - Introspector outObj = loader.introspectorFromName(outNodeType); - Introspector inObj = loader.introspectorFromName(inNodeType); - this.edgeQuery(type, outObj, inObj); - - return (QueryBuilder)this; - - } - /** - * @{inheritDoc} - */ - @Override - public QueryBuilder union(QueryBuilder... builder) { - GraphTraversal[] traversals = new GraphTraversal[builder.length]; - for (int i = 0; i < builder.length; i++) { - traversals[i] = (GraphTraversal)builder[i].getQuery(); - } - this.traversal.union(traversals); - stepIndex++; - - return this; - } - - /** - * @{inheritDoc} - */ - @Override - public QueryBuilder where(QueryBuilder... builder) { - GraphTraversal[] traversals = new GraphTraversal[builder.length]; - for (int i = 0; i < builder.length; i++) { - this.traversal.where((GraphTraversal)builder[i].getQuery()); - stepIndex++; - } - - return this; - } - - @Override - public QueryBuilder store(String name) { - - this.traversal.store(name); - stepIndex++; - - return this; - } - - @Override - public QueryBuilder cap(String name) { - this.traversal.cap(name); - stepIndex++; - - return this; - } - - @Override - public QueryBuilder unfold() { - this.traversal.unfold(); - stepIndex++; - - return this; - } - - @Override - public QueryBuilder dedup() { - - this.traversal.dedup(); - stepIndex++; - - return this; - } - - @Override - public QueryBuilder emit() { - - this.traversal.emit(); - stepIndex++; - - return this; - - } - - @Override - public QueryBuilder repeat(QueryBuilder builder) { - - this.traversal.repeat((GraphTraversal)builder.getQuery()); - stepIndex++; - - return this; - } - - @Override - public QueryBuilder until(QueryBuilder builder) { - this.traversal.until((GraphTraversal)builder.getQuery()); - stepIndex++; - - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public QueryBuilder simplePath(){ - this.traversal.simplePath(); - stepIndex++; - return this; - } - - @Override - public QueryBuilder outE() { - this.traversal.outE(); - stepIndex++; - return (QueryBuilder)this; - } - - @Override - public QueryBuilder inE() { - this.traversal.inE(); - stepIndex++; - return (QueryBuilder)this; - } - - @Override - public QueryBuilder outV() { - this.traversal.outV(); - stepIndex++; - return (QueryBuilder)this; - } - - @Override - public QueryBuilder inV() { - this.traversal.inV(); - stepIndex++; - return (QueryBuilder)this; - } - - @Override - public QueryBuilder as(String name) { - this.traversal.as(name); - - stepIndex++; - return this; - } - - @Override - public QueryBuilder not(QueryBuilder builder) { - this.traversal.not(builder.getQuery()); - - stepIndex++; - return this; - } - - @Override - public QueryBuilder select(String name) { - this.traversal.select(name); - - stepIndex++; - - return this; - } - - /** - * Edge query. - * - * @param outType the out type - * @param inType the in type - * @throws NoEdgeRuleFoundException - * @throws AAIException - */ - private void edgeQueryToVertex(EdgeType type, Introspector outObj, Introspector inObj) throws AAIException, NoEdgeRuleFoundException { - String outType = outObj.getDbName(); - String inType = inObj.getDbName(); - - if (outObj.isContainer()) { - outType = outObj.getChildDBName(); - } - if (inObj.isContainer()) { - inType = inObj.getChildDBName(); - } - markParentBoundary(); - EdgeRule rule = edgeRules.getEdgeRule(type, outType, inType); - if (rule.getDirection().equals(Direction.OUT)) { - traversal.out(rule.getLabel()); - } else { - traversal.in(rule.getLabel()); - } - stepIndex++; - this.createContainerQuery(inObj); - - } - - /** - * Edge query. - * - * @param outType the out type - * @param inType the in type - * @throws NoEdgeRuleFoundException - * @throws AAIException - */ - private void edgeQuery(EdgeType type, Introspector outObj, Introspector inObj) throws AAIException, NoEdgeRuleFoundException { - String outType = outObj.getDbName(); - String inType = inObj.getDbName(); - - if (outObj.isContainer()) { - outType = outObj.getChildDBName(); - } - if (inObj.isContainer()) { - inType = inObj.getChildDBName(); - } - markParentBoundary(); - EdgeRule rule = edgeRules.getEdgeRule(type, outType, inType); - if (rule.getDirection().equals(Direction.OUT)) { - traversal.outE(rule.getLabel()); - } else { - traversal.inE(rule.getLabel()); - } - stepIndex++; - - } - - @Override - public QueryBuilder limit(long amount) { - traversal.limit(amount); - return this; - } - - /** - * @{inheritDoc} - */ - @Override - public E2 getQuery() { - return (E2)this.traversal; - } - - /** - * @{inheritDoc} - */ - @Override - public QueryBuilder getParentQuery() { - - return cloneQueryAtStep(parentStepIndex); - } - - @Override - public QueryBuilder 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; - } - - protected abstract QueryBuilder cloneQueryAtStep(int index); - /** - * end is exclusive - * - * @param start - * @param end - * @return - */ - protected abstract QueryBuilder removeQueryStepsBetween(int start, int end); - - private 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) 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 toList() { - if (this.completeTraversal == null) { - executeQuery(); - } - - return this.completeTraversal.toList(); - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/query/builder/GremlinQueryBuilder.java b/aai-core/src/main/java/org/openecomp/aai/query/builder/GremlinQueryBuilder.java deleted file mode 100644 index b151d9d8..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/query/builder/GremlinQueryBuilder.java +++ /dev/null @@ -1,567 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.query.builder; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; -import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; -import org.apache.tinkerpop.gremlin.structure.Direction; -import org.apache.tinkerpop.gremlin.structure.Edge; -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.openecomp.aai.db.props.AAIProperties; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.restcore.search.GremlinGroovyShellSingleton; -import org.openecomp.aai.schema.enums.ObjectMetadata; -import org.openecomp.aai.serialization.db.EdgeRule; -import org.openecomp.aai.serialization.db.EdgeRules; -import org.openecomp.aai.serialization.db.EdgeType; -import org.openecomp.aai.serialization.db.exceptions.NoEdgeRuleFoundException; - -import com.google.common.base.Joiner; - -/** - * The Class GremlinQueryBuilder. - */ -public abstract class GremlinQueryBuilder extends QueryBuilder { - - private EdgeRules edgeRules = EdgeRules.getInstance(); - private GremlinGroovyShellSingleton gremlinGroovy = GremlinGroovyShellSingleton.getInstance(); - private GraphTraversal completeTraversal = null; - protected List list = null; - - protected int parentStepIndex = 0; - protected int containerStepIndex = 0; - protected int stepIndex = 0; - - /** - * Instantiates a new gremlin query builder. - * - * @param loader the loader - */ - public GremlinQueryBuilder(Loader loader, GraphTraversalSource source) { - super(loader, source); - list = new ArrayList(); - } - - /** - * Instantiates a new gremlin query builder. - * - * @param loader the loader - * @param start the start - */ - public GremlinQueryBuilder(Loader loader, GraphTraversalSource source, Vertex start) { - super(loader, source, start); - list = new ArrayList(); - } - - /** - * @{inheritDoc} - */ - @Override - public QueryBuilder createDBQuery(Introspector obj) { - this.createKeyQuery(obj); - this.createContainerQuery(obj); - return (QueryBuilder) this; - } - - @Override - public QueryBuilder exactMatchQuery(Introspector obj) { - // TODO not implemented because this is implementation is no longer used - this.createKeyQuery(obj); - //allPropertiesQuery(obj); - this.createContainerQuery(obj); - return (QueryBuilder) this; - } - - /** - * @{inheritDoc} - */ - @Override - public QueryBuilder getVerticesByIndexedProperty(String key, Object value) { - return this.getVerticesByProperty(key, value); - } - - /** - * @{inheritDoc} - */ - @Override - public QueryBuilder getVerticesByIndexedProperty(String key, List values) { - return this.getVerticesByProperty(key, values); - } - - /** - * @{inheritDoc} - */ - @Override - public QueryBuilder getVerticesByProperty(String key, Object value) { - - String term = ""; - if (value != null && !value.getClass().getName().equals("java.lang.String")) { - term = value.toString(); - } else { - term = "'" + value + "'"; - } - list.add(".has('" + key + "', " + term + ")"); - stepIndex++; - return (QueryBuilder) this; - } - - /** - * @{inheritDoc} - */ - @Override - public QueryBuilder getVerticesByProperty(String key, List values) { - - String term = ""; - String predicate = "P.within(#!#argument#!#)"; - List arguments = new ArrayList<>(); - for (Object item : values) { - if (item != null && !item.getClass().getName().equals("java.lang.String")) { - arguments.add(item.toString()); - } else { - arguments.add("'" + item + "'"); - } - } - String argument = Joiner.on(",").join(arguments); - predicate = predicate.replace("#!#argument#!#", argument); - list.add(".has('" + key + "', " + predicate + ")"); - stepIndex++; - return (QueryBuilder) this; - } - - - /** - * @{inheritDoc} - */ - @Override - public QueryBuilder getChildVerticesFromParent(String parentKey, String parentValue, String childType) { - /* - String query = ".has('aai-node-type', '" + childType + "')"; - - return this.processGremlinQuery(parentKey, parentValue, query); - */ - //TODO - return (QueryBuilder) this; - } - - /** - * @{inheritDoc} - */ - @Override - public QueryBuilder getTypedVerticesByMap(String type, LinkedHashMap map) { - - for (String key : map.keySet()) { - list.add(".has('" + key + "', '" + map.get(key) + "')"); - stepIndex++; - } - list.add(".has('aai-node-type', '" + type + "')"); - stepIndex++; - return (QueryBuilder) this; - } - - /** - * @{inheritDoc} - */ - @Override - public QueryBuilder createKeyQuery(Introspector obj) { - Set keys = obj.getKeys(); - - for (String key : keys) { - - this.getVerticesByProperty(key, obj.getValue(key)); - - } - return (QueryBuilder) this; - } - - /** - * @throws NoEdgeRuleFoundException - * @throws AAIException - * @{inheritDoc} - */ - @Override - public QueryBuilder createEdgeTraversal(EdgeType type, Introspector parent, Introspector child) throws AAIException, NoEdgeRuleFoundException { - String parentName = parent.getDbName(); - String childName = child.getDbName(); - if (parent.isContainer()) { - parentName = parent.getChildDBName(); - } - if (child.isContainer()) { - childName = child.getChildDBName(); - } - this.edgeQueryToVertex(type, parentName, childName); - return this; - - } - - /** - * @throws NoEdgeRuleFoundException - * @throws AAIException - * @{inheritDoc} - */ - @Override - public QueryBuilder createEdgeTraversal(EdgeType type, Vertex parent, Introspector child) throws AAIException, NoEdgeRuleFoundException { - String nodeType = parent.property(AAIProperties.NODE_TYPE).orElse(null); - this.edgeQueryToVertex(type, nodeType, child.getDbName()); - - return (QueryBuilder) this; - - } - - @Override - public QueryBuilder getEdgesBetween(EdgeType type, String outNodeType, String inNodeType) throws AAIException { - this.edgeQuery(type, outNodeType, inNodeType); - - return (QueryBuilder)this; - - } - /** - * Edge query. - * - * @param outType the out type - * @param inType the in type - * @throws NoEdgeRuleFoundException - * @throws AAIException - */ - private void edgeQueryToVertex(EdgeType type, String outType, String inType) throws AAIException, NoEdgeRuleFoundException { - markParentBoundary(); - EdgeRule rule = edgeRules.getEdgeRule(type, outType, inType); - if (rule.getDirection().equals(Direction.OUT)) { - list.add(".out('" + rule.getLabel() + "')"); - } else { - list.add(".in('" + rule.getLabel() + "')"); - } - stepIndex++; - list.add(".has('" + AAIProperties.NODE_TYPE + "', '" + inType + "')"); - stepIndex++; - - } - - /** - * Edge query. - * - * @param outType the out type - * @param inType the in type - * @throws NoEdgeRuleFoundException - * @throws AAIException - */ - private void edgeQuery(EdgeType type, String outType, String inType) throws AAIException, NoEdgeRuleFoundException { - markParentBoundary(); - EdgeRule rule = edgeRules.getEdgeRule(type, outType, inType); - if (rule.getDirection().equals(Direction.OUT)) { - list.add(".outE('" + rule.getLabel() + "')"); - } else { - list.add(".inV('" + rule.getLabel() + "')"); - } - stepIndex++; - - } - @Override - public QueryBuilder limit(long amount) { - list.add(".limit(" + amount + ")"); - return this; - } - /** - * @{inheritDoc} - */ - @Override - public QueryBuilder createContainerQuery(Introspector obj) { - String type = obj.getChildDBName(); - String abstractType = obj.getMetadata(ObjectMetadata.ABSTRACT); - if (abstractType != null) { - String[] inheritors = obj.getMetadata(ObjectMetadata.INHERITORS).split(","); - String[] wrapped = new String[inheritors.length]; - StringBuilder command = new StringBuilder(); - command.append("P.within("); - for (int i = 0; i < inheritors.length; i++) { - wrapped[i] = "'" + inheritors[i] + "'"; - } - command.append(Joiner.on(",").join(wrapped)); - command.append(")"); - list.add(".has('aai-node-type', " + command + ")"); - - } else { - list.add(".has('aai-node-type', '" + type + "')"); - } - stepIndex++; - this.markContainer(); - return (QueryBuilder) this; - } - - @Override - public QueryBuilder union(QueryBuilder... builder) { - markParentBoundary(); - String[] traversals = new String[builder.length]; - StringBuilder command = new StringBuilder(); - for (int i = 0; i < builder.length; i++) { - traversals[i] = "__" + (String)builder[i].getQuery(); - } - command.append(".union("); - command.append(Joiner.on(",").join(traversals)); - command.append(")"); - list.add(command.toString()); - stepIndex++; - - return this; - } - - @Override - public QueryBuilder where(QueryBuilder... builder) { - markParentBoundary(); - List traversals = new ArrayList<>(); - for (int i = 0; i < builder.length; i++) { - traversals.add(".where(__" + (String)builder[i].getQuery() + ")"); - stepIndex++; - } - list.addAll(traversals); - - - return this; - } - - @Override - public QueryBuilder store(String name) { - this.list.add(".store('"+ name + "')"); - stepIndex++; - - return this; - } - - @Override - public QueryBuilder cap(String name) { - this.list.add(".cap('"+ name + "')"); - stepIndex++; - - return this; - } - - @Override - public QueryBuilder unfold() { - this.list.add(".unfold()"); - stepIndex++; - - return this; - } - - @Override - public QueryBuilder dedup() { - this.list.add(".dedup()"); - stepIndex++; - - return this; - } - - @Override - public QueryBuilder emit() { - this.list.add(".emit()"); - stepIndex++; - - return this; - } - - @Override - public QueryBuilder repeat(QueryBuilder builder) { - this.list.add(".repeat(__" + builder.getQuery() + ")"); - stepIndex++; - - return this; - } - - @Override - public QueryBuilder until(QueryBuilder builder) { - this.list.add(".until(__" + builder.getQuery() + ")"); - stepIndex++; - - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public QueryBuilder simplePath(){ - this.list.add(".simplePath()"); - stepIndex++; - return this; - } - - @Override - public QueryBuilder outE() { - this.list.add(".outE()"); - stepIndex++; - - return (QueryBuilder)this; - } - - @Override - public QueryBuilder inE() { - this.list.add(".inE()"); - stepIndex++; - - return (QueryBuilder)this; - } - - @Override - public QueryBuilder outV() { - this.list.add(".outV()"); - stepIndex++; - - return (QueryBuilder)this; - } - - @Override - public QueryBuilder inV() { - this.list.add(".inV()"); - stepIndex++; - - return (QueryBuilder)this; - } - - @Override - public QueryBuilder not(QueryBuilder builder) { - this.list.add(".not(" + "__" + builder.getQuery() + ")"); - stepIndex++; - - return this; - } - - @Override - public QueryBuilder as(String name) { - this.list.add(".as('" + name + "')"); - stepIndex++; - - return this; - } - - @Override - public QueryBuilder select(String name) { - this.list.add(".select('" + name + "')"); - stepIndex++; - - return this; - } - /** - * @{inheritDoc} - */ - @Override - public QueryBuilder getParentQuery() { - return cloneQueryAtStep(parentStepIndex); - } - - @Override - public QueryBuilder getContainerQuery() { - return cloneQueryAtStep(containerStepIndex); - } - - /** - * @{inheritDoc} - */ - @Override - public T2 getQuery() { - StringBuilder sb = new StringBuilder(); - - for (String piece : this.list) { - sb.append(piece); - } - - return (T2)sb.toString(); - } - - /** - * @{inheritDoc} - */ - @Override - public void markParentBoundary() { - parentStepIndex = stepIndex; - } - - @Override - public void markContainer() { - this.containerStepIndex = stepIndex; - } - - protected abstract QueryBuilder cloneQueryAtStep(int index); - /** - * @{inheritDoc} - */ - @Override - public Vertex getStart() { - return this.start; - } - - protected int getParentStepIndex() { - return parentStepIndex; - } - - protected int getContainerStepIndex() { - return containerStepIndex; - } - - protected int getStepIndex() { - return stepIndex; - } - - private void executeQuery() { - String queryString = "g" + Joiner.on("").join(list); - Map params = new HashMap<>(); - if (this.start == null) { - params.put("g", source.V()); - } else { - params.put("g", source.V(this.start)); - } - this.completeTraversal = this.gremlinGroovy.executeTraversal(queryString, params); - } - @Override - public boolean hasNext() { - if (this.completeTraversal == null) { - executeQuery(); - } - - return this.completeTraversal.hasNext(); - } - - @Override - public E next() { - if (this.completeTraversal == null) { - executeQuery(); - } - - return (E)this.completeTraversal.next(); - } - - @Override - public List toList() { - if (this.completeTraversal == null) { - executeQuery(); - } - - return (List)this.completeTraversal.toList(); - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/query/builder/GremlinTraversal.java b/aai-core/src/main/java/org/openecomp/aai/query/builder/GremlinTraversal.java deleted file mode 100644 index daf795fd..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/query/builder/GremlinTraversal.java +++ /dev/null @@ -1,136 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.query.builder; - -import java.io.UnsupportedEncodingException; -import java.net.URI; -import java.util.ArrayList; -import java.util.List; - -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.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.parsers.query.QueryParser; -import org.openecomp.aai.parsers.query.TraversalStrategy; - -/** - * The Class GremlinTraversal. - */ -public class GremlinTraversal extends GremlinQueryBuilder { - - /** - * 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 traversal, Loader loader, GraphTraversalSource source, GremlinQueryBuilder 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 queryParams) - throws UnsupportedEncodingException, AAIException { - return factory.buildURIParser(uri, queryParams); - } - - /** - * @{inheritDoc} - */ - @Override - public QueryParser createQueryFromObjectName(String objName) { - return factory.buildObjectNameParser(objName); - } - - /** - * @{inheritDoc} - */ - @Override - public QueryBuilder newInstance(Vertex start) { - return new GremlinTraversal<>(loader, source, start); - } - - /** - * @{inheritDoc} - */ - @Override - public QueryBuilder newInstance() { - return new GremlinTraversal<>(loader, source); - } - - @Override - protected QueryBuilder cloneQueryAtStep(int index) { - if (index == 0) { - index = stepIndex; - } - List newList = new ArrayList<>(); - for (int i = 0; i < index; i++) { - newList.add(this.list.get(i)); - } - - return new GremlinTraversal<>(newList, loader, source, this); - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/query/builder/GremlinUnique.java b/aai-core/src/main/java/org/openecomp/aai/query/builder/GremlinUnique.java deleted file mode 100644 index ee2353f1..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/query/builder/GremlinUnique.java +++ /dev/null @@ -1,137 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.query.builder; - -import java.io.UnsupportedEncodingException; -import java.net.URI; -import java.util.ArrayList; -import java.util.List; - -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.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.parsers.query.QueryParser; -import org.openecomp.aai.parsers.query.TraversalStrategy; -import org.openecomp.aai.parsers.query.UniqueStrategy; - -/** - * The Class GremlinUnique. - */ -public class GremlinUnique extends GremlinQueryBuilder { - - /** - * 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 traversal, Loader loader, GraphTraversalSource source, GremlinQueryBuilder 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 queryParams) - throws UnsupportedEncodingException, AAIException { - return factory.buildURIParser(uri, queryParams); - } - - /** - * @{inheritDoc} - */ - @Override - public QueryParser createQueryFromObjectName(String objName) { - return factory.buildObjectNameParser(objName); - } - - /** - * @{inheritDoc} - */ - @Override - public QueryBuilder newInstance() { - return new GremlinUnique<>(loader, source); - } - - /** - * @{inheritDoc} - */ - @Override - public QueryBuilder newInstance(Vertex start) { - return new GremlinUnique<>(loader, source, start); - } - - @Override - protected QueryBuilder cloneQueryAtStep(int index) { - if (index == 0) { - index = stepIndex; - } - List newList = new ArrayList<>(); - for (int i = 0; i < index; i++) { - newList.add(this.list.get(i)); - } - - return new GremlinUnique<>(newList, loader, source, this); - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/query/builder/QueryBuilder.java b/aai-core/src/main/java/org/openecomp/aai/query/builder/QueryBuilder.java deleted file mode 100644 index 717033fa..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/query/builder/QueryBuilder.java +++ /dev/null @@ -1,318 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.query.builder; - -import java.io.UnsupportedEncodingException; -import java.net.URI; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; - -import javax.ws.rs.core.MultivaluedMap; - -import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; -import org.apache.tinkerpop.gremlin.structure.Edge; -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.parsers.query.QueryParser; -import org.openecomp.aai.parsers.query.QueryParserStrategy; -import org.openecomp.aai.serialization.db.EdgeType; -import org.openecomp.aai.serialization.db.exceptions.NoEdgeRuleFoundException; - -/** - * The Class QueryBuilder. - */ -public abstract class QueryBuilder implements Iterator { - - protected QueryParserStrategy factory = null; - - protected Loader loader = null; - - protected boolean optimize = false; - - protected Vertex start = null; - protected final GraphTraversalSource source; - - /** - * Instantiates a new query builder. - * - * @param loader the loader - */ - public QueryBuilder(Loader loader, GraphTraversalSource source) { - this.loader = loader; - this.source = source; - } - - /** - * 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; - } - - /** - * Gets the vertices by indexed property. - * - * @param key the key - * @param value the value - * @return the vertices by indexed property - */ - public abstract QueryBuilder getVerticesByIndexedProperty(String key, Object value); - - /** - * Gets the vertices by property. - * - * @param key the key - * @param value the value - * @return the vertices by property - */ - public abstract QueryBuilder getVerticesByProperty(String key, Object value); - - /** - * filters by all the values for this property - * @param key - * @param values - * @return vertices that match these values - */ - public abstract QueryBuilder getVerticesByIndexedProperty(String key, List values); - - /** - * filters by all the values for this property - * @param key - * @param values - * @return vertices that match these values - */ - public abstract QueryBuilder getVerticesByProperty(String key, List values); - - /** - * 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 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 getTypedVerticesByMap(String type, LinkedHashMap map); - - /** - * Creates the DB query. - * - * @param obj the obj - * @return the query builder - */ - public abstract QueryBuilder createDBQuery(Introspector obj); - - /** - * Creates the key query. - * - * @param obj the obj - * @return the query builder - */ - public abstract QueryBuilder createKeyQuery(Introspector obj); - - /** - * Creates the container query. - * - * @param obj the obj - * @return the query builder - */ - public abstract QueryBuilder createContainerQuery(Introspector obj); - - /** - * Creates the edge traversal. - * - * @param parent the parent - * @param child the child - * @return the query builder - */ - public abstract QueryBuilder createEdgeTraversal(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 abstract QueryBuilder createEdgeTraversal(EdgeType type, Vertex parent, Introspector child) throws AAIException; - - public QueryBuilder createEdgeTraversal(EdgeType type, String outNodeType, String inNodeType) throws NoEdgeRuleFoundException, AAIException { - Introspector out = loader.introspectorFromName(outNodeType); - Introspector in = loader.introspectorFromName(inNodeType); - - return createEdgeTraversal(type, out, in); - } - - public abstract QueryBuilder getEdgesBetween(EdgeType type, String outNodeType, String inNodeType) 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 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 getParentQuery(); - - /** - * Gets the query. - * - * @return the query - */ - public abstract E2 getQuery(); - - /** - * Form boundary. - */ - public abstract void markParentBoundary(); - - public abstract QueryBuilder limit(long amount); - /** - * New instance. - * - * @param start the start - * @return the query builder - */ - public abstract QueryBuilder newInstance(Vertex start); - - /** - * New instance. - * - * @return the query builder - */ - public abstract QueryBuilder 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 exactMatchQuery(Introspector obj); - - /** - * lets you join any number of QueryBuilders - * be careful about starting with a union it will not use indexes - * @param builder - * @return - */ - public abstract QueryBuilder union(QueryBuilder... builder); - - public abstract QueryBuilder where(QueryBuilder... builder); - - public abstract QueryBuilder store(String name); - public abstract QueryBuilder cap(String name); - public abstract QueryBuilder unfold(); - public abstract QueryBuilder dedup(); - public abstract QueryBuilder emit(); - public abstract QueryBuilder repeat(QueryBuilder builder); - public abstract QueryBuilder outE(); - public abstract QueryBuilder inE(); - public abstract QueryBuilder inV(); - public abstract QueryBuilder outV(); - public abstract QueryBuilder not(QueryBuilder builder); - public abstract QueryBuilder as(String name); - public abstract QueryBuilder select(String name); - public abstract QueryBuilder until(QueryBuilder builder); - - /** - * 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 simplePath(); - - public abstract void markContainer(); - - public abstract QueryBuilder getContainerQuery(); - - public abstract List toList(); - - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/query/builder/TraversalQuery.java b/aai-core/src/main/java/org/openecomp/aai/query/builder/TraversalQuery.java deleted file mode 100644 index 628e055e..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/query/builder/TraversalQuery.java +++ /dev/null @@ -1,150 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.query.builder; - -import 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.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.parsers.query.QueryParser; -import org.openecomp.aai.parsers.query.TraversalStrategy; - -/** - * The Class TraversalQuery. - */ -public class TraversalQuery extends GraphTraversalBuilder { - - /** - * 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 traversal, Loader loader, GraphTraversalSource source, GraphTraversalBuilder 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 queryParams) - throws UnsupportedEncodingException, AAIException { - return factory.buildURIParser(uri, queryParams); - } - - /** - * @{inheritDoc} - */ - @Override - public QueryParser createQueryFromObjectName(String objName) { - return factory.buildObjectNameParser(objName); - } - - /** - * @{inheritDoc} - */ - @Override - public QueryBuilder newInstance(Vertex start) { - return new TraversalQuery<>(loader, source, start); - } - - /** - * @{inheritDoc} - */ - @Override - public QueryBuilder newInstance() { - return new TraversalQuery<>(loader, source); - } - - @Override - protected QueryBuilder cloneQueryAtStep(int index) { - if (index == 0) { - index = stepIndex; - } - GraphTraversal clone = this.traversal.asAdmin().clone(); - GraphTraversal.Admin cloneAdmin = clone.asAdmin(); - List steps = cloneAdmin.getSteps(); - - for (int i = steps.size()-1; i >= index; i--) { - cloneAdmin.removeStep(i); - } - return new TraversalQuery<>(cloneAdmin, loader, source, this); - } - - @Override - protected QueryBuilder removeQueryStepsBetween(int start, int end) { - GraphTraversal clone = this.traversal.asAdmin().clone(); - GraphTraversal.Admin 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/openecomp/aai/rest/RestTokens.java b/aai-core/src/main/java/org/openecomp/aai/rest/RestTokens.java deleted file mode 100644 index 13bfe650..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/rest/RestTokens.java +++ /dev/null @@ -1,36 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.rest; - -public enum RestTokens { - - COUSIN("related-to"); - private final String name; - - private RestTokens(String name) { - this.name = name; - } - - @Override - public String toString() { - return name; - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/rest/db/DBRequest.java b/aai-core/src/main/java/org/openecomp/aai/rest/db/DBRequest.java deleted file mode 100644 index e7b68588..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/rest/db/DBRequest.java +++ /dev/null @@ -1,251 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.rest.db; - -import java.net.URI; -import java.util.Optional; - -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.UriInfo; - -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.MarshallerProperties; -import org.openecomp.aai.parsers.query.QueryParser; -import org.openecomp.aai.restcore.HttpMethod; - -/** - * The Class DBRequest. - */ -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 rawRequestContent; - - private final Optional 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 getRawRequestContent() { - return rawRequestContent; - } - - public Optional 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 = Optional.empty(); - - private Optional 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 getMarshallerProperties() { - return marshallerProperties; - } - protected Optional getRawRequestContent() { - return rawRequestContent; - } - public DBRequest build() { - - return new DBRequest(this); - } - - - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/rest/db/HttpEntry.java b/aai-core/src/main/java/org/openecomp/aai/rest/db/HttpEntry.java deleted file mode 100644 index 226e6023..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/rest/db/HttpEntry.java +++ /dev/null @@ -1,566 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.rest.db; - -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.lang.reflect.InvocationTargetException; -import java.net.MalformedURLException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Set; - -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.Status; -import javax.ws.rs.core.UriBuilder; - -import org.apache.commons.lang.StringUtils; -import org.apache.tinkerpop.gremlin.structure.Graph; -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.javatuples.Pair; -import org.openecomp.aai.db.props.AAIProperties; -import org.openecomp.aai.dbmap.DBConnectionType; -import org.openecomp.aai.domain.responseMessage.AAIResponseMessage; -import org.openecomp.aai.domain.responseMessage.AAIResponseMessageDatum; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.introspection.LoaderFactory; -import org.openecomp.aai.introspection.MarshallerProperties; -import org.openecomp.aai.introspection.ModelInjestor; -import org.openecomp.aai.introspection.ModelType; -import org.openecomp.aai.introspection.Version; -import org.openecomp.aai.introspection.exceptions.AAIUnknownObjectException; -import org.openecomp.aai.logging.ErrorLogHelper; -import org.openecomp.aai.parsers.query.QueryParser; -import org.openecomp.aai.parsers.uri.URIToExtensionInformation; -import org.openecomp.aai.rest.ueb.UEBNotification; -import org.openecomp.aai.restcore.HttpMethod; -import org.openecomp.aai.schema.enums.ObjectMetadata; -import org.openecomp.aai.serialization.db.DBSerializer; -import org.openecomp.aai.serialization.engines.QueryStyle; -import org.openecomp.aai.serialization.engines.TitanDBEngine; -import org.openecomp.aai.serialization.engines.TransactionalGraphEngine; -import org.openecomp.aai.serialization.engines.query.QueryEngine; - -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 com.thinkaurelius.titan.core.TitanException; - -/** - * The Class HttpEntry. - */ -public class HttpEntry { - - private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(HttpEntry.class); - - private final ModelType introspectorFactoryType; - - private final QueryStyle queryStyle; - - private final Version version; - - private final Loader loader; - - private final TransactionalGraphEngine dbEngine; - - private boolean processSingle = true; - - /** - * Instantiates a new http entry. - * - * @param version the version - * @param modelType the model type - * @param queryStyle the query style - * @param llBuilder the ll builder - */ - public HttpEntry(Version version, ModelType modelType, QueryStyle queryStyle, DBConnectionType connectionType) { - this.introspectorFactoryType = modelType; - this.queryStyle = queryStyle; - this.version = version; - this.loader = LoaderFactory.createLoaderForVersion(introspectorFactoryType, version); - this.dbEngine = new TitanDBEngine( - queryStyle, - connectionType, - loader); - //start transaction on creation - dbEngine.startTransaction(); - - } - - /** - * 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 Version 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>> process (List requests, String sourceOfTruth) throws AAIException { - return this.process(requests, sourceOfTruth, true); - } - /** - * Process. - * @param requests the requests - * @param sourceOfTruth the source of truth - * - * @return the pair - * @throws AAIException the AAI exception - */ - public Pair>> process (List requests, String sourceOfTruth, boolean enableResourceVersion) throws AAIException { - DBSerializer serializer = new DBSerializer(version, dbEngine, introspectorFactoryType, sourceOfTruth); - Response response = null; - Status status = Status.NOT_FOUND; - Introspector obj = null; - QueryParser query = null; - URI uri = null; - String transactionId = null; - UEBNotification notification = new UEBNotification(loader); - int depth = AAIProperties.MAXIMUM_DEPTH; - List> responses = new ArrayList<>(); - MultivaluedMap params = null; - HttpMethod method = null; - String uriTemp = ""; - Boolean success = true; - QueryEngine queryEngine = dbEngine.getQueryEngine(); - int maxRetries = 10; - int retry = 0; - for (DBRequest request : requests) { - try { - for (retry = 0; retry < maxRetries; ++retry) { - try { - method = request.getMethod(); - obj = request.getIntrospector(); - query = request.getParser(); - transactionId = request.getTransactionId(); - uriTemp = request.getUri().getRawPath().replaceFirst("^v\\d+/", ""); - uri = UriBuilder.fromPath(uriTemp).build(); - List 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")); - String cleanUp = params.getFirst("cleanup"); - String requestContext = ""; - List 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)) { - if (method.equals(HttpMethod.DELETE)) { - throw new AAIException("AAI_6138"); - } else { - 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(), (String)vertices.get(0).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 relatedObjects = new HashMap<>(); - switch (method) { - case GET: - String nodeOnly = params.getFirst("nodes-only"); - boolean isNodeOnly = nodeOnly != null; - - obj = this.getObjectFromDb(vertices, serializer, query, obj, request.getUri(), depth, isNodeOnly, cleanUp); - if (obj != null) { - status = Status.OK; - MarshallerProperties properties; - if (!request.getMarshallerProperties().isPresent()) { - properties = - new MarshallerProperties.Builder(org.openecomp.aai.restcore.MediaType.getEnum(outputMediaType)).build(); - } else { - properties = request.getMarshallerProperties().get(); - } - result = obj.marshal(properties); - } - - break; - case PUT: - if (isNewVertex) { - v = serializer.createNewVertex(obj); - } - serializer.serializeToDb(obj, v, query, uri.getRawPath(), requestContext); - status = Status.OK; - if (isNewVertex) { - status = Status.CREATED; - } - obj = serializer.getLatestVersionView(v); - if (query.isDependent()) { - relatedObjects = this.getRelatedObjects(serializer, queryEngine, v); - } - notification.createNotificationEvent(transactionId, sourceOfTruth, status, uri, obj, relatedObjects); - break; - case PUT_EDGE: - serializer.touchStandardVertexProperties(v, false); - serializer.createEdge(obj, v); - status = Status.OK; - break; - case MERGE_PATCH: - Introspector existingObj = (Introspector) obj.clone(); - 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); - } - notification.createNotificationEvent(transactionId, sourceOfTruth, status, uri, patchedObj, relatedObjects); - } catch (IOException | JsonPatchException e) { - 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); - } - serializer.delete(v, resourceVersion, enableResourceVersion); - status = Status.NO_CONTENT; - notification.createNotificationEvent(transactionId, sourceOfTruth, status, uri, obj, relatedObjects); - break; - case DELETE_EDGE: - serializer.touchStandardVertexProperties(v, false); - serializer.deleteEdge(obj, v); - status = Status.NO_CONTENT; - 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)) - ) { - String myvertid = v.id().toString(); - 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 pairedResp = Pair.with(request.getUri(), response); - responses.add(pairedResp); - //break out of retry loop - break; - } catch (TitanException e) { - this.dbEngine.rollback(); - AAIException ex = new AAIException("AAI_6142", e); - ErrorLogHelper.logException(ex); - Thread.sleep((retry + 1) * 20); - 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 templateVars = new ArrayList(); - templateVars.add(request.getMethod().toString()); //GET, PUT, etc - templateVars.add(request.getUri().getPath().toString()); - templateVars.addAll(e.getTemplateVars()); - - response = Response - .status(e.getErrorObject().getHTTPResponseCode()) - .entity(ErrorLogHelper.getRESTAPIErrorResponse(request.getHeaders().getAcceptableMediaTypes(), e, templateVars)) - .build(); - Pair 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 templateVars = new ArrayList(); - templateVars.add(request.getMethod().toString()); //GET, PUT, etc - templateVars.add(request.getUri().getPath().toString()); - - response = Response - .status(ex.getErrorObject().getHTTPResponseCode()) - .entity(ErrorLogHelper.getRESTAPIErrorResponse(request.getHeaders().getAcceptableMediaTypes(), ex, templateVars)) - .build(); - Pair pairedResp = Pair.with(request.getUri(), response); - responses.add(pairedResp); - continue; - } - } - - notification.triggerEvents(); - Pair>> tuple = Pair.with(success, responses); - return tuple; - } - - /** - * Gets the media type. - * - * @param mediaTypeList the media type list - * @return the media type - */ - private String getMediaType(List 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 g the g - * @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 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.size() == 0) { - String msg = createNotFoundMessage(query.getResultType(), uri); - throw new AAIException("AAI_6114", msg); - } - - obj = serializer.dbToObject(results, obj, depth, nodeOnly, cleanUp); - - return obj; - } - - - /** - * 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; - } - - /** - * 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; - - if(depthParam == null){ - if(this.version.compareTo(Version.v9) >= 0){ - depth = 0; - } else { - depth = AAIProperties.MAXIMUM_DEPTH; - } - } else { - if (depthParam.length() > 0 && !depthParam.equals("all")){ - try { - depth = Integer.valueOf(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; - - } - - private HashMap getRelatedObjects(DBSerializer serializer, QueryEngine queryEngine, Vertex v) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException, InstantiationException, NoSuchMethodException, UnsupportedEncodingException, AAIException, URISyntaxException { - HashMap relatedVertices = new HashMap<>(); - List vertexChain = queryEngine.findParents(v); - 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"); - } - - } - - return relatedVertices; - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/rest/ueb/NotificationEvent.java b/aai-core/src/main/java/org/openecomp/aai/rest/ueb/NotificationEvent.java deleted file mode 100644 index e473e9da..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/rest/ueb/NotificationEvent.java +++ /dev/null @@ -1,99 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.rest.ueb; - -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.introspection.Version; -import org.openecomp.aai.util.StoreNotificationEvent; - -/** - * The Class NotificationEvent. - */ -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 version the version - * @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 Version 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/openecomp/aai/rest/ueb/UEBNotification.java b/aai-core/src/main/java/org/openecomp/aai/rest/ueb/UEBNotification.java deleted file mode 100644 index fdba3081..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/rest/ueb/UEBNotification.java +++ /dev/null @@ -1,176 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.rest.ueb; - -import java.io.UnsupportedEncodingException; -import java.net.URI; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -import javax.ws.rs.core.Response.Status; - -import org.openecomp.aai.db.props.AAIProperties; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.introspection.LoaderFactory; -import org.openecomp.aai.introspection.Version; -import org.openecomp.aai.introspection.exceptions.AAIUnknownObjectException; -import org.openecomp.aai.introspection.exceptions.AAIUnmarshallingException; -import org.openecomp.aai.parsers.uri.URIToObject; -import org.openecomp.aai.util.AAIConfig; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -/** - * The Class UEBNotification. - */ -public class UEBNotification { - - private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(UEBNotification.class); - - private Loader currentVersionLoader = null; - protected List events = null; - private Version notificationVersion = null; - - /** - * Instantiates a new UEB notification. - * - * @param loader the loader - */ - public UEBNotification(Loader loader) { - events = new ArrayList<>(); - currentVersionLoader = LoaderFactory.createLoaderForVersion(loader.getModelType(), AAIProperties.LATEST); - notificationVersion = Version.valueOf(AAIConfig.get("aai.notification.current.version","v11")); - } - - - /** - * Creates the notification event. - * - * @param transactionId the X-TransactionId - * @param sourceOfTruth - * @param status the status - * @param uri the uri - * @param obj the obj - * @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 relatedObjects) 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 (uri.toString().startsWith("/")) { - entityLink = "/aai/" + notificationVersion + uri; - } else { - entityLink = "/aai/" + 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 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", e); - } - } - - /** - * Trigger events. - * - * @throws AAIException the AAI exception - */ - public void triggerEvents() throws AAIException { - for (NotificationEvent event : events) { - event.trigger(); - } - events.clear(); - } - - public List getEvents() { - return this.events; - } - - - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/restcore/CustomJacksonJaxBJsonProvider.java b/aai-core/src/main/java/org/openecomp/aai/restcore/CustomJacksonJaxBJsonProvider.java deleted file mode 100644 index 1748fd62..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/restcore/CustomJacksonJaxBJsonProvider.java +++ /dev/null @@ -1,71 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.restcore; - -import javax.ws.rs.ext.Provider; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; -import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider; -import com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule; - -/** - * The Class CustomJacksonJaxBJsonProvider. - */ -@Provider -public class CustomJacksonJaxBJsonProvider extends JacksonJaxbJsonProvider { - - 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); - - 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.registerModule(new JaxbAnnotationModule()); - - commonMapper = mapper; - } - super.setMapper(commonMapper); - } - - /** - * Gets the mapper. - * - * @return the mapper - */ - public ObjectMapper getMapper() { - return commonMapper; - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/restcore/HttpMethod.java b/aai-core/src/main/java/org/openecomp/aai/restcore/HttpMethod.java deleted file mode 100644 index 3dab68ee..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/restcore/HttpMethod.java +++ /dev/null @@ -1,33 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.restcore; - -/** - * The Enum HttpMethod. - */ -public enum HttpMethod { - PUT, - MERGE_PATCH, - DELETE, - PUT_EDGE, - DELETE_EDGE, - GET; -} diff --git a/aai-core/src/main/java/org/openecomp/aai/restcore/JettyObfuscationConversionCommandLineUtil.java b/aai-core/src/main/java/org/openecomp/aai/restcore/JettyObfuscationConversionCommandLineUtil.java deleted file mode 100644 index b2e2d9f8..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/restcore/JettyObfuscationConversionCommandLineUtil.java +++ /dev/null @@ -1,97 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.restcore; - -import org.apache.commons.cli.BasicParser; -import org.apache.commons.cli.CommandLine; -import org.apache.commons.cli.CommandLineParser; -import org.apache.commons.cli.Options; -import org.apache.commons.cli.ParseException; -import org.eclipse.jetty.util.security.Password; - -/* - * The purpose of this class is to be a tool for - * manually applying jetty obfuscation/deobfuscation - * so that one can obfuscate the various passwords/secrets - * in aaiconfig.properties. - * - * Originally, they were being encrypted by a similar - * command line utility, however the encryption key - * was being hardcoded in the src package - * which is a security violation. - * Since this ultimately just moved the problem of how - * to hide secrets to a different secret in a different file, - * and since that encryption was really just being done to - * obfuscate those values in case someone needed to look at - * properties with others looking at their screen, - * we decided that jetty obfuscation would be adequate - * for that task as well as - * removing the "turtles all the way down" secret-to-hide- - * 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"); - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/restcore/MediaType.java b/aai-core/src/main/java/org/openecomp/aai/restcore/MediaType.java deleted file mode 100644 index c6eb13ec..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/restcore/MediaType.java +++ /dev/null @@ -1,66 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.restcore; - -/** - * The Enum MediaType. - */ -public enum MediaType { - APPLICATION_JSON_TYPE("application/json"), - APPLICATION_XML_TYPE("application/xml"); - - private final String text; - - /** - * Instantiates a new media type. - * - * @param text the text - */ - private MediaType(final String text) { - this.text = text; - } - - /** - * Gets the enum. - * - * @param value the value - * @return the enum - */ - public static MediaType getEnum(String value) { - - for(MediaType v : values()) { - if(v.toString().equalsIgnoreCase(value)) { - return v; - } - } - - throw new IllegalArgumentException("bad value: " + value); - - } - - /** - * @{inheritDoc} - */ - @Override - public String toString() { - return text; - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/restcore/RESTAPI.java b/aai-core/src/main/java/org/openecomp/aai/restcore/RESTAPI.java deleted file mode 100644 index 18aef073..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/restcore/RESTAPI.java +++ /dev/null @@ -1,277 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.restcore; - -import java.io.UnsupportedEncodingException; -import java.net.URI; -import java.util.ArrayList; -import java.util.List; - -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriInfo; - -import org.openecomp.aai.db.props.AAIProperties; -import org.openecomp.aai.dbmap.DBConnectionType; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.introspection.tools.CreateUUID; -import org.openecomp.aai.introspection.tools.DefaultFields; -import org.openecomp.aai.introspection.tools.InjectKeysFromURI; -import org.openecomp.aai.introspection.tools.IntrospectorValidator; -import org.openecomp.aai.introspection.tools.Issue; -import org.openecomp.aai.introspection.tools.RemoveNonVisibleProperty; -import org.openecomp.aai.logging.ErrorLogHelper; -import org.openecomp.aai.logging.LoggingContext; -import org.openecomp.aai.util.AAIConfig; -import org.openecomp.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 - * @param logline the logline - * @return the from app id - * @throws AAIException the AAI exception - */ - protected String getFromAppId(HttpHeaders headers) throws AAIException { - String fromAppId = null; - if (headers != null) { - List 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 - * @param logline the logline - * @return the trans id - * @throws AAIException the AAI exception - */ - protected String getTransId(HttpHeaders headers) throws AAIException { - String transId = null; - if (headers != null) { - List 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 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 templateVars = new ArrayList(); - templateVars.add(templateAction.toString()); //GET, PUT, etc - templateVars.add(info.getPath().toString()); - templateVars.addAll(e.getTemplateVars()); - - 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 - * @param validateRequired the validate required - * @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 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 - String testURI = "/" + uri.getRawPath(); - if (!testURI.endsWith(objURI)) { - throw new AAIException("AAI_3000", "uri and payload keys don't match"); - } - } - - protected DBConnectionType determineConnectionType(String fromAppId, String realTime) { - 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; - - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/restcore/search/GremlinGroovyShellSingleton.java b/aai-core/src/main/java/org/openecomp/aai/restcore/search/GremlinGroovyShellSingleton.java deleted file mode 100644 index b098dcc4..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/restcore/search/GremlinGroovyShellSingleton.java +++ /dev/null @@ -1,90 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.restcore.search; - -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; -import org.codehaus.groovy.ast.expr.PropertyExpression; -import org.codehaus.groovy.control.CompilerConfiguration; -import org.codehaus.groovy.control.customizers.ASTTransformationCustomizer; -import org.codehaus.groovy.control.customizers.ImportCustomizer; - -import groovy.lang.Binding; -import groovy.lang.GroovyShell; -import groovy.lang.Script; -import groovy.transform.TimedInterrupt; - -/** - * Creates and returns a groovy shell with the - * configuration to statically import graph classes - * - */ -public class GremlinGroovyShellSingleton { - - private final GroovyShell shell; - private GremlinGroovyShellSingleton() { - Map 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" - ); - imports.addImports( - "org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__", - "org.apache.tinkerpop.gremlin.structure.T", - "org.apache.tinkerpop.gremlin.process.traversal.P", - "java.util.Map.Entry"); - imports.addStarImports("java.util"); - CompilerConfiguration config = new CompilerConfiguration(); - config.addCompilationCustomizers(custom, imports); - - this.shell = new GroovyShell(config); - } - - private static class Helper { - private static final GremlinGroovyShellSingleton INSTANCE = new GremlinGroovyShellSingleton(); - } - - public static GremlinGroovyShellSingleton getInstance() { - - return Helper.INSTANCE; - } - - /** - * @param traversal - * @param params - * @return result of graph traversal - */ - public GraphTraversal executeTraversal (String traversal, Map params) { - Binding binding = new Binding(params); - Script script = shell.parse(traversal); - script.setBinding(binding); - return (GraphTraversal) script.run(); - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/restcore/util/GenerateEdgeRules.java b/aai-core/src/main/java/org/openecomp/aai/restcore/util/GenerateEdgeRules.java deleted file mode 100644 index 082d6151..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/restcore/util/GenerateEdgeRules.java +++ /dev/null @@ -1,154 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.restcore.util; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import freemarker.template.Configuration; -import freemarker.template.Template; -import freemarker.template.TemplateException; - -import java.io.*; -import java.util.*; - -public class GenerateEdgeRules { - - private static final EELFLogger LOG = EELFManager.getInstance().getLogger(GenerateEdgeRules.class); - - public static void main(String[] args) throws IOException, TemplateException { - - String filename = "/AAI8032.csv"; - InputStream inputStream = GenerateEdgeRules.class.getResourceAsStream(filename); - Map headers = new HashMap<>(); - Map edgeRulesMap = new TreeMap(); - List> edgeRules = new ArrayList<>(); - - try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) { - - String line = null; - - int rowNum = 0; - - // Retrieve the header line to map the indexes to their column names - - while ((line = reader.readLine()) != null) { - - if (rowNum == 0) { - headers = retrieveHeaderMap(line); - } else { - String[] columns = line.split(","); - - String originalNode = columns[headers.get("Orig NodeA|NodeB")]; - String finalNode = columns[headers.get("Final NodeA|NodeB")]; - String originalEdge = columns[headers.get("Orig EdgeLabel")]; - String finalEdge = columns[headers.get("Final EdgeLabel")]; - - String lineage = columns[headers.get("Final Lineage")]; - String originalParent = columns[headers.get("Orig ParentOf")]; - String usesResource = columns[headers.get("Revised UsesResource")]; - String hasDelTarget = columns[headers.get("Revised hasDelTarget")]; - String svcInfra = columns[headers.get("Final SVC-INFRA")]; - String svcInfraRev = ""; - - if(usesResource.equals("T")) - usesResource = "true"; - else if(usesResource.equals("F")) - usesResource = "false"; - - if (hasDelTarget.equals("T") || hasDelTarget.equals("AB")) { - hasDelTarget = "true"; - } else if (hasDelTarget.equals("F")) { - hasDelTarget = "false"; - } - - if (svcInfra.equals("T")) { - svcInfra = "true"; - } else if (svcInfra.equals("F")) { - svcInfra = "false"; - } else if (svcInfra.equals("R")) { - svcInfra = "reverse"; - } - - if (originalParent.equals("T")) { - if (lineage.trim().equalsIgnoreCase("CHILD")) { - lineage = "true"; - } else if (lineage.trim().equalsIgnoreCase("PARENT")) { - lineage = "reverse"; - } - } else { - lineage = "false"; - } - - Map edgeMap = new HashMap(); - - edgeMap.put("lineage", lineage); - edgeMap.put("usesResource", usesResource); - edgeMap.put("hasDelTarget", hasDelTarget); - edgeMap.put("SVC-INFRA", svcInfra); - edgeMap.put("SVC-INFRA-REV", svcInfraRev); - edgeMap.put("nodes", finalNode); - edgeMap.put("edge", finalEdge); - edgeMap.put("direction", columns[headers.get("Orig Direction")]); - edgeMap.put("multiplicity", columns[headers.get("Revised Multiplicity")]); - - edgeRules.add(edgeMap); - - } - ++rowNum; - } - } catch(Exception ex){ - ex.printStackTrace(); - } - - edgeRulesMap.put("edgeRules", edgeRules); - - Collections.sort(edgeRules, new Comparator>() { - @Override - public int compare(Map o1, Map o2) { - return o1.get("nodes").compareTo(o2.get("nodes")); - } - }); - - Configuration configuration = new Configuration(); - Template template = configuration.getTemplate("ajsc-aai/src/main/resources/EdgeRules.ftl"); - Writer file = new FileWriter(new File("ajsc-aai/src/main/resources" + "/" + "EdgeRules.txt")); - template.process(edgeRulesMap, file); - } - - private static Map retrieveHeaderMap(String line){ - - if(line == null) - throw new NullPointerException(); - - String[] columnNames = line.split(","); - - Map map = new HashMap(); - - int index = 0; - - for(String columnName : columnNames){ - map.put(columnName, index++); - } - - return map; - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/restcore/util/URITools.java b/aai-core/src/main/java/org/openecomp/aai/restcore/util/URITools.java deleted file mode 100644 index 0a91d765..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/restcore/util/URITools.java +++ /dev/null @@ -1,113 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.restcore.util; - -import java.io.UnsupportedEncodingException; -import java.net.URI; -import java.util.HashMap; -import java.util.LinkedHashSet; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Optional; -import java.util.Set; -import java.util.regex.Matcher; -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.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.sideeffect.exceptions.AAIMissingRequiredPropertyException; -import org.openecomp.aai.schema.enums.PropertyMetadata; - -public class URITools { - - protected static final Pattern template = Pattern.compile("\\{(.*?)\\}"); - - public static MultivaluedMap getQueryMap(URI uri) { - MultivaluedMap 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"); - 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 replaceTemplates(Introspector obj, String uriString, PropertyMetadata metadata, boolean replaceWithWildcard) throws AAIMissingRequiredPropertyException { - String result = uriString; - final Map propMap = URITools.findProperties(obj, uriString, metadata, replaceWithWildcard); - if (propMap.isEmpty()) { - return Optional.empty(); - } - for (Entry 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 findProperties(Introspector obj, String uriString, PropertyMetadata metadata, boolean replaceWithWildcard) throws AAIMissingRequiredPropertyException { - - final Map result = new HashMap<>(); - final Set 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/openecomp/aai/serialization/db/AAIDirection.java b/aai-core/src/main/java/org/openecomp/aai/serialization/db/AAIDirection.java deleted file mode 100644 index fe9be364..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/db/AAIDirection.java +++ /dev/null @@ -1,34 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.serialization.db; - -public enum AAIDirection { - IN, OUT, BOTH, NONE; - - public AAIDirection opposite() { - if (this.equals(OUT)) - return IN; - else if (this.equals(IN)) - return OUT; - else - return BOTH; - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/db/DBSerializer.java b/aai-core/src/main/java/org/openecomp/aai/serialization/db/DBSerializer.java deleted file mode 100644 index 09d405a7..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/db/DBSerializer.java +++ /dev/null @@ -1,1443 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.serialization.db; - - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.google.common.base.CaseFormat; -import com.thinkaurelius.titan.core.SchemaViolationException; -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.__; -import org.apache.tinkerpop.gremlin.process.traversal.step.util.Tree; -import org.apache.tinkerpop.gremlin.structure.*; -import org.javatuples.Pair; -import org.openecomp.aai.db.props.AAIProperties; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.*; -import org.openecomp.aai.introspection.exceptions.AAIUnknownObjectException; -import org.openecomp.aai.introspection.sideeffect.DataCopy; -import org.openecomp.aai.introspection.sideeffect.DataLinkReader; -import org.openecomp.aai.introspection.sideeffect.DataLinkWriter; -import org.openecomp.aai.introspection.sideeffect.SideEffectRunner; -import org.openecomp.aai.logging.ErrorLogHelper; -import org.openecomp.aai.parsers.query.QueryParser; -import org.openecomp.aai.parsers.uri.URIParser; -import org.openecomp.aai.parsers.uri.URIToRelationshipObject; -import org.openecomp.aai.query.builder.QueryBuilder; -import org.openecomp.aai.schema.enums.ObjectMetadata; -import org.openecomp.aai.schema.enums.PropertyMetadata; -import org.openecomp.aai.serialization.db.exceptions.NoEdgeRuleFoundException; -import org.openecomp.aai.serialization.engines.TransactionalGraphEngine; -import org.openecomp.aai.serialization.tinkerpop.TreeBackedVertex; -import org.openecomp.aai.util.AAIApiServerURLBase; -import org.openecomp.aai.util.AAIConfig; -import org.openecomp.aai.util.AAIConstants; -import org.openecomp.aai.workarounds.NamingExceptions; - -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.Callable; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Future; - -public class DBSerializer { - - private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(DBSerializer.class); - - private final TransactionalGraphEngine engine; - private final String sourceOfTruth; - private final ModelType introspectionType; - private final Version version; - private final Loader latestLoader; - private final EdgeRules edgeRules = EdgeRules.getInstance(); - private final Loader loader; - private final String baseURL; - /** - * Instantiates a new DB serializer. - * - * @param version the version - * @param engine the engine - * @param g the g - * @param introspectionType the introspection type - * @param sourceOfTruth the source of truth - * @param llBuilder the ll builder - * @throws AAIException - */ - public DBSerializer(Version version, TransactionalGraphEngine engine, ModelType introspectionType, String sourceOfTruth) throws AAIException { - this.engine = engine; - this.sourceOfTruth = sourceOfTruth; - this.introspectionType = introspectionType; - this.latestLoader = LoaderFactory.createLoaderForVersion(introspectionType, AAIProperties.LATEST); - this.version = version; - this.loader = LoaderFactory.createLoaderForVersion(introspectionType, version); - this.baseURL = AAIApiServerURLBase.get(version); - } - - /** - * Touch standard vertex properties. - * - * @param v the v - * @param isNewVertex the is new vertex - */ - public void touchStandardVertexProperties(Vertex v, boolean isNewVertex) { - - long unixTimeNow = System.currentTimeMillis(); - String timeNowInSec = "" + unixTimeNow; - if (isNewVertex) { - v.property(AAIProperties.SOURCE_OF_TRUTH, this.sourceOfTruth); - v.property(AAIProperties.CREATED_TS, timeNowInSec); - } - v.property(AAIProperties.RESOURCE_VERSION, timeNowInSec ); - v.property(AAIProperties.LAST_MOD_TS, timeNowInSec); - v.property(AAIProperties.LAST_MOD_SOURCE_OF_TRUTH, this.sourceOfTruth); - - } - - private void touchStandardVertexProperties(String nodeType, Vertex v, boolean isNewVertex) { - - v.property(AAIProperties.NODE_TYPE, nodeType); - touchStandardVertexProperties(v, isNewVertex); - - } - - - - /** - * Creates the new vertex. - * - * @param wrappedObject the wrapped object - * @return the vertex - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - */ - public Vertex createNewVertex(Introspector wrappedObject) { - - - Vertex v = this.engine.tx().addVertex(); - touchStandardVertexProperties(wrappedObject.getDbName(), v, true); - - return v; - } - - /** - * Trim class name. - * - * @param className the class name - * @return the string - */ - /* - * Removes the classpath from a class name - */ - public String trimClassName (String className) { - String returnValue = ""; - - if (className.lastIndexOf('.') == -1) { - return className; - } - returnValue = className.substring(className.lastIndexOf('.') + 1, className.length()); - - return returnValue; - } - - /** - * Serialize to db. - * - * @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 UnsupportedEncodingException the unsupported encoding exception - * @throws AAIUnknownObjectException - */ - public void serializeToDb(Introspector obj, Vertex v, QueryParser uriQuery, String identifier, String requestContext) throws AAIException, UnsupportedEncodingException { - - try { - if (uriQuery.isDependent()) { - //try to find the parent - List vertices = uriQuery.getQueryBuilder().getParentQuery().toList(); - if (!vertices.isEmpty()) { - Vertex parent = vertices.get(0); - this.reflectDependentVertex(parent, v, obj, requestContext); - } else { - throw new AAIException("AAI_6114", "No parent Node of type " + uriQuery.getParentResultType() + " for " + identifier); - } - } else { - serializeSingleVertex(v, obj, requestContext); - } - - } catch (SchemaViolationException e) { - throw new AAIException("AAI_6117", e); - } - - } - - public void serializeSingleVertex(Vertex v, Introspector obj, String requestContext) throws UnsupportedEncodingException, AAIException { - try { - boolean isTopLevel = obj.isTopLevel(); - if (isTopLevel) { - v.property(AAIProperties.AAI_URI, obj.getURI()); - } - processObject(obj, v, requestContext); - if (!isTopLevel) { - URI uri = this.getURIForVertex(v); - URIParser parser = new URIParser(this.loader, uri); - if (parser.validate()) { - VertexProperty uriProp = v.property(AAIProperties.AAI_URI); - if (!uriProp.isPresent() || uriProp.isPresent() && !uriProp.value().equals(uri.toString())) { - v.property(AAIProperties.AAI_URI, uri.toString()); - } - } - } - } catch (SchemaViolationException e) { - throw new AAIException("AAI_6117", e); - } - } - - /** - * Process object. - * - * @param the generic type - * @param obj the obj - * @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 UnsupportedEncodingException the unsupported encoding exception - * @throws AAIUnknownObjectException - */ - /* - * Helper method for reflectToDb - * Handles all the property setting - */ - private List processObject (Introspector obj, Vertex v, String requestContext) throws UnsupportedEncodingException, AAIException { - Set properties = new LinkedHashSet<>(obj.getProperties()); - properties.remove(AAIProperties.RESOURCE_VERSION); - List dependentVertexes = new ArrayList<>(); - List processedVertexes = new ArrayList<>(); - boolean isComplexType = false; - boolean isListType = false; - if (!obj.isContainer()) { - this.touchStandardVertexProperties(obj.getDbName(), v, false); - } - this.executePreSideEffects(obj, v); - for (String property : properties) { - Object value = null; - final String propertyType; - propertyType = obj.getType(property); - isComplexType = obj.isComplexType(property); - isListType = obj.isListType(property); - value = obj.getValue(property); - - if (!(isComplexType || isListType)) { - boolean canModify = this.canModify(obj, property, requestContext); - - if (canModify) { - final Map metadata = obj.getPropertyMetadata(property); - String dbProperty = property; - if (metadata.containsKey(PropertyMetadata.DB_ALIAS)) { - dbProperty = metadata.get(PropertyMetadata.DB_ALIAS); - } - if (metadata.containsKey(PropertyMetadata.DATA_LINK)) { - //data linked properties are ephemeral - //they are populated dynamically on GETs - continue; - } - if (value != null) { - if (!value.equals(v.property(dbProperty).orElse(null))) { - if (propertyType.toLowerCase().contains(".long")) { - v.property(dbProperty, new Integer(((Long)value).toString())); - } else { - v.property(dbProperty, value); - } - } - } else { - v.property(dbProperty).remove(); - } - } - } else if (isListType) { - List list = (List)value; - if (obj.isComplexGenericType(property)) { - if (list != null) { - for (Object o : list) { - Introspector child = IntrospectorFactory.newInstance(this.introspectionType, o); - child.setURIChain(obj.getURI()); - processedVertexes.add(reflectDependentVertex(v, child, requestContext)); - } - } - } else { - //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 - if (value.getClass().isArray()) { - - int length = Array.getLength(value); - for (int i = 0; i < length; i ++) { - Object arrayElement = Array.get(value, i); - Introspector child = IntrospectorFactory.newInstance(this.introspectionType, arrayElement); - child.setURIChain(obj.getURI()); - processedVertexes.add(reflectDependentVertex(v, child, requestContext)); - - } - } else if (!property.equals("relationship-list")) { - // container case - Introspector introspector = IntrospectorFactory.newInstance(this.introspectionType, value); - if (introspector.isContainer()) { - 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())); - processedVertexes.add(reflectDependentVertex(v, introspector, requestContext)); - - } - } else if (property.equals("relationship-list")) { - handleRelationships(obj, v); - } - } - } - } - this.writeThroughDefaults(v, obj); - /* handle those vertexes not touched */ - for (Vertex toBeRemoved : processedVertexes) { - dependentVertexes.remove(toBeRemoved); - } - this.deleteItemsWithTraversal(dependentVertexes); - - this.executePostSideEffects(obj, v); - return processedVertexes; - } - - /** - * Handle relationships. - * - * @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 UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - */ - /* - * Handles the explicit relationships defined for an obj - */ - 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 - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - */ - private void processRelationshipList(Introspector wrapped, Vertex v) throws UnsupportedEncodingException, AAIException { - - List relationships = (List)wrapped.getValue("relationship"); - - List> addEdges = new ArrayList<>(); - List existingEdges = this.engine.getQueryEngine().findEdgesForVersion(v, wrapped.getLoader()); - - for (Object relationship : relationships) { - Edge e = null; - Vertex cousinVertex = null; - Introspector wrappedRel = IntrospectorFactory.newInstance(this.introspectionType, relationship); - QueryParser parser = engine.getQueryBuilder().createQueryFromRelationship(wrappedRel); - - List 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()); - ex.getTemplateVars().add(parser.getResultType()); - ex.getTemplateVars().add(parser.getUri().toString()); - throw ex; - } else { - //still an issue if there's more than one - cousinVertex = results.get(0); - } - - if (cousinVertex != null) { - try { - if (!edgeRules.hasEdgeRule(v, cousinVertex)) { - 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() + "."); - } - e = this.getEdgeBetween(EdgeType.COUSIN, v, cousinVertex); - - if (e == null) { - addEdges.add(new Pair<>(v, cousinVertex)); - } else { - existingEdges.remove(e); - } - } catch (NoEdgeRuleFoundException e1) { - throw new AAIException("AAI_6145"); - } - } - } - - for (Edge edge : existingEdges) { - edge.remove(); - } - for (Pair pair : addEdges) { - try { - edgeRules.addEdge(this.engine.asAdmin().getTraversalSource(), pair.getValue0(), pair.getValue1()); - } catch (NoEdgeRuleFoundException e) { - throw new AAIException("AAI_6129", e); - } - } - - } - - /** - * Write through defaults. - * - * @param v the v - * @param obj the obj - * @throws AAIUnknownObjectException - */ - private void writeThroughDefaults(Vertex v, Introspector obj) throws AAIUnknownObjectException { - Introspector latest = this.latestLoader.introspectorFromName(obj.getName()); - if (latest != null) { - Set required = latest.getRequiredProperties(); - - for (String field : required) { - String defaultValue = null; - Object vertexProp = null; - defaultValue = latest.getPropertyMetadata(field).get(PropertyMetadata.DEFAULT_VALUE); - if (defaultValue != null) { - vertexProp = v.property(field).orElse(null); - if (vertexProp == null) { - v.property(field, defaultValue); - } - } - } - } - - } - - - /** - * Reflect dependent vertex. - * - * @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 UnsupportedEncodingException the unsupported encoding exception - * @throws AAIUnknownObjectException - */ - private Vertex reflectDependentVertex(Vertex v, Introspector dependentObj, String requestContext) throws AAIException, UnsupportedEncodingException { - - //QueryParser p = this.engine.getQueryBuilder().createQueryFromURI(obj.getURI()); - //List items = p.getQuery().toList(); - QueryBuilder query = this.engine.getQueryBuilder(v); - query.createEdgeTraversal(EdgeType.TREE, v, dependentObj); - query.createKeyQuery(dependentObj); - - List items = query.toList(); - - Vertex dependentVertex = null; - if (items.size() == 1) { - dependentVertex = items.get(0); - this.verifyResourceVersion("update", dependentObj.getDbName(), dependentVertex.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()); - dependentVertex = createNewVertex(dependentObj); - } - - return reflectDependentVertex(v, dependentVertex, dependentObj, requestContext); - - } - - /** - * Reflect dependent vertex. - * - * @param parent the parent - * @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 UnsupportedEncodingException the unsupported encoding exception - * @throws AAIUnknownObjectException - */ - private Vertex reflectDependentVertex(Vertex parent, Vertex child, Introspector obj, String requestContext) throws AAIException, UnsupportedEncodingException { - - String parentUri = parent.property(AAIProperties.AAI_URI).orElse(null); - if (parentUri != null) { - String uri; - uri = obj.getURI(); - child.property(AAIProperties.AAI_URI, parentUri + uri); - } - processObject(obj, child, requestContext); - - Edge e; - e = this.getEdgeBetween(EdgeType.TREE, parent, child); - if (e == null) { - String canBeLinked = obj.getMetadata(ObjectMetadata.CAN_BE_LINKED); - if (canBeLinked != null && canBeLinked.equals("true")) { - boolean isFirst = !this.engine.getQueryBuilder(parent).createEdgeTraversal(EdgeType.TREE, parent, obj).hasNext(); - if (isFirst) { - child.property(AAIProperties.LINKED, true); - } - } - edgeRules.addTreeEdge(this.engine.asAdmin().getTraversalSource(), parent, child); - } - return child; - - } - - /** - * Db to object. - * - * @param vertices the vertices - * @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 UnsupportedEncodingException the unsupported encoding exception - * @throws MalformedURLException the malformed URL exception - * @throws AAIUnknownObjectException - * @throws URISyntaxException - */ - public Introspector dbToObject(List vertices, final Introspector obj, int depth, boolean nodeOnly, String cleanUp) throws UnsupportedEncodingException, AAIException { - - final int internalDepth; - if (depth == Integer.MAX_VALUE) { - internalDepth = depth--; - } else { - internalDepth = depth; - } - if (vertices.size() > 1 && !obj.isContainer()) { - 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; - for (String property : obj.getProperties()) { - if (obj.isListType(property) && obj.isComplexGenericType(property)) { - listProperty = property; - break; - } - } - final String propertyName = listProperty; - getList = (List)obj.getValue(listProperty); - - /* This is an experimental multithreading experiment - * on get alls. - */ - ExecutorService pool = GetAllPool.getInstance().getPool(); - - List> futures = new ArrayList<>(); - for (Vertex v : vertices) { - Callable task = () -> { - Set seen = new HashSet<>(); - Introspector childObject = obj.newIntrospectorInstanceOfNestedProperty(propertyName); - Tree tree = this.engine.getQueryEngine().findSubGraph(v, internalDepth, nodeOnly); - TreeBackedVertex treeVertex = new TreeBackedVertex(v, tree); - dbToObject(childObject, treeVertex, seen, internalDepth, nodeOnly, cleanUp); - return childObject.getUnderlyingObject(); - //getList.add(childObject.getUnderlyingObject()); - }; - futures.add(pool.submit(task)); - } - - for (Future future : futures) { - try { - getList.add(future.get()); - } catch (ExecutionException e) { - throw new AAIException("AAI_4000", e); - } catch (InterruptedException e) { - throw new AAIException("AAI_4000", e); - } - } - } else if (vertices.size() == 1) { - Set seen = new HashSet<>(); - Tree tree = this.engine.getQueryEngine().findSubGraph(vertices.get(0), depth, nodeOnly); - TreeBackedVertex treeVertex = new TreeBackedVertex(vertices.get(0), tree); - dbToObject(obj, treeVertex, seen, depth, nodeOnly, cleanUp); - } else { - //obj = null; - } - - - return obj; - } - - /** - * Db to object. - * - * @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 UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - * @throws MalformedURLException the malformed URL exception - * @throws AAIUnknownObjectException - * @throws URISyntaxException - */ - private Introspector dbToObject(Introspector obj, Vertex v, Set seen, int depth, boolean nodeOnly, String cleanUp) throws AAIException, UnsupportedEncodingException { - - if (depth < 0) { - return null; - } - depth--; - seen.add(v); - - boolean modified = false; - for (String property : obj.getProperties(PropertyPredicates.isVisible())) { - List getList = null; - Vertex[] vertices = null; - - if (!(obj.isComplexType(property) || obj.isListType(property))) { - this.copySimpleProperty(property, obj, v); - modified = true; - } else { - if (obj.isComplexType(property)) { - /* container case */ - - if (!property.equals("relationship-list") && depth >= 0) { - Introspector argumentObject = obj.newIntrospectorInstanceOfProperty(property); - Object result = dbToObject(argumentObject, v, seen, depth+1, nodeOnly, cleanUp); - if (result != null) { - obj.setValue(property, argumentObject.getUnderlyingObject()); - modified = true; - } - } else if (property.equals("relationship-list") && !nodeOnly){ - /* relationships need to be handled correctly */ - Introspector relationshipList = obj.newIntrospectorInstanceOfProperty(property); - relationshipList = createRelationshipList(v, relationshipList, cleanUp); - if (relationshipList != null) { - modified = true; - obj.setValue(property, relationshipList.getUnderlyingObject()); - modified = true; - } - - } - } else if (obj.isListType(property)) { - - if (property.equals("any")) { - continue; - } - String genericType = obj.getGenericTypeClass(property).getSimpleName(); - if (obj.isComplexGenericType(property) && depth >= 0) { - final String childDbName = convertFromCamelCase(genericType); - String vType = v.property(AAIProperties.NODE_TYPE).orElse(null); - EdgeRule rule; - - rule = edgeRules.getEdgeRule(EdgeType.TREE, vType, childDbName); - if (!rule.getContains().equals(AAIDirection.NONE.toString())) { - //vertices = this.queryEngine.findRelatedVertices(v, Direction.OUT, rule.getLabel(), childDbName); - Direction ruleDirection = rule.getDirection(); - Iterator itr = v.vertices(ruleDirection, rule.getLabel()); - List verticesList = (List)IteratorUtils.toList(itr); - itr = verticesList.stream().filter(item -> { - return item.property(AAIProperties.NODE_TYPE).orElse("").equals(childDbName); - }).iterator(); - if (itr.hasNext()) { - getList = (List)obj.getValue(property); - } - int processed = 0; - int removed = 0; - while (itr.hasNext()) { - Vertex childVertex = itr.next(); - if (!seen.contains(childVertex)) { - Introspector argumentObject = obj.newIntrospectorInstanceOfNestedProperty(property); - - Object result = dbToObject(argumentObject, childVertex, seen, depth, nodeOnly, cleanUp); - if (result != null && getList != null) { - getList.add(argumentObject.getUnderlyingObject()); - } - - processed++; - } else { - removed++; - LOGGER.warn("Cycle found while serializing vertex id={}", childVertex.id().toString()); - } - } - if (processed == 0) { - //vertices were all seen, reset the list - getList = null; - } - if (processed > 0) { - modified = true; - } - } - } else if (obj.isSimpleGenericType(property)) { - List temp = this.engine.getListProperty(v, property); - if (temp != null) { - getList = (List)obj.getValue(property); - getList.addAll(temp); - modified = true; - } - - } - - } - - } - } - - //no changes were made to this obj, discard the instance - if (!modified) { - return null; - } - this.enrichData(obj, v); - return obj; - - } - - - public Introspector getVertexProperties(Vertex v) throws AAIException, UnsupportedEncodingException { - String nodeType = v.property(AAIProperties.NODE_TYPE).orElse(null); - if (nodeType == null) { - throw new AAIException("AAI_6143"); - } - Introspector obj = this.latestLoader.introspectorFromName(nodeType); - Set seen = new HashSet<>(); - int depth = 0; - String cleanUp = "false"; - boolean nodeOnly = true; - this.dbToObject(obj, v, seen, depth, nodeOnly, cleanUp); - - return obj; - - } - public Introspector getLatestVersionView(Vertex v) throws AAIException, UnsupportedEncodingException { - String nodeType = v.property(AAIProperties.NODE_TYPE).orElse(null); - if (nodeType == null) { - throw new AAIException("AAI_6143"); - } - Introspector obj = this.latestLoader.introspectorFromName(nodeType); - Set seen = new HashSet<>(); - int depth = AAIProperties.MAXIMUM_DEPTH; - String cleanUp = "false"; - boolean nodeOnly = false; - Tree tree = this.engine.getQueryEngine().findSubGraph(v, depth, nodeOnly); - TreeBackedVertex treeVertex = new TreeBackedVertex(v, tree); - this.dbToObject(obj, treeVertex, seen, depth, nodeOnly, cleanUp); - - return obj; - } - /** - * 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 - * @throws InvocationTargetException the invocation target exception - * @throws NoSuchMethodException the no such method exception - * @throws SecurityException the security exception - */ - private void copySimpleProperty(String property, Introspector obj, Vertex v) { - final Map metadata = obj.getPropertyMetadata(property); - String dbPropertyName = property; - if (metadata.containsKey(PropertyMetadata.DB_ALIAS)) { - dbPropertyName = metadata.get(PropertyMetadata.DB_ALIAS); - } - final Object temp = v.property(dbPropertyName).orElse(null); - if (temp != null) { - - obj.setValue(property, temp); - } - } - - /** - * 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 - * @throws InvocationTargetException the invocation target exception - * @throws NoSuchMethodException the no such method exception - * @throws SecurityException the security exception - */ - private void simpleDbToObject (Introspector obj, Vertex v) { - for (String property : obj.getProperties()) { - - - if (!(obj.isComplexType(property) || obj.isListType(property))) { - this.copySimpleProperty(property, obj, v); - } - } - } - - /** - * Creates the relationship list. - * - * @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 UnsupportedEncodingException the unsupported encoding 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 { - - - List cousins = this.engine.getQueryEngine().findCousinVertices(v); - - List relationshipObjList = obj.getValue("relationship"); - - for (Vertex cousin : cousins) { - - Introspector relationshipObj = obj.newIntrospectorInstanceOfNestedProperty("relationship"); - Object result = processEdgeRelationship(relationshipObj, cousin, cleanUp); - if (result != null) { - relationshipObjList.add(result); - } - - } - - if (relationshipObjList.isEmpty()) { - return null; - } else { - return obj; - } - } - - /** - * Process edge relationship. - * - * @param relationshipObj the relationship obj - * @param edge the edge - * @param direction the direction - * @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 UnsupportedEncodingException the unsupported encoding 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) throws UnsupportedEncodingException, AAIUnknownObjectException { - - - //we must look up all parents in this case because we need to compute name-properties - //we cannot used the cached aaiUri to perform this action currently - Optional>> tuple = this.getParents(relationshipObj.getLoader(), cousin, "true".equals(cleanUp)); - //damaged vertex found, ignore - if (!tuple.isPresent()) { - return null; - } - List list = tuple.get().getValue1(); - URI uri = this.getURIFromList(list); - - URIToRelationshipObject uriParser = null; - Introspector result = null; - try { - 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=" + tuple.get().getValue0().id().toString() + ": " + e.getMessage(), e); - if ("true".equals(cleanUp)) { - this.deleteWithTraversal(tuple.get().getValue0()); - } - return null; - } - - if(list.size() > 0 && this.version.compareTo(Version.v8) >= 0){ - this.addRelatedToProperty(result, list.get(0)); - } - - return result.getUnderlyingObject(); - } - - /** - * Gets the URI for vertex. - * - * @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 UnsupportedEncodingException the unsupported encoding exception - * @throws AAIUnknownObjectException - */ - public URI getURIForVertex(Vertex v) throws UnsupportedEncodingException { - - return getURIForVertex(v, false); - } - - public URI getURIForVertex(Vertex v, boolean overwrite) throws UnsupportedEncodingException { - URI uri = UriBuilder.fromPath("/unknown-uri").build(); - - String aaiUri = v.property(AAIProperties.AAI_URI).orElse(null); - - if (aaiUri != null && !overwrite) { - uri = UriBuilder.fromPath(aaiUri).build(); - } else { - Optional>> tuple = this.getParents(this.loader, v, false); - if (tuple.isPresent()) { - List list = tuple.get().getValue1(); - uri = this.getURIFromList(list); - } - } - return uri; - } - /** - * Gets the URI from list. - * - * @param list the list - * @return the URI from list - * @throws UnsupportedEncodingException the unsupported encoding exception - */ - private URI getURIFromList(List list) throws UnsupportedEncodingException { - String uri = ""; - StringBuilder sb = new StringBuilder(); - for (Introspector i : list) { - sb.insert(0, i.getURI()); - } - - uri = sb.toString(); - URI result = UriBuilder.fromPath(uri).build(); - return result; - } - - /** - * Gets the parents. - * - * @param start the start - * @param removeDamaged the remove damaged - * @return the parents - * @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 AAIUnknownObjectException - */ - private Optional>> getParents(Loader loader, Vertex start, boolean removeDamaged) { - - List results = this.engine.getQueryEngine().findParents(start); - List objs = new ArrayList<>(); - boolean shortCircuit = false; - for (Vertex v : results) { - String nodeType = v.property(AAIProperties.NODE_TYPE).orElse(null); - Introspector obj = null; - //vertex on the other end of this edge is bad - if (nodeType == null) { - //log something here about what was found and that it was removed - ErrorLogHelper.logError("AAI-6143", "Found a damaged parent vertex " + v.id().toString()); - if (removeDamaged) { - this.deleteWithTraversal(v); - } - shortCircuit = true; - } else { - try { - obj = loader.introspectorFromName(nodeType); - } catch (AAIUnknownObjectException e) { - LOGGER.info("attempted to create node type " + nodeType + " but we do not understand it for version: " + loader.getVersion()); - obj = null; - } - } - - if (obj == null) { - //can't make a valid path because we don't understand this object - // don't include it - } else { - this.simpleDbToObject(obj, v); - objs.add(obj); - } - } - - //stop processing and don't return anything for this bad vertex - if (shortCircuit) { - return Optional.empty(); - } - - return Optional.of(new Pair<>(results.get(results.size()-1), objs)); - } - /** - * Takes a list of vertices and a list of objs and assumes they are in - * the order you want the URIs to be nested. - * [A,B,C] creates uris [A, AB, ABC] - * @param vertices - * @param objs - * @throws UnsupportedEncodingException - * @throws URISyntaxException - */ - public void setCachedURIs(List vertices, List objs) throws UnsupportedEncodingException, URISyntaxException { - - String uriChain = ""; - for (int i = 0; i < vertices.size(); i++) { - String aaiUri = ""; - Vertex v = null; - v = vertices.get(i); - aaiUri = v.property(AAIProperties.AAI_URI).orElse(null); - if (aaiUri != null) { - uriChain += aaiUri; - } else { - URI uri = UriBuilder.fromPath(objs.get(i).getURI()).build(); - aaiUri = uri.toString(); - uriChain += aaiUri; - v.property(AAIProperties.AAI_URI, uriChain); - } - } - - - - } - - - /** - * Adds the r - * @throws AAIUnknownObjectException - * @throws IllegalArgumentException elated to property. - * - * @param relationship the relationship - * @param child the throws IllegalArgumentException, AAIUnknownObjectException child - */ - public void addRelatedToProperty(Introspector relationship, Introspector child) throws AAIUnknownObjectException { - String nameProps = child.getMetadata(ObjectMetadata.NAME_PROPS); - List relatedToProperties = new ArrayList<>(); - - if (nameProps != null) { - String[] props = nameProps.split(","); - for (String prop : props) { - Introspector relatedTo = relationship.newIntrospectorInstanceOfNestedProperty("related-to-property"); - relatedTo.setValue("property-key", child.getDbName() + "." + prop); - relatedTo.setValue("property-value", child.getValue(prop)); - relatedToProperties.add(relatedTo); - } - } - - if (relatedToProperties.size() > 0) { - List relatedToList = (List)relationship.getValue("related-to-property"); - for (Introspector obj : relatedToProperties) { - relatedToList.add(obj.getUnderlyingObject()); - } - } - - } - - /** - * Creates the edge. - * - * @param relationship the relationship - * @param inputVertex the input vertex - * @return true, if successful - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - */ - public boolean createEdge(Introspector relationship, Vertex inputVertex) throws UnsupportedEncodingException, AAIException { - - Vertex relatedVertex = null; - - QueryParser parser = engine.getQueryBuilder().createQueryFromRelationship(relationship); - - List results = parser.getQueryBuilder().toList(); - if (results.size() == 0) { - 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 - relatedVertex = results.get(0); - } - - if (relatedVertex != null) { - - Edge e; - try { - e = this.getEdgeBetween(EdgeType.COUSIN, inputVertex, relatedVertex); - if (e == null) { - edgeRules.addEdge(this.engine.asAdmin().getTraversalSource(), inputVertex, relatedVertex); - - } else { - //attempted to link two vertexes already linked - } - } catch (NoEdgeRuleFoundException e1) { - throw new AAIException("AAI_6129", e1); - } - - - - - } - - return true; - } - - /** - * Gets the edges between. - * - * @param aVertex the out vertex - * @param bVertex the in vertex - * @return the edges between - * @throws AAIException the AAI exception - * @throws NoEdgeRuleFoundException - */ - private List getEdgesBetween(EdgeType type, Vertex aVertex, Vertex bVertex) throws AAIException, NoEdgeRuleFoundException { - - List result = new ArrayList<>(); - - if (bVertex != null) { - EdgeRule rule = edgeRules.getEdgeRule(type, aVertex, bVertex); - GraphTraversal findEdgesBetween = null; - findEdgesBetween = this.engine.asAdmin().getTraversalSource().V(aVertex).bothE(rule.getLabel()).filter(__.otherV().hasId(bVertex.id())); - List edges = findEdgesBetween.toList(); - for (Edge edge : edges) { - if (edge.label().equals(rule.getLabel())) { - result.add(edge); - } - } - - } - - return result; - } - - /** - * Gets the edge between. - * - * @param aVertex the out vertex - * @param bVertex the in vertex - * @return the edge between - * @throws AAIException the AAI exception - * @throws NoEdgeRuleFoundException - */ - public Edge getEdgeBetween(EdgeType type, Vertex aVertex, Vertex bVertex) throws AAIException { - - - - if (bVertex != null) { - - List edges = this.getEdgesBetween(type, aVertex, bVertex); - - if (edges.size() > 0) { - return edges.get(0); - } - - } - - return null; - } - - - /** - * Delete edge. - * - * @param relationship the relationship - * @param inputVertex the input vertex - * @return true, if successful - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - */ - public boolean deleteEdge(Introspector relationship, Vertex inputVertex) throws UnsupportedEncodingException, AAIException { - - Vertex relatedVertex = null; - - QueryParser parser = engine.getQueryBuilder().createQueryFromRelationship(relationship); - - List results = parser.getQueryBuilder().toList(); - - if (results.size() == 0) { - return false; - } - - relatedVertex = results.get(0); - Edge edge; - try { - edge = this.getEdgeBetween(EdgeType.COUSIN, inputVertex, relatedVertex); - } catch (NoEdgeRuleFoundException e) { - throw new AAIException("AAI_6129", e); - } - if (edge != null) { - edge.remove(); - return true; - } else { - return false; - } - - } - - /** - * Delete items with traversal. - * - * @param vertexes the vertexes - * @throws IllegalStateException the illegal state exception - */ - public void deleteItemsWithTraversal(List vertexes) throws IllegalStateException { - for (Vertex v : vertexes) { - LOGGER.debug("About to delete the vertex with id: " + v.id()); - deleteWithTraversal(v); - } - } - - /** - * Delete with traversal. - * - * @param startVertex the start vertex - */ - public void deleteWithTraversal(Vertex startVertex) { - - List results = this.engine.getQueryEngine().findDeletable(startVertex); - - for (Vertex v : results) { - LOGGER.warn("Removing vertex " + v.id().toString()); - - v.remove(); - } - - } - - /** - * Delete. - * - * @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 - */ - public void delete(Vertex v, String resourceVersion, boolean enableResourceVersion) throws IllegalArgumentException, AAIException { - - boolean result = verifyDeleteSemantics(v, resourceVersion, enableResourceVersion); - if (result) { - try { - deleteWithTraversal(v); - } catch (IllegalStateException e) { - throw new AAIException("AAI_6110", e); - } - - } - - } - - - /** - * Verify delete semantics. - * - * @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 { - boolean result = true; - String nodeType = ""; - String errorDetail = " unknown delete semantic found"; - String aaiExceptionCode = ""; - nodeType = vertex.property(AAIProperties.NODE_TYPE).orElse(null); - if (enableResourceVersion && !this.verifyResourceVersion("delete", nodeType, vertex.property(AAIProperties.RESOURCE_VERSION).orElse(null), resourceVersion, nodeType)) { - } - List preventDeleteVertices = this.engine.asAdmin().getReadOnlyTraversalSource().V(vertex).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(); - - if (preventDeleteVertices.size() > 0) { - 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); - result = false; - } - if (!result) { - throw new AAIException(aaiExceptionCode, errorDetail); - } - return result; - } - - /** - * Verify resource version. - * - * @param action the action - * @param nodeType the node type - * @param currentResourceVersion the current resource version - * @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 { - String enabled = ""; - String errorDetail = ""; - String aaiExceptionCode = ""; - if (currentResourceVersion == null) { - currentResourceVersion = ""; - } - - if (resourceVersion == null) { - resourceVersion = ""; - } - try { - enabled = AAIConfig.get(AAIConstants.AAI_RESVERSION_ENABLEFLAG); - } catch (AAIException e) { - ErrorLogHelper.logException(e); - } - // We're only doing the resource version checks for v5 and later - if (enabled.equals("true") && this.version.compareTo(Version.v8) > 0) { - if (!currentResourceVersion.equals(resourceVersion)) { - if (action.equals("create") && !resourceVersion.equals("")) { - errorDetail = "resource-version passed for " + action + " of " + uri; - aaiExceptionCode = "AAI_6135"; - } else if (resourceVersion.equals("")) { - errorDetail = "resource-version not passed for " + action + " of " + uri; - aaiExceptionCode = "AAI_6130"; - } else { - errorDetail = "resource-version MISMATCH for " + action + " of " + uri; - aaiExceptionCode = "AAI_6131"; - } - - throw new AAIException(aaiExceptionCode, errorDetail); - - } - } - return true; - } - - /** - * Convert from camel case. - * - * @param name the name - * @return the string - */ - private String convertFromCamelCase (String name) { - String result = ""; - result = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, name); - - NamingExceptions exceptions = NamingExceptions.getInstance(); - result = exceptions.getDBName(result); - - return result; - } - - private boolean canModify(Introspector obj, String propName, String requestContext) { - final String readOnly = obj.getPropertyMetadata(propName).get(PropertyMetadata.READ_ONLY); - if (readOnly != null) { - final String[] items = readOnly.split(","); - for (String item : items) { - if (requestContext.equals(item)) { - return false; - } - } - } - return true; - } - - private void executePreSideEffects(Introspector obj, Vertex self) throws AAIException { - - SideEffectRunner runner = new SideEffectRunner - .Builder(this.engine, this).addSideEffect(DataCopy.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(); - - 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(); - - runner.execute(obj, self); - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/db/DeleteSemantic.java b/aai-core/src/main/java/org/openecomp/aai/serialization/db/DeleteSemantic.java deleted file mode 100644 index 5b153c29..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/db/DeleteSemantic.java +++ /dev/null @@ -1,40 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.serialization.db; - - -/** - * 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, -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/db/EdgeProperties.java b/aai-core/src/main/java/org/openecomp/aai/serialization/db/EdgeProperties.java deleted file mode 100644 index 8ce1d1c9..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/db/EdgeProperties.java +++ /dev/null @@ -1,43 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.serialization.db; - -public class EdgeProperties { - - public static String out(EdgeProperty prop) { - - return out(prop.toString()); - } - - public static String in(EdgeProperty prop) { - return in(prop.toString()); - } - - public static String out(String prop) { - - return prop; - } - - public static String in(String prop) { - return prop + "-REV"; - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/db/EdgeProperty.java b/aai-core/src/main/java/org/openecomp/aai/serialization/db/EdgeProperty.java deleted file mode 100644 index 21f07451..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/db/EdgeProperty.java +++ /dev/null @@ -1,44 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.serialization.db; - -public enum EdgeProperty { - FROM("from"), - TO("to"), - LABEL("label"), - DIRECTION("direction"), - MULTIPLICITY("multiplicity"), - CONTAINS("contains-other-v"), - DELETE_OTHER_V("delete-other-v"), - SVC_INFRA("SVC-INFRA"), - PREVENT_DELETE("prevent-delete"); - - private final String name; - - private EdgeProperty(String name) { - this.name = name; - } - - @Override - public String toString() { - return name; - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/db/EdgePropertyMap.java b/aai-core/src/main/java/org/openecomp/aai/serialization/db/EdgePropertyMap.java deleted file mode 100644 index bce2c313..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/db/EdgePropertyMap.java +++ /dev/null @@ -1,59 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.serialization.db; - -import org.apache.tinkerpop.gremlin.structure.Direction; - -import java.util.HashMap; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class EdgePropertyMap extends HashMap { - - 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/openecomp/aai/serialization/db/EdgeRule.java b/aai-core/src/main/java/org/openecomp/aai/serialization/db/EdgeRule.java deleted file mode 100644 index 1b6c19f0..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/db/EdgeRule.java +++ /dev/null @@ -1,210 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.serialization.db; - -import org.apache.tinkerpop.gremlin.structure.Direction; - -import java.util.HashMap; -import java.util.Map; - -public class EdgeRule { - - private String label = ""; - private MultiplicityRule multiplicityRule = null; - private Direction direction = null; - private Map edgeProperties = null; - - /** - * Instantiates a new edge rule. - */ - public EdgeRule() { - edgeProperties = new HashMap<>(); - } - - /** - * Gets the label. - * - * @return the label - */ - public String getLabel() { - return label; - } - - /** - * Sets the label. - * - * @param label the new label - */ - public void setLabel(String label) { - this.label = label; - } - - /** - * Gets the multiplicity rule. - * - * @return the multiplicity rule - */ - public MultiplicityRule getMultiplicityRule() { - return multiplicityRule; - } - - public void setMultiplicityRule(String multiplicity){ - if ("Many2Many".equalsIgnoreCase(multiplicity)) { - this.multiplicityRule = MultiplicityRule.MANY2MANY; - } else if ("One2Many".equalsIgnoreCase(multiplicity)) { - this.multiplicityRule = MultiplicityRule.ONE2MANY; - } else if ("One2One".equalsIgnoreCase(multiplicity)) { - this.multiplicityRule = MultiplicityRule.ONE2ONE; - } else { //should be "Many2One" - this.multiplicityRule = MultiplicityRule.MANY2ONE; - } - } - - /** - * Sets the multiplicity rule. - * - * @param multiplicityRule the new multiplicity rule - */ - public void setMultiplicityRule(MultiplicityRule multiplicityRule) { - this.multiplicityRule = multiplicityRule; - } - - /** - * Gets the direction. - * - * @return the direction - */ - public Direction getDirection() { - return direction; - } - - public void setDirection(String direction){ - if ("OUT".equalsIgnoreCase(direction)) { - this.direction = Direction.OUT; - } else if ("IN".equalsIgnoreCase(direction)) { - this.direction = Direction.IN; - } else { - this.direction = Direction.BOTH; - } - } - - /** - * Sets the direction. - * - * @param direction the new direction - */ - public void setDirection(Direction direction) { - this.direction = direction; - } - - /** - * Gets the checks if is parent. - * - * @return the checks if is parent - */ - public String getContains() { - return this.getProp(EdgeProperty.CONTAINS); - } - - /** - * Sets the checks if is parent. - * - * @param isParent the new checks if is parent - */ - public void setContains(String isParent) { - this.setProp(EdgeProperty.CONTAINS, isParent); - } - - /** - * Gets the checks for del target. - * - * @return the checks for del target - */ - public String getDeleteOtherV() { - return this.getProp(EdgeProperty.DELETE_OTHER_V); - } - - /** - * Sets the checks for del target. - * - * @param hasDelTarget the new checks for del target - */ - public void setDeleteOtherV(String hasDelTarget) { - this.setProp(EdgeProperty.DELETE_OTHER_V, hasDelTarget); - } - - /** - * Gets the service infrastructure. - * - * @return the service infrastructure - */ - public String getServiceInfrastructure() { - return this.getProp(EdgeProperty.SVC_INFRA); - } - - /** - * Sets the service infrastructure. - * - * @param serviceInfrastructure the new service infrastructure - */ - public void setServiceInfrastructure(String serviceInfrastructure) { - this.setProp(EdgeProperty.SVC_INFRA, serviceInfrastructure); - } - - public String getPreventDelete() { - return this.getProp(EdgeProperty.PREVENT_DELETE); - } - - public void setPreventDelete(String preventDelete) { - this.setProp(EdgeProperty.PREVENT_DELETE, preventDelete); - } - - /** - * Gets the edge properties. - * - * @return the edge properties - */ - public Map getEdgeProperties() { - return this.edgeProperties; - } - - /** - * Sets the prop. - * - * @param key the key - * @param value the value - */ - private void setProp(EdgeProperty key, String value) { - this.edgeProperties.put(key, value); - } - - /** - * Gets the prop. - * - * @param key the key - * @return the prop - */ - private String getProp(EdgeProperty key) { - return this.edgeProperties.get(key); - } - - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/db/EdgeRules.java b/aai-core/src/main/java/org/openecomp/aai/serialization/db/EdgeRules.java deleted file mode 100644 index f819b9ea..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/db/EdgeRules.java +++ /dev/null @@ -1,588 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.serialization.db; - -import static com.jayway.jsonpath.Criteria.where; -import static com.jayway.jsonpath.Filter.filter; - -import java.io.InputStream; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Optional; -import java.util.Scanner; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; - -import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; -import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__; -import org.apache.tinkerpop.gremlin.structure.Direction; -import org.apache.tinkerpop.gremlin.structure.Edge; -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.openecomp.aai.db.props.AAIProperties; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Version; -import org.openecomp.aai.serialization.db.exceptions.EdgeMultiplicityException; -import org.openecomp.aai.serialization.db.exceptions.NoEdgeRuleFoundException; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.google.common.collect.ArrayListMultimap; -import com.google.common.collect.Multimap; -import com.jayway.jsonpath.DocumentContext; -import com.jayway.jsonpath.Filter; -import com.jayway.jsonpath.JsonPath; - -public class EdgeRules { - - private EELFLogger logger = EELFManager.getInstance().getLogger(EdgeRules.class); - - private DocumentContext rulesDoc; - - /** - * Loads the most recent DbEdgeRules json file for later parsing. - * Only need most recent version for actual A&AI operations that call this class; - * the old ones are only used in tests. - */ - private EdgeRules() { - - String json = this.getEdgeRuleJson(Version.getLatest()); - rulesDoc = JsonPath.parse(json); - - } - - private EdgeRules(String rulesFilename) { - String json = this.getEdgeRuleJson(rulesFilename); - rulesDoc = JsonPath.parse(json); - } - - private String getEdgeRuleJson(String rulesFilename) { - InputStream is = getClass().getResourceAsStream(rulesFilename); - - Scanner scanner = new Scanner(is); - String json = scanner.useDelimiter("\\Z").next(); - scanner.close(); - - return json; - } - - /** - * Loads the versioned DbEdgeRules json file for later parsing. - */ - @SuppressWarnings("unchecked") - private EdgeRules(Version version) { - String json = this.getEdgeRuleJson(version); - rulesDoc = JsonPath.parse(json); - } - - private String getEdgeRuleJson(Version version) { - InputStream is = getClass().getResourceAsStream("/dbedgerules/DbEdgeRules_" + version.toString() + ".json"); - - Scanner scanner = new Scanner(is); - String json = scanner.useDelimiter("\\Z").next(); - scanner.close(); - - return json; - } - - private static class Helper { - private static final EdgeRules INSTANCE = new EdgeRules(); - private static final Map INSTANCEMAP = new ConcurrentHashMap<>(); - - private static EdgeRules getEdgeRulesByFilename(String rulesFilename) { - return new EdgeRules(rulesFilename); - } - - private static EdgeRules getVersionedEdgeRules(Version v) { - if (Version.isLatest(v)) { - return INSTANCE; - } - if (!INSTANCEMAP.containsKey(v)) { - INSTANCEMAP.put(v, new EdgeRules(v)); - } - return INSTANCEMAP.get(v); - } - } - - /** - * Gets the single instance of EdgeRules. - * - * @return single instance of EdgeRules - */ - public static EdgeRules getInstance() { - return Helper.INSTANCE; - - } - - /** - * Gets the versioned instance of EdgeRules. - * - * @return versioned instance of EdgeRules - */ - public static EdgeRules getInstance(Version v) { - return Helper.getVersionedEdgeRules(v); - - } - - /** - * Loads edge rules from the given file. - * - * @param rulesFilename - name of the file to load rules from - * @return the EdgeRules instance - */ - public static EdgeRules getInstance(String rulesFilename) { - return Helper.getEdgeRulesByFilename(rulesFilename); - } - - /** - * 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); - } - - /** - * 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(EdgeType.COUSIN, traversalSource, aVertex, bVertex, false); - } - - /** - * 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); - } - - /** - * 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.addEdge(EdgeType.COUSIN, traversalSource, aVertex, bVertex, true); - } - - /** - * 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) throws AAIException { - - EdgeRule rule = this.getEdgeRule(type, aVertex, bVertex); - - Edge e = null; - - Optional 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) { - - // In DbEdgeRules.EdgeRules -- What we have as "edgeRule" is a comma-delimited set of strings. - // The first item is the edgeLabel. - // The second in the list is always "direction" which is always OUT for the way we've implemented it. - // Items starting at "firstTagIndex" and up are all assumed to be booleans that map according to - // tags as defined in EdgeInfoMap. - // Note - if they are tagged as 'reverse', that means they get the tag name with "-REV" on it - Map propMap = rule.getEdgeProperties(); - - for (Entry entry : propMap.entrySet()) { - edge.property(entry.getKey().toString(), entry.getValue()); - } - } - - /** - * Checks if any edge rules exist between the two given nodes, in either A|B or B|A order. - * - * @param nodeA - node at one end of the edge - * @param nodeB - node at the other end - * @return true, if any such rules exist - */ - public boolean hasEdgeRule(String nodeA, String nodeB) { - Filter aToB = filter( - where("from").is(nodeA).and("to").is(nodeB) - ); - Filter bToA = filter( - where("from").is(nodeB).and("to").is(nodeA) - ); - - List> results = readRules(aToB); - results.addAll(readRules(bToA)); - - return !results.isEmpty(); - - } - - /** - * Checks if any edge rules exist between the two given nodes, in either A|B or B|A order. - * - * @param aVertex - node at one end of the edge - * @param bVertex - node at the other end - * @return true, if any such rules exist - */ - public boolean hasEdgeRule(Vertex aVertex, Vertex bVertex) { - String outType = aVertex.property("aai-node-type").orElse(null); - String inType = bVertex.property("aai-node-type").orElse(null); - - return this.hasEdgeRule(outType, inType); - - } - - /** - * Gets all the edge rules that exist between the given node types. - * The rules will be phrased in terms of out|in, though this will - * also find rules defined as in|out (it will flip the direction in - * the EdgeRule object returned accordingly to match out|in). - * - * @param outType - * @param inType - * @return Map where edgeLabel is the label name - * @throws AAIException - */ - public Map getEdgeRules(String outType, String inType) throws AAIException { - Map result = new HashMap<>(); - EdgeRule rule = null; - for (EdgeType type : EdgeType.values()) { - try { - rule = this.getEdgeRule(type, outType, inType); - result.put(rule.getLabel(), rule); - } catch (NoEdgeRuleFoundException e) { - continue; - } - } - - return result; - } - - - - /** - * Gets the edge rule of the given type that exists between A and B. - * Will check B|A as well, and flips the direction accordingly if that succeeds - * to match the expected A|B return. - * - * @param type - the type of edge you're looking for - * @param nodeA - first node type - * @param nodeB - second node type - * @return EdgeRule describing the rule in terms of A|B, if there is any such rule - * @throws AAIException if no such edge exists - */ - public EdgeRule getEdgeRule(EdgeType type, String nodeA, String nodeB) throws AAIException { - //try A to B - List> aToBEdges = readRules(buildFilter(type, nodeA, nodeB)); - if (!aToBEdges.isEmpty()) { - //lazily stop iterating if we find a match - //should there be a mismatch between type and isParent, - //the caller will receive something. - //this operates on the assumption that there are at most two rules - //for a given vertex pair - verifyRule(aToBEdges.get(0)); - return buildRule(aToBEdges.get(0)); - } - - //we get here if there was nothing for A to B, so let's try B to A - List> bToAEdges = readRules(buildFilter(type, nodeB, nodeA)); - if (!bToAEdges.isEmpty()) { - verifyRule(bToAEdges.get(0)); - return flipDirection(buildRule(bToAEdges.get(0))); //bc we need to return as A|B, so flip the direction to match - } - - //found none - throw new NoEdgeRuleFoundException("no " + type.toString() + " edge between " + nodeA + " and " + nodeB); - } - - /** - * Builds a JsonPath filter to search for an edge from nodeA to nodeB with the given edge type (cousin or parent/child) - * - * @param type - * @param nodeA - start node - * @param nodeB - end node - * @return - */ - private Filter buildFilter(EdgeType type, String nodeA, String nodeB) { - if (EdgeType.COUSIN.equals(type)) { - return filter( - where("from").is(nodeA).and("to").is(nodeB).and(EdgeProperty.CONTAINS.toString()).is(AAIDirection.NONE.toString()) - ); - } else { - return filter( - where("from").is(nodeA).and("to").is(nodeB).and(EdgeProperty.CONTAINS.toString()).is("${direction}")).or( - where("from").is(nodeA).and("to").is(nodeB).and(EdgeProperty.CONTAINS.toString()).is("!${direction}") - ); - } - } - - /** - * Puts the give edge rule information into an EdgeRule object. - * - * @param edge - the edge information returned from JsonPath - * @return EdgeRule containing that information - */ - private EdgeRule buildRule(Map map) { - Map edge = new EdgePropertyMap<>(); - edge.putAll(map); - - EdgeRule rule = new EdgeRule(); - rule.setLabel(edge.get("label")); - rule.setDirection(edge.get("direction")); - rule.setMultiplicityRule(edge.get("multiplicity")); - rule.setContains(edge.get(EdgeProperty.CONTAINS.toString())); - rule.setDeleteOtherV(edge.get(EdgeProperty.DELETE_OTHER_V.toString())); - rule.setServiceInfrastructure(edge.get(EdgeProperty.SVC_INFRA.toString())); - rule.setPreventDelete(edge.get(EdgeProperty.PREVENT_DELETE.toString())); - - return rule; - } - - /** - * If getEdgeRule gets a request for A|B, and it finds something as B|A, the caller still expects - * the returned EdgeRule to reflect A|B directionality. This helper method flips B|A direction to - * match this expectation. - * - * @param rule whose direction needs flipped - * @return the updated rule - */ - private EdgeRule flipDirection(EdgeRule rule) { - if (Direction.IN.equals(rule.getDirection())) { - rule.setDirection(Direction.OUT); - return rule; - } else if (Direction.OUT.equals(rule.getDirection())) { - rule.setDirection(Direction.IN); - return rule; - } else { //direction is BOTH, flipping both is still both - return rule; - } - } - - /** - * Gets the edge rule of the given type that exists between A and B. - * Will check B|A as well, and flips the direction accordingly if that succeeds - * to match the expected A|B return. - * - * @param type - the type of edge you're looking for - * @param aVertex - first node type - * @param bVertex - second node type - * @return EdgeRule describing the rule in terms of A|B, if there is any such rule - * @throws AAIException if no such edge exists - */ - public EdgeRule getEdgeRule(EdgeType type, Vertex aVertex, Vertex bVertex) throws AAIException { - String outType = aVertex.property(AAIProperties.NODE_TYPE).orElse(null); - String inType = bVertex.property(AAIProperties.NODE_TYPE).orElse(null); - - return this.getEdgeRule(type, outType, inType); - - - } - - /** - * 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 validateMultiplicity(EdgeRule rule, GraphTraversalSource traversalSource, Vertex aVertex, Vertex bVertex) { - - if (rule.getDirection().equals(Direction.OUT)) { - - } else if (rule.getDirection().equals(Direction.IN)) { - Vertex tempV = bVertex; - bVertex = aVertex; - aVertex = tempV; - } - - String aVertexType = aVertex.property(AAIProperties.NODE_TYPE).orElse(null); - String bVertexType = bVertex.property(AAIProperties.NODE_TYPE).orElse(null); - String label = rule.getLabel(); - MultiplicityRule multiplicityRule = rule.getMultiplicityRule(); - List outEdges = traversalSource.V(aVertex).outE(label).where(__.inV().has(AAIProperties.NODE_TYPE, bVertexType)).toList(); - List inEdges = traversalSource.V(bVertex).inE(label).where(__.outV().has(AAIProperties.NODE_TYPE, aVertexType)).toList(); - String detail = ""; - if (multiplicityRule.equals(MultiplicityRule.ONE2ONE)) { - if (inEdges.size() >= 1 || outEdges.size() >= 1 ) { - detail = "multiplicity rule violated: only one edge can exist with label: " + label + " between " + aVertexType + " and " + bVertexType; - } - } else if (multiplicityRule.equals(MultiplicityRule.ONE2MANY)) { - if (inEdges.size() >= 1) { - detail = "multiplicity rule violated: only one edge can exist with label: " + label + " between " + aVertexType + " and " + bVertexType; - } - } else if (multiplicityRule.equals(MultiplicityRule.MANY2ONE)) { - if (outEdges.size() >= 1) { - detail = "multiplicity rule violated: only one edge can exist with label: " + label + " between " + aVertexType + " and " + bVertexType; - } - } else { - - } - - if (!"".equals(detail)) { - return Optional.of(detail); - } else { - return Optional.empty(); - } - - - } - - /** - * Verifies that all required properties are defined in the given edge rule. - * If they are not, throws a RuntimeException. - * - * @param rule - Map representing - * an edge rule - */ - private void verifyRule(Map rule) { - for (EdgeProperty prop : EdgeProperty.values()) { - if (!rule.containsKey(prop.toString())) { - /* Throws RuntimeException as rule definition errors - * cannot be recovered from, and should never happen anyway - * because these are configuration files, so requiring all - * downstream code to check for this exception seems inappropriate. - * It's instantiated with an AAIException to make sure all - * relevant information is present in the error message. - */ - throw new RuntimeException(new AAIException("AAI_4005", - "Rule between " + rule.get("from") + " and " + rule.get("to") + - " is missing property " + prop + ".")); - } - } - } - - /** - * Reads all the edge rules from the loaded json file. - * - * @return List> - * Each map represents a rule read from the json. - */ - private List> readRules() { - return readRules(null); - } - - /** - * Reads the edge rules from the loaded json file, using the given filter - * to get specific rules. If filter is null, will get all rules. - * - * @param filter - may be null to indicate get all - * @return List> - * Each map represents a rule read from the json. - */ - private List> readRules(Filter filter) { - List> results; - if (filter == null) { //no filter means get all - results = rulesDoc.read("$.rules.*"); - } else { - results = rulesDoc.read("$.rules.[?]", filter); - } - for (Map result : results) { - verifyRule(result); - } - return results; - } - - /** - * Gets all the edge rules we define. - * - * @return Multimap - */ - public Multimap getAllRules() { - Multimap result = ArrayListMultimap.create(); - - List> rules = readRules(); - for (Map rule : rules) { - EdgeRule er = buildRule(rule); - String name = rule.get("from") + "|" + rule.get("to"); - result.put(name, er); - } - - return result; - } - - /** - * Gets all edge rules that define a child relationship from - * the given node type. - * - * @param nodeType - * @return - */ - public Set getChildren(String nodeType) { - - final Filter filter = filter( - where("from").is(nodeType).and(EdgeProperty.CONTAINS.toString()).is("${direction}") - ).or(where("to").is(nodeType).and(EdgeProperty.CONTAINS.toString()).is("!${direction}")); - - final List> rules = readRules(filter); - final Set result = new HashSet<>(); - rules.forEach(item -> { - verifyRule(item); - result.add(buildRule(item)); - }); - - return result; - - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/db/EdgeType.java b/aai-core/src/main/java/org/openecomp/aai/serialization/db/EdgeType.java deleted file mode 100644 index cf3219fa..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/db/EdgeType.java +++ /dev/null @@ -1,26 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.serialization.db; - -public enum EdgeType { - COUSIN, - TREE; -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/db/GetAllPool.java b/aai-core/src/main/java/org/openecomp/aai/serialization/db/GetAllPool.java deleted file mode 100644 index 379c3f30..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/db/GetAllPool.java +++ /dev/null @@ -1,46 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.serialization.db; - -import java.util.concurrent.ExecutorService; -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; - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/db/GraphSingleton.java b/aai-core/src/main/java/org/openecomp/aai/serialization/db/GraphSingleton.java deleted file mode 100644 index ba616387..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/db/GraphSingleton.java +++ /dev/null @@ -1,69 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.serialization.db; - -import com.thinkaurelius.titan.core.TitanGraph; -import org.openecomp.aai.dbmap.AAIGraph; -import org.openecomp.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; - - } - - /** - * Gets the count. - * - * @return the count - */ - public AtomicInteger getCount() { - return totalCount; - } - - /** - * Gets the tx graph. - * - * @return the tx graph - */ - public TitanGraph getTxGraph() { - return AAIGraph.getInstance().getGraph(); - } - - public TitanGraph getTxGraph(DBConnectionType connectionType) { - return AAIGraph.getInstance().getGraph(connectionType); - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/db/LegacyDBSerializer.java b/aai-core/src/main/java/org/openecomp/aai/serialization/db/LegacyDBSerializer.java deleted file mode 100644 index 5d419852..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/db/LegacyDBSerializer.java +++ /dev/null @@ -1,34 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.serialization.db; - -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.ModelType; -import org.openecomp.aai.introspection.Version; -import org.openecomp.aai.serialization.engines.TransactionalGraphEngine; - -public class LegacyDBSerializer extends DBSerializer { - - public LegacyDBSerializer(Version version, TransactionalGraphEngine engine, ModelType introspectionType, String sourceOfTruth) throws AAIException { - super(version, engine, introspectionType, sourceOfTruth); - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/db/MultiplicityRule.java b/aai-core/src/main/java/org/openecomp/aai/serialization/db/MultiplicityRule.java deleted file mode 100644 index a1c9124d..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/db/MultiplicityRule.java +++ /dev/null @@ -1,28 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.serialization.db; - -public enum MultiplicityRule { - MANY2ONE, - ONE2MANY, - ONE2ONE, - MANY2MANY -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/db/TitanGraphSingleton.java b/aai-core/src/main/java/org/openecomp/aai/serialization/db/TitanGraphSingleton.java deleted file mode 100644 index 58008dab..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/db/TitanGraphSingleton.java +++ /dev/null @@ -1,38 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.serialization.db; - -/* This is class is just a wrapper of its parent */ -public class TitanGraphSingleton extends GraphSingleton { - - private static class Helper { - private static final TitanGraphSingleton INSTANCE = new TitanGraphSingleton(); - } - - /** - * Gets the single instance of TitanGraphSingleton. - * - * @return single instance of TitanGraphSingleton - */ - public static TitanGraphSingleton getInstance() { - return Helper.INSTANCE; - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/db/exceptions/EdgeMultiplicityException.java b/aai-core/src/main/java/org/openecomp/aai/serialization/db/exceptions/EdgeMultiplicityException.java deleted file mode 100644 index 081a2d62..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/db/exceptions/EdgeMultiplicityException.java +++ /dev/null @@ -1,40 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.serialization.db.exceptions; - -import org.openecomp.aai.exceptions.AAIException; - -public class EdgeMultiplicityException extends AAIException { - - private static final long serialVersionUID = -5575661036426538012L; - - public EdgeMultiplicityException(String message) { - super("AAI_6140", message); - } - - public EdgeMultiplicityException(Throwable cause) { - super("AAI_6140",cause); - } - - public EdgeMultiplicityException(String message, Throwable cause) { - super("AAI_6140", cause, message); - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/db/exceptions/NoEdgeRuleFoundException.java b/aai-core/src/main/java/org/openecomp/aai/serialization/db/exceptions/NoEdgeRuleFoundException.java deleted file mode 100644 index 025dfd82..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/db/exceptions/NoEdgeRuleFoundException.java +++ /dev/null @@ -1,40 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.serialization.db.exceptions; - -import org.openecomp.aai.exceptions.AAIException; - -public class NoEdgeRuleFoundException extends AAIException { - - private static final long serialVersionUID = -906843868234976763L; - - public NoEdgeRuleFoundException(String message) { - super("AAI_6129", message); - } - - public NoEdgeRuleFoundException(Throwable cause) { - super("AAI_6129",cause); - } - - public NoEdgeRuleFoundException(String message, Throwable cause) { - super("AAI_6129", cause, message); - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/engines/QueryStyle.java b/aai-core/src/main/java/org/openecomp/aai/serialization/engines/QueryStyle.java deleted file mode 100644 index f6fae4d5..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/engines/QueryStyle.java +++ /dev/null @@ -1,25 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.serialization.engines; - -public enum QueryStyle { - GREMLIN_TRAVERSAL, GREMLIN_UNIQUE, GREMLINPIPELINE_TRAVERSAL, TRAVERSAL -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/engines/TitanDBEngine.java b/aai-core/src/main/java/org/openecomp/aai/serialization/engines/TitanDBEngine.java deleted file mode 100644 index 8611ba6b..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/engines/TitanDBEngine.java +++ /dev/null @@ -1,101 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.serialization.engines; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.apache.tinkerpop.gremlin.structure.VertexProperty; -import org.openecomp.aai.dbmap.DBConnectionType; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.serialization.db.TitanGraphSingleton; - -public class TitanDBEngine extends TransactionalGraphEngine { - - /** - * Instantiates a new titan DB engine. - * - * @param style the style - * @param loader the loader - */ - public TitanDBEngine(QueryStyle style, DBConnectionType connectionType, Loader loader) { - super(style, loader, connectionType, TitanGraphSingleton.getInstance()); - } - - /** - * Instantiates a new titan DB engine. - * - * @param style the style - * @param loader the loader - * @param connect the connect - */ - public TitanDBEngine(QueryStyle style, Loader loader, boolean connect) { - super(style, loader); - if (connect) { - this.singleton = TitanGraphSingleton.getInstance(); - } - } - - /** - * {@inheritDoc} - */ - @Override - public boolean setListProperty(Vertex v, String name, List objs) { - - //clear out list full replace style - - Iterator> 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 getListProperty(Vertex v, String name) { - - List result = new ArrayList(); - - Iterator> 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/openecomp/aai/serialization/engines/TransactionalGraphEngine.java b/aai-core/src/main/java/org/openecomp/aai/serialization/engines/TransactionalGraphEngine.java deleted file mode 100644 index ef91a868..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/engines/TransactionalGraphEngine.java +++ /dev/null @@ -1,245 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.serialization.engines; - -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.openecomp.aai.dbmap.DBConnectionType; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.query.builder.GremlinTraversal; -import org.openecomp.aai.query.builder.GremlinUnique; -import org.openecomp.aai.query.builder.QueryBuilder; -import org.openecomp.aai.query.builder.TraversalQuery; -import org.openecomp.aai.serialization.db.GraphSingleton; -import org.openecomp.aai.serialization.engines.query.GraphTraversalQueryEngine; -import org.openecomp.aai.serialization.engines.query.QueryEngine; - -import com.thinkaurelius.titan.core.TitanGraph; -import com.thinkaurelius.titan.core.schema.TitanManagement; - -public abstract class TransactionalGraphEngine { - - protected GraphSingleton singleton = null; - protected QueryEngine queryEngine = null; - protected QueryBuilder 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 getListProperty(Vertex v, String name); - - /** - * Gets the graph. - * - * @return the graph - */ - private TitanGraph 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)) { - - 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 getQueryBuilder() { - return getQueryBuilder(this.loader); - } - - public QueryBuilder getQueryBuilder(QueryStyle style) { - return getQueryBuilder(style, this.loader); - } - - public QueryBuilder getQueryBuilder(Loader loader) { - return getQueryBuilder(this.style, loader); - } - - public QueryBuilder 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 { - throw new IllegalArgumentException("Query Builder type not recognized"); - } - return queryBuilder; - } - /** - * Gets the query builder. - * - * @param start the start - * @return the query builder - */ - public QueryBuilder getQueryBuilder(Vertex start) { - return getQueryBuilder(this.loader, start); - } - - public QueryBuilder getQueryBuilder(Loader loader, Vertex start) { - return getQueryBuilder(this.style, loader, start); - } - - public QueryBuilder 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 { - 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 TitanManagement getManagementSystem() { - return getGraph().openManagement(); - } - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/engines/query/GraphTraversalQueryEngine.java b/aai-core/src/main/java/org/openecomp/aai/serialization/engines/query/GraphTraversalQueryEngine.java deleted file mode 100644 index ac8b21e1..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/engines/query/GraphTraversalQueryEngine.java +++ /dev/null @@ -1,197 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.serialization.engines.query; - - -import static org.openecomp.aai.serialization.db.AAIDirection.IN; -import static org.openecomp.aai.serialization.db.AAIDirection.NONE; -import static org.openecomp.aai.serialization.db.AAIDirection.OUT; -import static org.openecomp.aai.serialization.db.EdgeProperty.CONTAINS; -import static org.openecomp.aai.serialization.db.EdgeProperty.DELETE_OTHER_V; - -import java.util.List; -import java.util.Set; - -import org.apache.tinkerpop.gremlin.process.traversal.P; -import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; -import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; -import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__; -import org.apache.tinkerpop.gremlin.process.traversal.step.util.Tree; -import org.apache.tinkerpop.gremlin.structure.Direction; -import org.apache.tinkerpop.gremlin.structure.Edge; -import org.apache.tinkerpop.gremlin.structure.Element; -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.openecomp.aai.db.props.AAIProperties; -import org.openecomp.aai.introspection.Loader; - -/* - * This class needs some big explanation despite its compact size. - * This controls all the queries performed by the CRUD API in A&AI. - * findParents, findChildren, and findDeletable require special attention - * These methods use 'repeat'. You cannot use 'emit' with repeat currently - * as it is extremely buggy as of tinkerpop-3.0.1-incubating. The way around - * it (for now) is to sideEffect all the vertices we traverse into an ArrayList. - * - */ -public class GraphTraversalQueryEngine extends QueryEngine { - - /** - * Instantiates a new graph traversal query engine. - * - * @param graphEngine the graph engine - */ - public GraphTraversalQueryEngine(GraphTraversalSource g) { - super(g); - } - - /** - * {@inheritDoc} - */ - @Override - public List findParents(Vertex start) { - - final GraphTraversal 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(); - } - - /** - * {@inheritDoc} - */ - @Override - public List findAllChildren(Vertex start) { - - GraphTraversal 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(); - - } - - public List findChildrenOfType(Vertex start, String type) { - GraphTraversal 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(); - } - - public List findChildren(Vertex start) { - GraphTraversal pipe = this.g.V(start).union( - __.outE().has(CONTAINS.toString(), OUT.toString()), - __.inE().has(CONTAINS.toString(), IN.toString()) - ).otherV().dedup(); - - return pipe.toList(); - } - - /** - * {@inheritDoc} - */ - @Override - public List findDeletable(Vertex start) { - GraphTraversal pipe = this.g - .V(start).emit(v -> true).repeat( - __.union( - __.outE().or( - __.has(CONTAINS.toString(), OUT.toString()), - __.has(DELETE_OTHER_V.toString(), OUT.toString()) - ).inV(), - __.inE().or( - __.has(CONTAINS.toString(), IN.toString()), - __.has(DELETE_OTHER_V.toString(), IN.toString()) - ).outV() - ) - ); - - return pipe.toList(); - } - - /** - * {@inheritDoc} - */ - @Override - public List findRelatedVertices(Vertex start, Direction direction, String label, String nodeType) { - GraphTraversal 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 findSubGraph(Vertex start, int iterations, boolean nodeOnly) { - final GraphTraversal 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()) - ); - - 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 findEdgesForVersion(Vertex start, Loader loader) { - final Set objects = loader.getAllObjects().keySet(); - GraphTraversal 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))) - ).dedup(); - - return pipeline.toList(); - } - - - @Override - public List findCousinVertices(Vertex start) { - GraphTraversal pipeline = this.g.V(start).union( - __.inE().has(CONTAINS.toString(), NONE.toString()), - __.outE().has(CONTAINS.toString(), NONE.toString())).otherV().dedup(); - - return pipeline.toList(); - } - -} - diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/engines/query/GremlinPipelineQueryEngine.java b/aai-core/src/main/java/org/openecomp/aai/serialization/engines/query/GremlinPipelineQueryEngine.java deleted file mode 100644 index 809b6d96..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/engines/query/GremlinPipelineQueryEngine.java +++ /dev/null @@ -1,185 +0,0 @@ -package org.openecomp.aai.serialization.engines.query;/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -/* -package org.openecomp.aai.serialization.engines.query; - -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.openecomp.aai.db.AAIProperties; -import org.openecomp.aai.query.builder.QueryBuilder; -import org.openecomp.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 executeQuery(TransactionalGraph g, QueryBuilder query) { - List 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 executeParentQuery(TransactionalGraph g, QueryBuilder query) { - List 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 findParents(Vertex start) { - GremlinPipeline pipe = new GremlinPipeline(start).as("x").inE() - .has("isParent", true).outV().loop("x", new PipeFunction, Boolean>() { - - @Override - public Boolean compute(LoopPipe.LoopBundle argument) { - GremlinPipeline pipe = new GremlinPipeline<>(argument.getObject()); - return pipe.inE().has("isParent", true).count() == 1 || argument.getLoops() < 100; - } - - }, new PipeFunction, Boolean>() { - - @Override - public Boolean compute(LoopPipe.LoopBundle argument) { - return true; - } - - }); - - List results = pipe.toList(); - results.add(0, start); - return results; - } - - @Override - public List findChildren(Vertex start) { - Set seen = new HashSet<>(); - seen.add(start); - GremlinPipeline pipe = new GremlinPipeline(start).as("x").outE().has("isParent", true).inV() - .except(seen).store(seen).loop("x", new PipeFunction, Boolean>() { - - @Override - public Boolean compute(LoopPipe.LoopBundle argument) { - GremlinPipeline pipe = new GremlinPipeline<>(argument.getObject()); - return pipe.outE().has("isParent", true).count() >= 1 || argument.getLoops() < 100; - } - - }, new PipeFunction, Boolean>() { - - @Override - public Boolean compute(LoopPipe.LoopBundle argument) { - return true; - } - - }); - - List results = pipe.toList(); - results.add(0, start); - return results; - } - - @Override - public List findDeletable(Vertex start) { - Set seen = new HashSet<>(); - seen.add(start); - GremlinPipeline pipe = new GremlinPipeline(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, Boolean>() { - - @Override - public Boolean compute(LoopPipe.LoopBundle argument) { - GremlinPipeline 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, Boolean>() { - - @Override - public Boolean compute(LoopPipe.LoopBundle argument) { - return true; - } - - }); - List results = pipe.toList(); - results.add(0, start); - - return results; - } - - private List process(GremlinPipeline start, GremlinPipeline pipe) { - - - return start.add(pipe).cast(Vertex.class).toList(); - } - - @Override - public List findRelatedVertices(Vertex start, Direction direction, String label, String nodeType) { - GremlinPipeline pipe = new GremlinPipeline(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 result = pipe.toList(); - return result; - } - -} -*/ diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/engines/query/GremlinQueryEngine.java b/aai-core/src/main/java/org/openecomp/aai/serialization/engines/query/GremlinQueryEngine.java deleted file mode 100644 index 1ca02112..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/engines/query/GremlinQueryEngine.java +++ /dev/null @@ -1,175 +0,0 @@ -package org.openecomp.aai.serialization.engines.query;/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -// -//package org.openecomp.aai.serialization.engines.query; -// -//import java.util.List; -//import java.util.regex.Matcher; -//import java.util.regex.Pattern; -// -//import org.apache.commons.collections.IteratorUtils; -// -//import org.openecomp.aai.db.AAIProperties; -//import org.openecomp.aai.query.builder.QueryBuilder; -//import org.openecomp.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 executeQuery(TransactionalGraph g, QueryBuilder query) { -// List 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 executeParentQuery(TransactionalGraph g, QueryBuilder query) { -// -// List 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 executeQuery(Vertex startVertex, String query) { -// -// return this.processGremlinQuery(startVertex, "_()" + query); -// -// } -// -// @Override -// public List findParents(Vertex start) { -// -// String findAllParents = ".as('x').inE.has('isParent', true).outV" -// + ".loop('x'){it.object.inE.has('isParent',true).count()==1}{true}"; -// -// List results = this.executeQuery(start, findAllParents); -// results.add(0, start); -// return results; -// -// } -// -// @Override -// public List findChildren(Vertex start) { -// String findAllChildren = ".as('x').outE.has('isParent', true).inV" -// + ".loop('x'){it.object.outE.has('isParent', true).count() >= 1}{true}"; -// -// List results = this.executeQuery(start, findAllChildren); -// results.add(0, start); -// return results; -// -// } -// -// @Override -// public List 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 results = this.executeQuery(start, findAllChildren); -// results.add(0, start); -// return results; -// } -// private List processGremlinQuery(String query) { -// -// Pattern firstHasSet = Pattern.compile("^(\\.has\\(.*?\\))(\\.has\\(.*?\\))*(?!\\.has)"); -// Pattern p = Pattern.compile("\\.has\\('(.*?)',\\s?'(.*?)'\\)"); -// Matcher m = firstHasSet.matcher(query); -// List results = null; -// GremlinPipeline 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 processGremlinQuery(Vertex startVertex, String query) { -// -// Pipe pipe = Gremlin.compile(query); -// pipe.setStarts(new SingleIterator(startVertex)); -// -// return (List)IteratorUtils.toList(pipe.iterator()); -// } -// private List processGremlinQuery(List list, String query) { -// -// Pipe pipe = Gremlin.compile(query); -// -// pipe.setStarts(list); -// -// return (List)IteratorUtils.toList(pipe.iterator()); -// } -// -// -// @Override -// public List 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 results = this.executeQuery(start, findRelatedVertices); -// results.add(0, start); -// return results; -// } -// -//} -// diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/engines/query/QueryEngine.java b/aai-core/src/main/java/org/openecomp/aai/serialization/engines/query/QueryEngine.java deleted file mode 100644 index 5ac94d6c..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/engines/query/QueryEngine.java +++ /dev/null @@ -1,93 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.serialization.engines.query; - -import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; -import org.apache.tinkerpop.gremlin.process.traversal.step.util.Tree; -import org.apache.tinkerpop.gremlin.structure.Direction; -import org.apache.tinkerpop.gremlin.structure.Edge; -import org.apache.tinkerpop.gremlin.structure.Element; -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.openecomp.aai.db.props.AAIProperties; -import org.openecomp.aai.introspection.Loader; - -import java.util.List; - -public abstract class QueryEngine { - - final protected GraphTraversalSource g; - - /** - * Instantiates a new query engine. - * - * @param graphEngine the graph engine - */ - public QueryEngine (GraphTraversalSource g) { - this.g = g; - } - - /** - * Find parents. - * - * @param start the start - * @return the list - */ - public abstract List findParents(Vertex start); - - /** - * Find children. - * - * @param start the start - * @return the list - */ - public abstract List findAllChildren(Vertex start); - - public abstract List findChildrenOfType(Vertex start, String type); - - public abstract List findChildren(Vertex start); - /** - * Find deletable. - * - * @param start the start - * @return the list - */ - public abstract List findDeletable(Vertex start); - - public Tree findSubGraph(Vertex start) { - return findSubGraph(start, AAIProperties.MAXIMUM_DEPTH, false); - } - public abstract Tree findSubGraph(Vertex start, int iterations, boolean nodeOnly); - /** - * Find related vertices. - * - * @param start the start - * @param direction the direction - * @param label the label - * @param nodeType the node type - * @return the list - */ - public abstract List findRelatedVertices(Vertex start, Direction direction, String label, String nodeType); - - public abstract List findEdgesForVersion(Vertex start, Loader loader); - - public abstract List findCousinVertices(Vertex start); - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/Console.java b/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/Console.java deleted file mode 100644 index 561fd6cf..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/Console.java +++ /dev/null @@ -1,42 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.serialization.queryformats; - -import com.google.gson.JsonObject; -import org.openecomp.aai.serialization.queryformats.exceptions.AAIFormatVertexException; - -public class Console implements FormatMapper { - - @Override - public JsonObject formatObject(Object v) throws AAIFormatVertexException { - - JsonObject json = new JsonObject(); - json.addProperty("result", v.toString()); - - return json; - } - - @Override - public int parallelThreshold() { - return 100; - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/Format.java b/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/Format.java deleted file mode 100644 index 0505f626..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/Format.java +++ /dev/null @@ -1,30 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.serialization.queryformats; - -public enum Format { - graphson, - pathed, id, resource, - simple, - resource_and_url, - console, - raw -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/FormatFactory.java b/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/FormatFactory.java deleted file mode 100644 index 7753ae77..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/FormatFactory.java +++ /dev/null @@ -1,96 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.serialization.queryformats; - -import javax.ws.rs.core.MultivaluedHashMap; -import javax.ws.rs.core.MultivaluedMap; - -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.serialization.db.DBSerializer; -import org.openecomp.aai.serialization.queryformats.exceptions.QueryParamInjectionException; -import org.openecomp.aai.serialization.queryformats.utils.QueryParamInjector; -import org.openecomp.aai.serialization.queryformats.utils.UrlBuilder; - -import javax.ws.rs.core.MultivaluedHashMap; -import javax.ws.rs.core.MultivaluedMap; - -public class FormatFactory { - - private final Loader loader; - private final DBSerializer serializer; - private final UrlBuilder urlBuilder; - private final QueryParamInjector injector; - public FormatFactory (Loader loader, DBSerializer serializer) throws AAIException { - this.loader = loader; - this.serializer = serializer; - this.urlBuilder = new UrlBuilder(loader.getVersion(), serializer); - this.injector = QueryParamInjector.getInstance(); - } - - public Formatter get(Format format) throws AAIException { - return get(format, new MultivaluedHashMap()); - } - - public Formatter get(Format format, MultivaluedMap params) throws AAIException { - - Formatter formattter = null; - - switch (format) { - case graphson : - formattter = new Formatter(inject(new GraphSON(), params)); - break; - case pathed : - formattter = new Formatter(inject(new PathedURL(loader, urlBuilder), params)); - break; - case id : - formattter = new Formatter(inject(new IdURL(loader, urlBuilder), params)); - break; - case resource : - formattter = new Formatter(inject(new Resource.Builder(loader, serializer, urlBuilder), params).build()); - break; - case resource_and_url : - formattter = new Formatter(inject(new Resource.Builder(loader, serializer, urlBuilder).includeUrl(), params).build()); - break; - case raw : - formattter = new Formatter(inject(new RawFormat.Builder(loader, serializer, urlBuilder), params).build()); - break; - case simple : - formattter = new Formatter(inject(new RawFormat.Builder(loader, serializer, urlBuilder).depth(0).modelDriven(), params).build()); - break; - case console : - formattter = new Formatter(inject(new Console(), params)); - break; - default : - break; - - } - - return formattter; - } - - private T inject (T obj, MultivaluedMap params) throws QueryParamInjectionException { - - injector.injectParams(obj, params); - return obj; - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/FormatMapper.java b/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/FormatMapper.java deleted file mode 100644 index e9f17c6b..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/FormatMapper.java +++ /dev/null @@ -1,31 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.serialization.queryformats; - -import com.google.gson.JsonObject; -import org.openecomp.aai.serialization.queryformats.exceptions.AAIFormatVertexException; - -public interface FormatMapper { - - public JsonObject formatObject(Object v) throws AAIFormatVertexException; - - public int parallelThreshold(); -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/Formatter.java b/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/Formatter.java deleted file mode 100644 index 26b0411e..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/Formatter.java +++ /dev/null @@ -1,79 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.serialization.queryformats; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import org.openecomp.aai.serialization.queryformats.exceptions.AAIFormatVertexException; - -import java.util.List; -import java.util.Optional; -import java.util.stream.Stream; - -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 vertices) { - Stream stream = null; - JsonObject result = new JsonObject(); - JsonArray body = new JsonArray(); - if (vertices.size() >= format.parallelThreshold()) { - stream = vertices.parallelStream(); - } else { - stream = vertices.stream(); - } - final boolean isParallel = stream.isParallel(); - stream.map(v -> { - try { - return Optional.of(format.formatObject(v)); - } catch (AAIFormatVertexException e) { - LOGGER.warn("Failed to format vertex, returning a partial list", e); - } - - return Optional.empty(); - }).forEach(obj -> { - if (obj.isPresent()) { - if (isParallel) { - synchronized (body) { - body.add(obj.get()); - } - } else { - body.add(obj.get()); - } - } - }); - - result.add("results", body); - - return result.getAsJsonObject(); - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/GraphSON.java b/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/GraphSON.java deleted file mode 100644 index 9d119875..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/GraphSON.java +++ /dev/null @@ -1,62 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.serialization.queryformats; - -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import com.thinkaurelius.titan.graphdb.tinkerpop.TitanIoRegistry; -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 java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.OutputStream; - -public class GraphSON implements FormatMapper { - - private final GraphSONMapper mapper = GraphSONMapper.build().addRegistry(TitanIoRegistry.INSTANCE).create(); - private final GraphSONWriter writer = GraphSONWriter.build().mapper(mapper).create(); - protected JsonParser parser = new JsonParser(); - - @Override - public 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(); - } - - return parser.parse(result).getAsJsonObject(); - - } - - @Override - public int parallelThreshold() { - return 50; - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/IdURL.java b/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/IdURL.java deleted file mode 100644 index d0496c65..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/IdURL.java +++ /dev/null @@ -1,70 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.serialization.queryformats; - -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.openecomp.aai.db.props.AAIProperties; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.introspection.exceptions.AAIUnknownObjectException; -import org.openecomp.aai.serialization.queryformats.exceptions.AAIFormatVertexException; -import org.openecomp.aai.serialization.queryformats.utils.UrlBuilder; - -public class IdURL implements FormatMapper { - - 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 - public JsonObject formatObject(Object input) throws AAIFormatVertexException { - Vertex v = (Vertex)input; - try { - final Introspector searchResult = this.loader.introspectorFromName("result-data"); - - searchResult.setValue("resource-type", v.value(AAIProperties.NODE_TYPE)); - searchResult.setValue("resource-link", this.urlBuilder.id(v)); - - final String json = searchResult.marshal(false); - - return 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/openecomp/aai/serialization/queryformats/PathedURL.java b/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/PathedURL.java deleted file mode 100644 index 09383c9a..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/PathedURL.java +++ /dev/null @@ -1,69 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.serialization.queryformats; - -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.openecomp.aai.db.props.AAIProperties; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.introspection.exceptions.AAIUnknownObjectException; -import org.openecomp.aai.serialization.queryformats.exceptions.AAIFormatVertexException; -import org.openecomp.aai.serialization.queryformats.utils.UrlBuilder; - -public final class PathedURL implements FormatMapper { - - private final UrlBuilder urlBuilder; - private final JsonParser parser; - private final 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 JsonObject formatObject(Object input) throws AAIFormatVertexException { - Vertex v = (Vertex)input; - try { - final Introspector searchResult = this.loader.introspectorFromName("result-data"); - - searchResult.setValue("resource-type", v.value(AAIProperties.NODE_TYPE)); - - searchResult.setValue("resource-link", this.urlBuilder.pathed(v)); - final String json = searchResult.marshal(false); - return 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/openecomp/aai/serialization/queryformats/RawFormat.java b/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/RawFormat.java deleted file mode 100644 index 070e22f4..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/RawFormat.java +++ /dev/null @@ -1,189 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.serialization.queryformats; - -import java.util.Iterator; -import java.util.List; - -import org.apache.tinkerpop.gremlin.structure.Direction; -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.apache.tinkerpop.gremlin.structure.VertexProperty; -import org.openecomp.aai.db.props.AAIProperties; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.serialization.db.DBSerializer; -import org.openecomp.aai.serialization.queryformats.exceptions.AAIFormatVertexException; -import org.openecomp.aai.serialization.queryformats.params.Depth; -import org.openecomp.aai.serialization.queryformats.params.NodesOnly; -import org.openecomp.aai.serialization.queryformats.utils.UrlBuilder; - -import com.google.gson.Gson; -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; - - -public class RawFormat implements FormatMapper { - 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 JsonObject formatObject(Object input) throws AAIFormatVertexException { - Vertex v = (Vertex)input; - JsonObject json = new JsonObject(); - json.addProperty("id", v.id().toString()); - json.addProperty("node-type", v.value(AAIProperties.NODE_TYPE)); - json.addProperty("url", this.urlBuilder.pathed(v)); - json.add("properties", this.createPropertiesObject(v)); - if (!nodesOnly) { - json.add("related-to", this.createRelationshipObject(v)); - } - return json; - } - - @Override - public int parallelThreshold() { - return 100; - } - - - public JsonObject createPropertiesObject(Vertex v) throws AAIFormatVertexException { - JsonObject json = new JsonObject(); - Iterator> iter = v.properties(); - - while (iter.hasNext()) { - VertexProperty 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 json; - } - protected JsonArray createRelationshipObject(Vertex v) throws AAIFormatVertexException { - JsonArray jarray = new JsonArray(); - Iterator iter = v.vertices(Direction.BOTH); - - while (iter.hasNext()) { - Vertex related = iter.next(); - - JsonObject json = new JsonObject(); - json.addProperty("id", related.id().toString()); - json.addProperty("node-type", related.value(AAIProperties.NODE_TYPE)); - json.addProperty("url", this.urlBuilder.pathed(related)); - jarray.add(json); - } - - return jarray; - } - - public static class Builder implements NodesOnly, Depth { - - 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); - } - } - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/Resource.java b/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/Resource.java deleted file mode 100644 index 9a090a4b..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/Resource.java +++ /dev/null @@ -1,162 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.serialization.queryformats; - -import java.io.UnsupportedEncodingException; -import java.util.ArrayList; -import java.util.List; - -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.openecomp.aai.db.props.AAIProperties; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.introspection.exceptions.AAIUnknownObjectException; -import org.openecomp.aai.serialization.db.DBSerializer; -import org.openecomp.aai.serialization.queryformats.exceptions.AAIFormatVertexException; -import org.openecomp.aai.serialization.queryformats.params.Depth; -import org.openecomp.aai.serialization.queryformats.params.NodesOnly; -import org.openecomp.aai.serialization.queryformats.utils.UrlBuilder; - -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; - -public class Resource implements FormatMapper { - - 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 - public JsonObject formatObject(Object input) throws AAIFormatVertexException { - Vertex v = (Vertex)input; - JsonObject json = new JsonObject(); - - if (this.includeUrl) { - json.addProperty("url", this.urlBuilder.pathed(v)); - } - json.add(v.property(AAIProperties.NODE_TYPE) - .orElse(null), this.vertexToJsonObject(v)); - - return json; - } - - protected JsonObject vertexToJsonObject(Vertex v) throws AAIFormatVertexException { - try { - final Introspector obj = getLoader().introspectorFromName( - v.property(AAIProperties.NODE_TYPE) - .orElse(null) - ); - - final List 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 getParser().parse(json).getAsJsonObject(); - } catch (AAIUnknownObjectException e) { - throw new AAIFormatVertexException("Failed to format vertex - unknown object", e); - } - } - - @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, Depth { - - 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/openecomp/aai/serialization/queryformats/SimpleFormat.java b/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/SimpleFormat.java deleted file mode 100644 index f3a2990c..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/SimpleFormat.java +++ /dev/null @@ -1,75 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.serialization.queryformats; - -import java.io.UnsupportedEncodingException; -import java.util.ArrayList; -import java.util.List; - -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.openecomp.aai.db.props.AAIProperties; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.exceptions.AAIUnknownObjectException; -import org.openecomp.aai.serialization.queryformats.exceptions.AAIFormatVertexException; - -import com.google.gson.JsonObject; - -public class SimpleFormat extends RawFormat { - - - protected SimpleFormat(Builder builder) { - super(builder); - - } - - @Override - public int parallelThreshold() { - return 20; - } - - @Override - public JsonObject createPropertiesObject(Vertex v) throws AAIFormatVertexException { - try { - final Introspector obj = loader.introspectorFromName( - v.property(AAIProperties.NODE_TYPE) - .orElse(null) - ); - - final List 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 parser.parse(json).getAsJsonObject(); - } catch (AAIUnknownObjectException e) { - throw new AAIFormatVertexException("Failed to format vertex - unknown object", e); - } - - - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/SubGraphStyle.java b/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/SubGraphStyle.java deleted file mode 100644 index 15c5041d..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/SubGraphStyle.java +++ /dev/null @@ -1,27 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.serialization.queryformats; - -public enum SubGraphStyle { - star, - prune, - no_op -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/exceptions/AAIFormatVertexException.java b/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/exceptions/AAIFormatVertexException.java deleted file mode 100644 index dc2b8a71..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/exceptions/AAIFormatVertexException.java +++ /dev/null @@ -1,40 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.serialization.queryformats.exceptions; - -public class AAIFormatVertexException extends Exception { - - private static final long serialVersionUID = -5814240841844624097L; - - public AAIFormatVertexException() {} - - public AAIFormatVertexException(String message) { - super(message); - } - - public AAIFormatVertexException(Throwable cause) { - super(cause); - } - - public AAIFormatVertexException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/exceptions/QueryParamInjectionException.java b/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/exceptions/QueryParamInjectionException.java deleted file mode 100644 index 6f75e3ba..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/exceptions/QueryParamInjectionException.java +++ /dev/null @@ -1,40 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.serialization.queryformats.exceptions; - -import org.openecomp.aai.exceptions.AAIException; - -public class QueryParamInjectionException extends AAIException { - - private static final long serialVersionUID = -5575661036426538012L; - - public QueryParamInjectionException(String message) { - super("AAI_4017", message); - } - - public QueryParamInjectionException(Throwable cause) { - super("AAI_4017",cause); - } - - public QueryParamInjectionException(String message, Throwable cause) { - super("AAI_4017", cause, message); - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/params/Depth.java b/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/params/Depth.java deleted file mode 100644 index d5ade869..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/params/Depth.java +++ /dev/null @@ -1,28 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.serialization.queryformats.params; - -@Inject(name = "depth") -public interface Depth { - - @Setter - public T depth(Integer depth); -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/params/Inject.java b/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/params/Inject.java deleted file mode 100644 index 128b7394..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/params/Inject.java +++ /dev/null @@ -1,34 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.serialization.queryformats.params; - -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; - -@Retention(RetentionPolicy.RUNTIME) -public @interface Inject { - - /** - * The way the query parameter appears in the URI - * @return - */ - String name(); -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/params/NodesOnly.java b/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/params/NodesOnly.java deleted file mode 100644 index e81b5447..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/params/NodesOnly.java +++ /dev/null @@ -1,28 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.serialization.queryformats.params; - -@Inject(name = "nodesOnly") -public interface NodesOnly { - - @Setter - public T nodesOnly(Boolean nodesOnly); -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/params/Setter.java b/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/params/Setter.java deleted file mode 100644 index ad866c22..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/params/Setter.java +++ /dev/null @@ -1,36 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.serialization.queryformats.params; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.METHOD}) -/** - * Marks what method in the object should be used for setting the value - * of the query parameter - */ -public @interface Setter { - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/utils/QueryParamInjector.java b/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/utils/QueryParamInjector.java deleted file mode 100644 index 725152dd..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/utils/QueryParamInjector.java +++ /dev/null @@ -1,84 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.serialization.queryformats.utils; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.Set; - -import javax.ws.rs.core.MultivaluedMap; - -import org.openecomp.aai.serialization.queryformats.exceptions.QueryParamInjectionException; -import org.openecomp.aai.serialization.queryformats.params.Inject; -import org.openecomp.aai.serialization.queryformats.params.Setter; -import org.reflections.Reflections; - -public class QueryParamInjector { - - private final Set> results; - - - private QueryParamInjector () { - Reflections reflections = new Reflections("org.openecomp.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 injectParams(T obj, MultivaluedMap 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/openecomp/aai/serialization/queryformats/utils/UrlBuilder.java b/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/utils/UrlBuilder.java deleted file mode 100644 index 5579c8a6..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/utils/UrlBuilder.java +++ /dev/null @@ -1,91 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.serialization.queryformats.utils; - -import java.io.UnsupportedEncodingException; -import java.net.URI; -import java.net.URISyntaxException; - -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Version; -import org.openecomp.aai.serialization.db.DBSerializer; -import org.openecomp.aai.serialization.queryformats.exceptions.AAIFormatVertexException; -import org.openecomp.aai.util.AAIApiServerURLBase; -import org.openecomp.aai.util.AAIConstants; -import org.openecomp.aai.workarounds.LegacyURITransformer; - -public class UrlBuilder { - - private final DBSerializer serializer; - private final Version version; - private final String serverBase; - - public UrlBuilder (Version version, DBSerializer serializer) throws AAIException { - this.serializer = serializer; - this.version = version; - this.serverBase = this.getServerBase(version); - } - - public UrlBuilder (Version version, DBSerializer serializer, String serverBase) { - this.serializer = serializer; - this.version = version; - this.serverBase = serverBase; - } - - public String pathed(Vertex v) throws AAIFormatVertexException { - - try { - final StringBuilder result = new StringBuilder(); - final URI uri = this.serializer.getURIForVertex(v); - - if (this.version.compareTo(Version.v11) >= 0) { - result.append(AAIConstants.AAI_APP_ROOT); - } else { - result.append(this.serverBase); - } - result.append(this.version); - result.append(uri); - - 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(Version.v11) >= 0) { - result.insert(0, AAIConstants.AAI_APP_ROOT); - } else { - result.insert(0, this.serverBase); - } - - return result.toString(); - } - - protected String getServerBase(Version v) throws AAIException { - return AAIApiServerURLBase.get(v); - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/tinkerpop/TreeBackedEdge.java b/aai-core/src/main/java/org/openecomp/aai/serialization/tinkerpop/TreeBackedEdge.java deleted file mode 100644 index 774ab28f..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/tinkerpop/TreeBackedEdge.java +++ /dev/null @@ -1,80 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.serialization.tinkerpop; - -import org.apache.tinkerpop.gremlin.structure.Direction; -import org.apache.tinkerpop.gremlin.structure.Edge; -import org.apache.tinkerpop.gremlin.structure.Graph; -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.apache.tinkerpop.gremlin.structure.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, - * 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 bothVertices() { - return this.vertices(Direction.BOTH); - } - - @Override - public Iterator 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/openecomp/aai/serialization/tinkerpop/TreeBackedVertex.java b/aai-core/src/main/java/org/openecomp/aai/serialization/tinkerpop/TreeBackedVertex.java deleted file mode 100644 index 7ebad216..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/tinkerpop/TreeBackedVertex.java +++ /dev/null @@ -1,162 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.serialization.tinkerpop; - -import org.apache.tinkerpop.gremlin.process.traversal.step.util.Tree; -import org.apache.tinkerpop.gremlin.structure.*; -import org.apache.tinkerpop.gremlin.structure.util.detached.DetachedVertex; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; - -/** - * 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. - * - */ - -public class TreeBackedVertex extends DetachedVertex implements Vertex { - - private static final long serialVersionUID = -976854460992756953L; - private final Tree tree; - private final Vertex self; - public TreeBackedVertex (Vertex v, Tree tree) { - super(v, true); - this.self = v; - this.tree = tree; - } - - @Override - public Iterator edges(final Direction direction, final String... edgeLabels) { - final List edges = tree.getObjectsAtDepth(2); - final List> trees = tree.getTreesAtDepth(2); - final List> 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 eTree = new Tree<>(); - for (Tree 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> trees) { - Tree vTree = new Tree<>(); - for (Tree tree : trees) { - if (tree.keySet().contains(v)) { - vTree = tree; - break; - } - } - - return new TreeBackedVertex((Vertex)vTree.keySet().iterator().next(), vTree); - } - @Override - public Iterator vertices(final Direction direction, final String... labels) { - final List> vertexElements = tree.getTreesAtDepth(3); - final List 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 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 itr = e.bothVertices(); - while (itr.hasNext()) { - list.add(itr.next()); - } - } - return list; - - }).flatMap(list -> list.stream()).map(v -> { - Tree vTree = new Tree(); - for (Tree 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/openecomp/aai/tasks/ScheduledTasks.java b/aai-core/src/main/java/org/openecomp/aai/tasks/ScheduledTasks.java deleted file mode 100644 index f0a4d41a..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/tasks/ScheduledTasks.java +++ /dev/null @@ -1,90 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.tasks; - -import java.io.File; -import java.util.Arrays; -import java.util.Date; -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.openecomp.aai.logging.LoggingContext; -import org.openecomp.aai.util.AAIConfig; -import org.openecomp.aai.util.AAIConstants; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -@Component -public class ScheduledTasks { - - 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 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(); - - LoggingContext.requestId(transId); - LoggingContext.partnerName(FROM_APP_ID); - LoggingContext.component(COMPONENT); - - 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; - - // 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.info("reloaded from aaiconfig.properties"); - } - break; - } - } - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/util/AAIApiServerURLBase.java b/aai-core/src/main/java/org/openecomp/aai/util/AAIApiServerURLBase.java deleted file mode 100644 index 12a2c06d..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/util/AAIApiServerURLBase.java +++ /dev/null @@ -1,80 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.util; - -import java.util.List; -import java.util.Map; - -import org.apache.cxf.helpers.CastUtils; -import org.apache.cxf.message.Message; -import org.apache.cxf.phase.PhaseInterceptorChain; - -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Version; - -public class AAIApiServerURLBase { - - /** - * Gets the. - * - * @return the string - * @throws AAIException the AAI exception - */ - public static String get() throws AAIException { - - String hostName = null; - try { - Message message = PhaseInterceptorChain.getCurrentMessage(); - Map> headers = CastUtils.cast((Map) message.get(Message.PROTOCOL_HEADERS)); - List sa = null; - if (headers != null) { - sa = headers.get("host"); - } - - if (sa != null && sa.size() == 1) { - hostName = "https://"+ sa.get(0).toString() + "/aai/"; - } - } catch (Exception e) { - // TODO: we may want to log an error here - } - // TODO: should this check the value a little closer and look for a pattern? - if (hostName == null) { - hostName = AAIConfig.get(AAIConstants.AAI_SERVER_URL_BASE); - //AAIConstants.AAI_SERVER_URL_BASE; - } - return hostName; - } - - /** - * Gets the. - * - * @param v the v - * @return the string - * @throws AAIException the AAI exception - */ - public static String get(Version v) throws AAIException { - String hostName = null; - hostName = AAIApiServerURLBase.get(); - - return hostName; - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/util/AAIApiVersion.java b/aai-core/src/main/java/org/openecomp/aai/util/AAIApiVersion.java deleted file mode 100644 index 680fcf63..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/util/AAIApiVersion.java +++ /dev/null @@ -1,74 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.util; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.cxf.message.Message; -import org.apache.cxf.phase.PhaseInterceptorChain; - -import org.openecomp.aai.exceptions.AAIException; - -public class AAIApiVersion { - - private static final Pattern versionPattern = Pattern.compile("(^|\\/)(v\\d+)\\/"); - - private static final Pattern latestVersionPattern = Pattern.compile("(^|\\/)(latest)\\/"); - - /** - * Gets the. - * - * @return the string - * @throws AAIException the AAI exception - */ - public static String get() throws AAIException { - - String apiVersion = null; - try { - Message message = PhaseInterceptorChain.getCurrentMessage(); - String requestURI = (String) message.get(Message.REQUEST_URI); - - if (requestURI != null) { - Matcher matcher = versionPattern.matcher(requestURI); - if (matcher.find() && matcher.groupCount() >= 2) { - apiVersion = matcher.group(2); - } - if (apiVersion == null) { - Matcher latestMatcher = latestVersionPattern.matcher(requestURI); - if (latestMatcher.find() && latestMatcher.groupCount() >= 2) { - apiVersion = AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP, AAIConstants.AAI_DEFAULT_API_VERSION); - } - } - - } - - } catch (Exception e) { - // TODO: we may want to log an error here - } - // TODO: should this check the value a little closer and look for a pattern? - if (apiVersion == null || !apiVersion.startsWith("v")) { - apiVersion = AAIConfig.get (AAIConstants.AAI_DEFAULT_API_VERSION_PROP, AAIConstants.AAI_DEFAULT_API_VERSION); - //apiVersion = AAIConstants.AAI_DEFAULT_API_VERSION; - } - return apiVersion; - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/util/AAICSVWriter.java b/aai-core/src/main/java/org/openecomp/aai/util/AAICSVWriter.java deleted file mode 100644 index 5467168c..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/util/AAICSVWriter.java +++ /dev/null @@ -1,167 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -/** - * - */ -package org.openecomp.aai.util; - -import java.io.IOException; -import java.io.PrintWriter; -import java.io.Writer; - -import com.opencsv.CSVWriter; - -/** - * had to overwrite the separate character to separate string - * Based on the public - A very simple CSV writer released under a commercial-friendly license. - * - - */ -public class AAICSVWriter extends CSVWriter { - - private String separatorStr; - private char overridequotechar; - private String overridelineEnd; - private Writer rawWriter; - private PrintWriter pw; - - /** - * Instantiates a new AAICSV writer. - * - * @param writer the writer - */ - public AAICSVWriter(Writer writer) { - super(writer); - // TODO Auto-generated constructor stub - } - - /** - * Constructs AAICSVWriter with supplied separator string and quote char. - * - * @param writer the writer to an underlying CSV source. - * @param overrideseparator the overrideseparator - * @param quotechar the character to use for quoted elements - * @param lineEnd the line feed terminator to use - */ - public AAICSVWriter(Writer writer, String overrideseparator, char quotechar, String lineEnd) { - super(writer, CSVWriter.DEFAULT_SEPARATOR, quotechar, DEFAULT_ESCAPE_CHARACTER, lineEnd); - separatorStr = overrideseparator; - overridequotechar = quotechar; - overridelineEnd = lineEnd; - this.rawWriter = writer; - this.pw = new PrintWriter(writer); - } - - /** - * String contains special characters. - * - * @param line the line - * @return true, if successful - */ - private boolean stringContainsSpecialCharacters(String line) { - return line.indexOf(overridequotechar) != -1 || line.indexOf(DEFAULT_ESCAPE_CHARACTER) != -1 || line.indexOf(separatorStr) != -1 || line.contains("\n") || line.contains("\r"); - } - - /** - * Close the underlying stream writer flushing any buffered content. - * - * @throws IOException if bad things happen - */ - public void close() throws IOException { - flush(); - pw.close(); - rawWriter.close(); - } - - /** - * Writes the next line to the file. - * - * @param nextLine a string array with each comma-separated element as a separate - * entry. - * @param applyQuotesToAll true if all values are to be quoted. false applies quotes only - * to values which contain the separator, escape, quote or new line characters. - */ - public void writeNext(String[] nextLine, boolean applyQuotesToAll) { - - if (nextLine == null) - return; - - StringBuilder sb = new StringBuilder(INITIAL_STRING_SIZE); - for (int i = 0; i < nextLine.length; i++) { - - if (i != 0) { - sb.append(separatorStr); - } - - String nextElement = nextLine[i]; - - if (nextElement == null) - continue; - - Boolean stringContainsSpecialCharacters = stringContainsSpecialCharacters(nextElement); - - if ((applyQuotesToAll || stringContainsSpecialCharacters) && overridequotechar != NO_QUOTE_CHARACTER) - sb.append(overridequotechar); - - if (stringContainsSpecialCharacters) { - sb.append(processLine(nextElement)); - } else { - sb.append(nextElement); - } - - if ((applyQuotesToAll || stringContainsSpecialCharacters) && overridequotechar != NO_QUOTE_CHARACTER) - sb.append(overridequotechar); - } - - sb.append(overridelineEnd); - pw.write(sb.toString()); - } - - - /** - * Writes the next line to the file ignoring all exceptions. - * - * @param nextLine a string array with each comma-separated element as a separate - * entry. - */ - public void writeColumn(String[] nextLine) { - - if (nextLine == null) - return; - - StringBuilder sb = new StringBuilder(INITIAL_STRING_SIZE); - for (int i = 0; i < nextLine.length; i++) { - - - String nextElement = nextLine[i]; - - if (nextElement == null) - continue; - - sb.append(nextElement); - - - } - - sb.append(overridelineEnd); - pw.write(sb.toString()); - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/util/AAIConfig.java b/aai-core/src/main/java/org/openecomp/aai/util/AAIConfig.java deleted file mode 100644 index 9fcb521d..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/util/AAIConfig.java +++ /dev/null @@ -1,266 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.util; - -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.net.InetAddress; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Properties; -import java.util.Timer; - -import org.eclipse.jetty.util.security.Password; - -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.logging.ErrorLogHelper; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - - -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 boolean propsInitialized = false; - - // this (probably) won't change between releases, put it in the config if it gets annoying... - private static HashMap> defaultBools = new HashMap>(); - private static Timer timer = new Timer(); - - /** - * Instantiates a new AAI config. - */ - // Don't instantiate - private AAIConfig() {} - - /** - * Inits the. - * - * @throws AAIException the AAI exception - */ - public synchronized static void init() throws AAIException{ - LOGGER.info("Initializing AAIConfig"); - - ArrayList genericVnfBools = new ArrayList(); - ArrayList l3NetworkBools = new ArrayList(); - ArrayList pserverBools = new ArrayList(); - ArrayList subnetBools = new ArrayList(); - ArrayList vserverBools = new ArrayList(); - ArrayList vnfcBools = new ArrayList(); - - genericVnfBools.add("in-maint"); - genericVnfBools.add("is-closed-loop-disabled"); - l3NetworkBools.add("is-bound-to-vpn"); - pserverBools.add("in-maint"); - subnetBools.add("dhcp-enabled"); - vserverBools.add("in-maint"); - vserverBools.add("is-closed-loop-disabled"); - vnfcBools.add("in-maint"); - vnfcBools.add("is-closed-loop-disabled"); - - defaultBools.put("generic-vnf", genericVnfBools); - defaultBools.put("l3-network", l3NetworkBools); - defaultBools.put("pserver", pserverBools); - defaultBools.put("subnet", subnetBools); - defaultBools.put("vserver", vserverBools); - defaultBools.put("vnfc", vnfcBools); - - AAIConfig.getConfigFile(); - AAIConfig.reloadConfig(); - - if (AAIConstants.AAI_NODENAME == null || AAIConstants.AAI_NODENAME == "") { - ErrorLogHelper.logError("AAI_4005", " AAI_NODENAME is not defined"); - } else { - LOGGER.info("A&AI Server Node Name = " + AAIConstants.AAI_NODENAME); - } - } - - /** - * Gets the default bools. - * - * @return the default bools - */ - public static HashMap> getDefaultBools() { - return defaultBools; - } - - /** - * Cleanup. - */ - public static void cleanup() { - timer.cancel(); - } - - /** - * Gets the config file. - * - * @return the config file - */ - public static String getConfigFile() { -// if (GlobalPropFileName == null) { -// String nc = System.getProperty("aaiconfig"); -// if (nc == null) nc = "/home/aaiadmin/etc/aaiconfig.props"; -// logger.info( "aaiconfig = " + nc==null?"null":nc); -// GlobalPropFileName = nc; -// } - return GLOBAL_PROP_FILE_NAME; - } - - /** - * Reload config. - */ - public synchronized static void reloadConfig() { - - String propFileName = GLOBAL_PROP_FILE_NAME; - Properties newServerProps = null; - - LOGGER.info("Reloading config from " + propFileName); - - try { - InputStream is = new FileInputStream(propFileName); - newServerProps = new Properties(); - newServerProps.load(is); - propsInitialized = true; - - serverProps = newServerProps; - newServerProps = null; - - } catch (FileNotFoundException fnfe) { - ErrorLogHelper.logError("AAI_4001", " " + propFileName + ". Exception: "+fnfe.getMessage()); - } catch (IOException e) { - ErrorLogHelper.logError("AAI_4002", " " + propFileName + ". IOException: "+e.getMessage()); - } - } - - /** - * Gets the. - * - * @param key the key - * @param defaultValue the default value - * @return the string - */ - public static String get(String key, String defaultValue) { - String result = defaultValue; - try { - result = get (key); - } - catch ( AAIException a ) { - - } - return ( result ); - } - - /** - * Gets the. - * - * @param key the key - * @return the string - * @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; - } - - /** - * Gets the int. - * - * @param key the key - * @return the int - * @throws AAIException the AAI exception - */ - public static int getInt(String key) throws AAIException{ - return Integer.valueOf(AAIConfig.get(key)); - } - - /** - * Gets the server props. - * - * @return the server props - */ - public static Properties getServerProps() { - return serverProps; - } - - /** - * Gets the node name. - * - * @return the node name - */ - public static String getNodeName() { - try { - InetAddress ip = InetAddress.getLocalHost(); - if (ip != null) { - String hostname = ip.getHostName(); - if (hostname != null) { - return hostname; - } - } - } catch (Exception e) { - return null; - } - return null; - } - - - /** - * 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/openecomp/aai/util/AAIConfigCommandLinePropGetter.java b/aai-core/src/main/java/org/openecomp/aai/util/AAIConfigCommandLinePropGetter.java deleted file mode 100644 index c6ddc4fd..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/util/AAIConfigCommandLinePropGetter.java +++ /dev/null @@ -1,66 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.util; - -import org.openecomp.aai.exceptions.AAIException; - -/* - * The script deobfuscatePW.sh needs to retrieve pws from the AAIConfig file. - * As AAIConfig has no main to be callable on the command line, this class helps - * by providing one for accessing AAIConfig that way. - * (AAIConfig deobfuscates pws itself, so we just need to call its .get() on the desired pw.) - * - * This could be used to get any property from AAIConfig via the command line, - * not just the pws, even though it was made for pw-related needs. - */ -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); - } - - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/util/AAIConstants.java b/aai-core/src/main/java/org/openecomp/aai/util/AAIConstants.java deleted file mode 100644 index 6c23c6e3..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/util/AAIConstants.java +++ /dev/null @@ -1,151 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.util; - -import org.openecomp.aai.db.props.AAIProperties; - -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"); - // - /** 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; - - /** etc directory, relative to AAI_HOME */ - public static final String AAI_HOME_ETC = AAI_HOME_BUNDLECONFIG + AAI_FILESEP + "etc" + AAI_FILESEP; - public static final String AAI_HOME_ETC_APP_PROPERTIES = AAI_HOME_ETC + "appprops" + AAI_FILESEP; - public static final String AAI_V2_OUTPUT_TRANSFORMS = AAIConstants.AAI_HOME_ETC_APP_PROPERTIES + AAIConstants.AAI_FILESEP + "output" + AAIConstants.AAI_FILESEP; - public static final String AAI_HOME_ETC_AUTH = AAI_HOME_ETC + "auth" + AAI_FILESEP; - public static final String AAI_CONFIG_FILENAME = AAI_HOME_ETC_APP_PROPERTIES + "aaiconfig.properties"; - public static final String AAI_AUTH_CONFIG_FILENAME = AAI_HOME_ETC_AUTH + "aai_policy.json"; - public static final String AAI_MECHID_CONFIG_FILENAME = AAI_HOME_ETC_APP_PROPERTIES + "mechIds.json"; - public static final String AAI_HOME_ETC_QUERY = AAI_HOME_ETC + "query" + AAI_FILESEP + "stored-queries.properties"; - public static final String REALTIME_DB_CONFIG = AAI_HOME_ETC_APP_PROPERTIES + "titan-realtime.properties"; - public static final String CACHED_DB_CONFIG = AAI_HOME_ETC_APP_PROPERTIES + "titan-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_PROV_LOGBACK_PROPS = "prov-logback.xml"; - public static final String AAI_GETRES_LOGBACK_PROPS = "getres-logback.xml"; - public static final String AAI_DELTOOL_LOGBACK_PROPS = "deltool-logback.xml"; - public static final String AAI_UPDTOOL_LOGBACK_PROPS = "updtool-logback.xml"; - public static final String AAI_PUTTOOL_LOGBACK_PROPS = "puttool-logback.xml"; - public static final String AAI_POSTTOOL_LOGBACK_PROPS = "posttool-logback.xml"; - public static final String AAI_NOTIFYSDNCTOOL_LOGBACK_PROPS = "notifysdnctool-logback.xml"; - public static final String AAI_RSHIPTOOL_LOGBACK_PROPS = "rshiptool-logback.xml"; - public static final String AAI_LOGBACK_PROPS = "logback.xml"; - - - public static final String AAI_CREATE_DB_SCHEMA_LOGBACK_PROPS = "createDBSchema-logback.xml"; - public static final String AAI_PULL_INV_DATA_LOGBACK_PROPS = "pullInvData-logback.xml"; - public static final String AAI_DATA_GROOMING_LOGBACK_PROPS = "dataGrooming-logback.xml"; - public static final String AAI_DATA_SNAPSHOT_LOGBACK_PROPS = "dataSnapshot-logback.xml"; - public static final String AAI_SCHEMA_MOD_LOGBACK_PROPS = "schemaMod-logback.xml"; - public static final String AAI_FORCE_DELETE_LOGBACK_PROPS = "forceDelete-logback.xml"; - - public static final String AAI_LOAD_DATA_DHV_LOGBACK_PROPS = "loadDataForDHV-logback.xml"; - - public static final String AVPN_INTERIM_LAG_INTERFACE = "aai.avpn.interim.laginterface"; - - public static final String AAI_TRUSTSTORE_FILENAME = "aai.truststore.filename"; - public static final String AAI_TRUSTSTORE_PASSWD = "aai.truststore.passwd"; - public static final String AAI_KEYSTORE_FILENAME = "aai.keystore.filename"; - public static final String AAI_KEYSTORE_PASSWD = "aai.keystore.passwd"; - - public static final String AAI_OLDSERVER_URL_BASE = "aai.oldserver.url.base"; - public static final String AAI_SERVER_URL_BASE = "aai.server.url.base"; - public static final String AAI_SERVER_URL = "aai.server.url"; - public static final String AAI_OLDSERVER_URL = "aai.oldserver.url"; - public static final String AAI_GLOBAL_CALLBACK_URL = "aai.global.callback.url"; - public static final String AAI_LOCAL_REST = "https://localhost:%d/aai/" + AAIProperties.LATEST + "/"; - public static final String AAI_APP_ROOT = "/aai/"; - - public static final int AAI_RESOURCES_PORT = 8447; - public static final int AAI_QUERY_PORT = 8446; - public static final int AAI_LEGACY_PORT = 8443; - - public static final String AAI_DEFAULT_API_VERSION = "v7"; - public static final String AAI_DEFAULT_API_VERSION_PROP = "aai.default.api.version"; - public static final String AAI_NOTIFICATION_CURRENT_VERSION = "aai.notification.current.version"; - - public static final String AAI_NODENAME = "aai.config.nodename"; - - public static final String AAI_LOGGING_HBASE_INTERCEPTOR = "aai.logging.hbase.interceptor"; - public static final String AAI_LOGGING_HBASE_ENABLED = "aai.logging.hbase.enabled"; - public static final String AAI_LOGGING_HBASE_LOGREQUEST = "aai.logging.hbase.logrequest"; - public static final String AAI_LOGGING_HBASE_LOGRESPONSE = "aai.logging.hbase.logresponse"; - - public static final String AAI_LOGGING_TRACE_ENABLED = "aai.logging.trace.enabled"; - public static final String AAI_LOGGING_TRACE_LOGREQUEST = "aai.logging.trace.logrequest"; - public static final String AAI_LOGGING_TRACE_LOGRESPONSE = "aai.logging.trace.logresponse"; - - public static final String AAI_CONFIG_CHECKINGTIME = "aai.config.checktime"; - public static final String AAI_DBMODEL_FILENAME = "aai.dbmodel.filename"; - public static final String AAI_RESVERSION_ENABLEFLAG = "aai.resourceversion.enableflag"; - - public static final int AAI_MAX_TRANS_RETRIES = 5; - public static final long AAI_TRANS_RETRY_SLEEP_MSEC = 500; - - public static final int AAI_GROOMING_DEFAULT_MAX_FIX = 150; - public static final int AAI_GROOMING_DEFAULT_SLEEP_MINUTES = 7; - - public static final int AAI_DUPETOOL_DEFAULT_MAX_FIX = 25; - public static final int AAI_DUPETOOL_DEFAULT_SLEEP_MINUTES = 7; - - public static final String LOGGING_MAX_STACK_TRACE_ENTRIES = "aai.logging.maxStackTraceEntries"; - - /** Default to skipping real-time grooming unless system property aai.skiprealtime.grooming is set to "false" */ - public static final String AAI_SKIPREALTIME_GROOMING = (System.getProperty("aai.skiprealtime.grooming") == null) ? "true" : System.getProperty("aai.skiprealtime.grooming"); - - - /*** UEB ***/ - public static final String UEB_PUB_PARTITION_AAI = "AAI"; - public static final String UEB_PUB_AAI_VCE_INTERFACE_DATA_TOPIC = "ueb.pub.aai.vce.interface.data.topic"; - - - /** Service description for Hosted Communications */ - public static final String AAI_SERVICEDESCRIPTION_HOSTEDCOMM = "aai.servicedescription.hostedcomm"; - - /** Service description for Mobility */ - public static final String AAI_SERVICEDESCRIPTION_MOBILITY = "aai.servicedescription.mobility"; - - /** Service description for Mobility */ - public static final String AAI_SERVICEDESCRIPTION_VUSP = "aai.servicedescription.vusp"; - - /** Service description for Vvig */ - public static final String AAI_SERVICEDESCRIPTION_VVIG = "aai.servicedescription.vvig"; - - /** Service description for LRSI */ - public static final String AAI_SERVICEDESCRIPTION_LRSI = "aai.servicedescription.lrsi"; - - /** - * Instantiates a new AAI constants. - */ - private AAIConstants() { - // prevent instantiation - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/util/AAIMechIdConfig.java b/aai-core/src/main/java/org/openecomp/aai/util/AAIMechIdConfig.java deleted file mode 100644 index 54331f4e..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/util/AAIMechIdConfig.java +++ /dev/null @@ -1,129 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.util; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Set; - -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; -import org.json.simple.parser.JSONParser; - -import org.openecomp.aai.logging.ErrorLogHelper; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -public class AAIMechIdConfig { - private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(AAIMechIdConfig.class); - private static final String mechIdConfigFileName = AAIConstants.AAI_HOME_ETC_APP_PROPERTIES + "mechid-config.json"; - - public static final String SYSTEM_GFP_IP = "GFP"; - public static final String SYSTEM_GCP = "GCP"; - public static final String SYSTEM_DCAE = "DCAE"; - public static final String SYSTEM_RUBY = "RUBY"; - public static final String SYSTEM_ACTION = "ACTION"; - public static final String SYSTEM_INSTAR = "INSTAR-LPP-AMS"; - public static final String FILE_CLASS_GFP_IP = "GFP-IP"; - public static final String FILE_CLASS_INSTAR = "INSTAR-LPP-AMS"; - - public static HashMap mechIdtoSystem = new HashMap(); - public static HashMap> fileClassToMechId = new HashMap>(); - - /** - * Inits the. - * - * @param tId the t id - * @param appId the app id - * @param logger the logger - */ - public static void init() { - LOGGER.debug("Initializing AAIMechIdConfig"); - Boolean enable; - String systemMechId = ""; - JSONParser parser = new JSONParser(); - - try { - Object obj = parser.parse(new FileReader(mechIdConfigFileName)); - JSONObject jsonObject = (JSONObject) obj; - JSONObject mechIds = (JSONObject) jsonObject.get("mech-ids"); - - @SuppressWarnings("unchecked") - Set systemSet = mechIds.keySet(); - for (String system : systemSet) { - JSONObject systemJsonObj = (JSONObject) mechIds.get(system); - systemMechId = (String) systemJsonObj.get("mechid"); - enable = (Boolean) systemJsonObj.get("enable"); - if (systemMechId != null && !systemMechId.isEmpty() && enable != null && enable == true) { - mechIdtoSystem.put(systemMechId, system); - JSONArray fileClasses = (JSONArray) systemJsonObj.get("file-classes"); - if (fileClasses != null ) { - String fileClass = ""; - for (Object fileClassObj : fileClasses) { - fileClass = (String) fileClassObj; - - if (!fileClassToMechId.containsKey(fileClass)) { - fileClassToMechId.put(fileClass, new ArrayList()); - fileClassToMechId.get(fileClass).add(systemMechId); - } else { - if(!fileClassToMechId.get(fileClass).contains(systemMechId)){ - fileClassToMechId.get(fileClass).add(systemMechId); - - } - } - } - } - } - } - - } catch (FileNotFoundException fnfe) { - ErrorLogHelper.logError("AAI_4001", - " " + mechIdConfigFileName + ". Exception: " + fnfe.getMessage()); - } catch (Exception e) { - ErrorLogHelper.logError("AAI_4004", - " " + mechIdConfigFileName + ". Exception: " + e.getMessage()); - } - } - - - /** - * Transform mech id to pickup dir. - * - * @param systemMechId the system mech id - * @return the string - */ - public static String transformMechIdToPickupDir(String systemMechId) { - String pickupDir = ""; - if (systemMechId != null && !systemMechId.isEmpty()) { - pickupDir = "/opt/aaihome/" + systemMechId + "/pickup"; - - if (pickupDir != null && !pickupDir.isEmpty() && new File(pickupDir).isDirectory()) { - return pickupDir; - } - - } - return null; - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/util/AAIRSyncUtility.java b/aai-core/src/main/java/org/openecomp/aai/util/AAIRSyncUtility.java deleted file mode 100644 index 9c93d5ef..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/util/AAIRSyncUtility.java +++ /dev/null @@ -1,197 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -/** - * - */ -package org.openecomp.aai.util; - -import java.io.BufferedReader; -import java.io.InputStreamReader; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.ArrayList; -import java.util.List; -import java.util.StringTokenizer; - -import org.openecomp.aai.exceptions.AAIException; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - - -public class AAIRSyncUtility { - - private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(AAIRSyncUtility.class); - private final String DEFAULT_CHECK = new String("aai.primary.filetransfer."); - - /** - * Instantiates a new AAIR sync utility. - */ - public AAIRSyncUtility() { - - } - - /** - * Do command. - * - * @param command the command - * @return the int - * @throws Exception the exception - */ - public int doCommand(List command) - throws Exception - { - String s = null; - - ProcessBuilder pb = new ProcessBuilder(command); - Process process = pb.start(); - - BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream())); - BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream())); - - LOGGER.debug("Here is the standard output of the command:\n"); - while ((s = stdInput.readLine()) != null) - { - LOGGER.debug(s); - } - - LOGGER.debug("Here is the standard error of the command (if any):\n"); - while ((s = stdError.readLine()) != null) - { - LOGGER.debug(s); - } - return process.waitFor(); - } - - - /** - * Method sendRsyncCommand. - * - * @param transId the trans id - * @param fileName the file name - */ - public void sendRsyncCommand(String transId, String fileName) - { - String aaiServerList = null; - String rsyncOptionsList = null; - - try { - aaiServerList = AAIConfig.get(DEFAULT_CHECK + "serverlist"); - rsyncOptionsList = AAIConfig.get("aai.rsync.options.list"); - String enableRsync = AAIConfig.get("aai.rsync.enabled"); - - if (!AAIConfig.isEmpty(enableRsync) && "n".equalsIgnoreCase(enableRsync)){ - LOGGER.info("rsync not invoked for " + fileName + ": rsync is not enabled in aaiconfig.properties"); - return; - } - } catch ( Exception e ) { - LOGGER.warn( "rsync not invoked: missing aaiconfig.properties entries for rsync" ); - } - - LOGGER.info("rsync to copy files started...."); - - ArrayList remoteHostList = new ArrayList(); - StringTokenizer serverList = new StringTokenizer( aaiServerList, "|" ); - String host = null; - try { - host = getHost(); - String remoteConnString = null; - - remoteHostList = getRemoteHostList(serverList, host); - LOGGER.debug("This host:" + host); - String pickUpDirectory = AAIConfig.get("instar.pickup.dir"); - String user = AAIConfig.get("aai.rsync.remote.user"); - String rsyncCmd = AAIConfig.get("aai.rsync.command"); - - //Push: rsync [OPTION...] SRC... [USER@]HOST:DEST - - java.util.Iterator remoteHostItr = remoteHostList.iterator(); - while (!remoteHostList.isEmpty() && remoteHostItr.hasNext()) { - String remoteHost = remoteHostItr.next(); - remoteConnString =user+"@"+remoteHost+":"+pickUpDirectory; - - List commands = new ArrayList(); - commands.add(rsyncCmd); - StringTokenizer optionTks = new StringTokenizer( rsyncOptionsList, "|" ); - while (optionTks.hasMoreTokens()){ - commands.add(optionTks.nextToken()); - } - commands.add(fileName); // src directory/fileName - commands.add(remoteConnString); // target username/host/path - LOGGER.debug("Commands: " + commands.toString()); - int rsyncResult = doCommand(commands); - if ( rsyncResult == 0 ) { - LOGGER.info("rsync completed for "+remoteHost); - }else { - LOGGER.error("rsync failed for "+ remoteHost+ " with response code "+rsyncResult ); - } - } - } catch ( Exception e) { - LOGGER.error("no server found processing serverList for host " + host + ": " + e.getMessage() + " (AAI_4000)"); - } - } - - /** - * Gets the remote host list. - * - * @param serverList the server list - * @param host the host - * @return the remote host list - */ - private ArrayList getRemoteHostList(StringTokenizer serverList, String host) { - ArrayList remoteHostList = new ArrayList(); - String remoteHost = null; - while ( serverList.hasMoreTokens() ) { - remoteHost = serverList.nextToken(); - if (!host.equalsIgnoreCase(remoteHost)){ - remoteHostList.add(remoteHost); - } - } - return remoteHostList; - } - - /** - * Gets the host. - * - * @return the host - * @throws AAIException the AAI exception - */ - private String getHost() throws AAIException { - String aaiServerList = AAIConfig.get(DEFAULT_CHECK + "serverlist"); - String hostname = null; - try { - InetAddress ip = InetAddress.getLocalHost(); - if ( ip != null ) { - hostname = ip.getHostName(); - if ( hostname != null ) { - if ( !( aaiServerList.contains(hostname) ) ) - LOGGER.warn("Host name not found in server list " + hostname); - } else - LOGGER.warn("InetAddress returned null hostname"); - } - - } catch (UnknownHostException e) { - LOGGER.warn("InetAddress getLocalHost exception " + e.getMessage()); - } - - return hostname; - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/util/Entity.java b/aai-core/src/main/java/org/openecomp/aai/util/Entity.java deleted file mode 100644 index c1324043..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/util/Entity.java +++ /dev/null @@ -1,196 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.util; - -import 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 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" -}) -public class Entity { - - @JsonProperty("equipment-role") - private String equipmentRole; - @JsonProperty("action") - private String action; - @JsonProperty("key-value-list") - private List keyValueList = new ArrayList(); - @JsonProperty("self-link") - private String selfLink; - @JsonIgnore - private Map additionalProperties = new HashMap(); - - /** - * - * @return - * The equipmentRole - */ - @JsonProperty("equipment-role") - public String getEquipmentRole() { - return equipmentRole; - } - - /** - * - * @param equipmentRole - * The equipment-role - */ - @JsonProperty("equipment-role") - public void setEquipmentRole(String equipmentRole) { - this.equipmentRole = equipmentRole; - } - - public Entity withEquipmentRole(String equipmentRole) { - this.equipmentRole = equipmentRole; - return this; - } - - /** - * - * @return - * The action - */ - @JsonProperty("action") - public String getAction() { - return action; - } - - /** - * - * @param action - * The action - */ - @JsonProperty("action") - public void setAction(String action) { - this.action = action; - } - - public Entity withAction(String action) { - this.action = action; - return this; - } - - /** - * - * @return - * The keyValueList - */ - @JsonProperty("key-value-list") - public List getKeyValueList() { - return keyValueList; - } - - /** - * - * @param keyValueList - * The key-value-list - */ - @JsonProperty("key-value-list") - public void setKeyValueList(List keyValueList) { - this.keyValueList = keyValueList; - } - - public Entity withKeyValueList(List keyValueList) { - this.keyValueList = keyValueList; - return this; - } - - /** - * - * @return - * The selfLink - */ - @JsonProperty("self-link") - public String getSelfLink() { - return selfLink; - } - - /** - * - * @param selfLink - * The self-link - */ - @JsonProperty("self-link") - public void setSelfLink(String selfLink) { - this.selfLink = selfLink; - } - - public Entity withSelfLink(String selfLink) { - this.selfLink = selfLink; - return this; - } - - @Override - public String toString() { - return ToStringBuilder.reflectionToString(this); - } - - @JsonAnyGetter - public Map getAdditionalProperties() { - return this.additionalProperties; - } - - @JsonAnySetter - public void setAdditionalProperty(String name, Object value) { - this.additionalProperties.put(name, value); - } - - public Entity withAdditionalProperty(String name, Object value) { - this.additionalProperties.put(name, value); - return this; - } - - @Override - public int hashCode() { - return new HashCodeBuilder().append(equipmentRole).append(action).append(keyValueList).append(selfLink).append(additionalProperties).toHashCode(); - } - - @Override - public boolean equals(Object other) { - if (other == this) { - return true; - } - if ((other instanceof Entity) == false) { - 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(); - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/util/EntityList.java b/aai-core/src/main/java/org/openecomp/aai/util/EntityList.java deleted file mode 100644 index 6bf06054..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/util/EntityList.java +++ /dev/null @@ -1,112 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.util; - -import 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 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" -}) -public class EntityList { - - @JsonProperty("entity") - private List entity = new ArrayList(); - @JsonIgnore - private Map additionalProperties = new HashMap(); - - /** - * - * @return - * The entity - */ - @JsonProperty("entity") - public List getEntity() { - return entity; - } - - /** - * - * @param entity - * The entity - */ - @JsonProperty("entity") - public void setEntity(List entity) { - this.entity = entity; - } - - public EntityList withEntity(List entity) { - this.entity = entity; - return this; - } - - @Override - public String toString() { - return ToStringBuilder.reflectionToString(this); - } - - @JsonAnyGetter - public Map getAdditionalProperties() { - return this.additionalProperties; - } - - @JsonAnySetter - public void setAdditionalProperty(String name, Object value) { - this.additionalProperties.put(name, value); - } - - public EntityList withAdditionalProperty(String name, Object value) { - this.additionalProperties.put(name, value); - return this; - } - - @Override - public int hashCode() { - return new HashCodeBuilder().append(entity).append(additionalProperties).toHashCode(); - } - - @Override - public boolean equals(Object other) { - if (other == this) { - return true; - } - if ((other instanceof EntityList) == false) { - return false; - } - EntityList rhs = ((EntityList) other); - return new EqualsBuilder().append(entity, rhs.entity).append(additionalProperties, rhs.additionalProperties).isEquals(); - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/util/FileWatcher.java b/aai-core/src/main/java/org/openecomp/aai/util/FileWatcher.java deleted file mode 100644 index 84e7a1a3..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/util/FileWatcher.java +++ /dev/null @@ -1,59 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.util; - -import java.util.*; -import java.io.*; - -public abstract class FileWatcher extends TimerTask { - 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(); - } - - /** - * runs a timer task - * @see java.util.TimerTask.run - */ - public final void run() { - long timeStamp = file.lastModified(); - - if( (timeStamp - this.timeStamp) > 500 ) { - this.timeStamp = timeStamp; - onChange(file); - } - } - - /** - * On change. - * - * @param file the file - */ - protected abstract void onChange( File file ); -} diff --git a/aai-core/src/main/java/org/openecomp/aai/util/FormatDate.java b/aai-core/src/main/java/org/openecomp/aai/util/FormatDate.java deleted file mode 100644 index d1489992..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/util/FormatDate.java +++ /dev/null @@ -1,46 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.util; - -import java.time.ZoneId; -import java.time.ZonedDateTime; -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))); - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/util/GenerateXsd.java b/aai-core/src/main/java/org/openecomp/aai/util/GenerateXsd.java deleted file mode 100644 index 15ea8a32..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/util/GenerateXsd.java +++ /dev/null @@ -1,1697 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.util; - -import com.google.common.base.Joiner; -import com.jayway.jsonpath.JsonPath; -import org.openecomp.aai.introspection.Version; -import org.openecomp.aai.serialization.db.EdgeProperty; -import org.w3c.dom.*; - -import javax.xml.XMLConstants; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.xpath.*; -import java.io.*; -import java.nio.charset.Charset; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.*; - - - -public class GenerateXsd { - - static String apiVersion = null; - static String apiVersionFmt = null; - static boolean useAnnotationsInXsd = false; - static String responsesUrl = null; - static String responsesLabel = null; - static String jsonEdges = null; - - static Map generatedJavaType; - static Map appliedPaths; - static NodeList javaTypeNodes; - - - public static final int VALUE_NONE = 0; - public static final int VALUE_DESCRIPTION = 1; - public static final int VALUE_INDEXED_PROPS = 2; - - private static final String generateTypeXSD = "xsd"; - private static final String generateTypeYAML = "yaml"; - - private static final String root = "../aai-schema/src/main/resources"; - private static final String xsd_dir = root + "/aai_schema"; - private static final String yaml_dir = root + "/aai_swagger_yaml"; - - private static int annotationsStartVersion = 9; // minimum version to support annotations in xsd - private static int swaggerSupportStartsVersion = 7; // minimum version to support swagger documentation - - private static XPath xpath = XPathFactory.newInstance().newXPath(); - - - private enum LineageType { - PARENT, CHILD, UNRELATED; - } - private class EdgeDescription { - - private String ruleKey; - private LineageType type = LineageType.UNRELATED; - private String direction; - private String multiplicity; - private boolean hasDelTarget = false; - - public String getRuleKey() { - return ruleKey; - } - public String getMultiplicity() { - return multiplicity; - } - public String getDirection() { - return direction; - } - public void setRuleKey(String val) { - this.ruleKey=val; - } - public void setType(LineageType val) { - this.type=val; - } - public void setDirection(String val) { - this.direction = val; - } - public void setMultiplicity(String val) { - this.multiplicity=val; - } - public void setHasDelTarget(String val) { - hasDelTarget = Boolean.parseBoolean(val); - } - - public String getRelationshipDescription(String fromTo, String otherNodeName) { - - String result = ""; - - if ("FROM".equals(fromTo)) { - if ("OUT".equals(direction)) { - if (LineageType.PARENT == type) { - result = " (is composed of "+otherNodeName; - } - } - else { - if (LineageType.CHILD == type) { - result = " (comprises "+otherNodeName; - } - else if (LineageType.PARENT == type) { - result = " (comprises "+otherNodeName; - } - } - } else { - if ("OUT".equals(direction)) { - if (LineageType.PARENT == type) { - result = " (comprises "+otherNodeName; - } - } else { - if (LineageType.PARENT == type) { - result = " (is composed of "+otherNodeName; - } - } - } - -// if (type != null) { -// if (LineageType.PARENT.equals(type) && "FROM".equals(fromTo)) { -// if ("OUT".equals(direction)) { -// result = " (is composed of "+otherNodeName; -// } else { -// result = " (comprises "+otherNodeName; -// } -// } else { -// result = " (comprises " + otherNodeName; -// // if (!(multiplicity.startsWith("One"))) { -// // System.err.println("Surprised to find multiplicity "+multiplicity+" with comprises for "+ruleKey); -// // } -// } -// } - if ("TO".equals(fromTo)) { - if (result.length() == 0) result = result + " ("; - else result = result + ", "; - - result = result + mapMultiplicity(fromTo); - if (hasDelTarget) result = result + ", will delete target node"; - } - - if (result.length() > 0) result = result + ")"; - - return result; - } - - private String mapMultiplicity(String fromTo) { - String result = multiplicity; -// Below logic works if an IN switches multiplicity, which it doesn't today. -// if ("TO".equals(fromTo)) { -// if (direction.equals("OUT")) { -// result = multiplicity; -// } else { -// result = switchMultiplicity(multiplicity); -// } -// } else { -// if (direction.equals("OUT")) { -// result = multiplicity; -// } else { -// result = switchMultiplicity(multiplicity); -// } -// } - return result; - } - -// private String switchMultiplicity(String val) throws IllegalArgumentException -// { -// String result = null; -// switch (val) { -// case "Many2Many": -// case "One2One": -// result = val; -// break; -// case "Many2One": -// result = "One2Many"; -// break; -// case "One2Many": -// result = "Many2One"; -// break; -// default: -// throw new IllegalArgumentException("Multiplicity cannot be "+val); -// } -// System.out.println("Switched Multiplicity from "+val+" to "+result); -// return result; -// } - } - - private static boolean validVersion(String versionToGen) { - - if ("ALL".equalsIgnoreCase(versionToGen)) { - return true; - } - - for (Version v : Version.values()) { - if (v.name().equals(versionToGen)) { - return true; - } - } - - return false; - } - - private static boolean versionUsesAnnotations( String version) { - if (new Integer(version.substring(1)).intValue() >= annotationsStartVersion ) { - return true; - } - return false; - } - - private static boolean versionSupportsSwagger( String version) { - if (new Integer(version.substring(1)).intValue() >= swaggerSupportStartsVersion ) { - return true; - } - return false; - } - - public static void main(String[] args) throws IOException { - String versionToGen = System.getProperty("gen_version").toLowerCase(); - String fileTypeToGen = System.getProperty("gen_type").toLowerCase(); - if ( fileTypeToGen == null ) { - fileTypeToGen = generateTypeXSD; - } - - if ( !fileTypeToGen.equals( generateTypeXSD ) && !fileTypeToGen.equals( generateTypeYAML )) { - System.err.println("Invalid gen_type passed. " + fileTypeToGen); - System.exit(1); - } - - - if ( versionToGen == null ) { - System.err.println("Version is required, ie v or ALL."); - System.exit(1); - } - - responsesUrl = System.getProperty("yamlresponses_url"); - String responsesLabel = System.getProperty("yamlresponses_label"); - List versionsToGen = new ArrayList<>(); - - - if (!"ALL".equalsIgnoreCase(versionToGen) && !versionToGen.matches("v\\d+") && !validVersion(versionToGen)) { - System.err.println("Invalid version passed. " + versionToGen); - System.exit(1); - } - - if ("ALL".equalsIgnoreCase(versionToGen)) { - versionsToGen = Arrays.asList(Version.values()); - Collections.sort(versionsToGen); - Collections.reverse(versionsToGen); - } else { - versionsToGen.add(Version.valueOf(versionToGen)); - } - - if ( fileTypeToGen.equals(generateTypeYAML) ) { - if ( responsesUrl == null || responsesUrl.length() < 1 - || responsesLabel == null || responsesLabel.length() < 1 ) { - System.err.println("generating swagger yaml file requires yamlresponses_url and yamlresponses_label properties" ); - System.exit(1); - } - responsesUrl = "description: "+ responsesLabel+ "(" + responsesUrl + ").\n"; - } - String oxmPath = root + "/oxm/"; - - String outfileName; - File outfile; - String fileContent; - - for (Version v : versionsToGen) { - apiVersion = v.toString(); - System.out.println("Generating " + apiVersion + " " + fileTypeToGen); - File oxm_file = new File(oxmPath + "aai_oxm_" + apiVersion + ".xml"); - apiVersionFmt = "." + apiVersion + "."; - generatedJavaType = new HashMap(); - appliedPaths = new HashMap(); - if ( fileTypeToGen.equals(generateTypeXSD) ) { - useAnnotationsInXsd = versionUsesAnnotations(apiVersion); - outfileName = xsd_dir + "/aai_schema_" + apiVersion + "." + generateTypeXSD; - fileContent = processOxmFile(oxm_file, v); - } else if ( versionSupportsSwagger(apiVersion )) { - outfileName = yaml_dir + "/aai_swagger_" + apiVersion + "." + generateTypeYAML; - fileContent = generateSwaggerFromOxmFile( oxm_file); - } else { - continue; - } - outfile = new File(outfileName); - File parentDir = outfile.getParentFile(); - if(! parentDir.exists()) - parentDir.mkdirs(); - - try { - outfile.createNewFile(); - } catch (IOException e) { - System.out.println( "Exception creating output file " + outfileName); - e.printStackTrace(); - } - BufferedWriter bw = null; - try { - Charset charset = Charset.forName("UTF-8"); - Path path = Paths.get(outfileName); - bw = Files.newBufferedWriter(path, charset); - bw.write(fileContent); - } catch ( IOException e) { - System.out.println( "Exception writing output file " + outfileName); - e.printStackTrace(); - } finally { - if ( bw != null ) { - bw.close(); - } - } - System.out.println( "GeneratedXSD successful, saved in " + outfileName); - } - - } - - - public static String processJavaTypeElement( String javaTypeName, Element javaTypeElement) { - - String xmlRootElementName = null; - - NodeList parentNodes = javaTypeElement.getElementsByTagName("java-attributes"); - StringBuffer sb = new StringBuffer(); - if ( parentNodes.getLength() == 0 ) { - //System.out.println( "no java-attributes for java-type " + javaTypeName); - return ""; - - } - - NamedNodeMap attributes; - - NodeList valNodes = javaTypeElement.getElementsByTagName("xml-root-element"); - Element valElement = (Element) valNodes.item(0); - attributes = valElement.getAttributes(); - for ( int i = 0; i < attributes.getLength(); ++i ) { - Attr attr = (Attr) attributes.item(i); - String attrName = attr.getNodeName(); - - String attrValue = attr.getNodeValue(); - //System.out.println("Found xml-root-element attribute: " + attrName + " with value: " + attrValue); - if ( attrName.equals("name")) - xmlRootElementName = attrValue; - } - /* - if ( javaTypeName.equals("RelationshipList")) { - System.out.println( "Skipping " + javaTypeName); - generatedJavaType.put(javaTypeName, null); - return ""; - } - */ - - Element parentElement = (Element)parentNodes.item(0); - NodeList xmlElementNodes = parentElement.getElementsByTagName("xml-element"); - NodeList childNodes; - Element childElement; - String xmlElementWrapper; - - Element xmlElementElement; - String addType; - String elementName, elementType, elementIsKey, elementIsRequired, elementContainerType; - StringBuffer sb1 = new StringBuffer(); - if ( xmlElementNodes.getLength() > 0 ) { - sb1.append(" \n"); - sb1.append(" \n"); - NodeList properties = GenerateXsd.locateXmlProperties(javaTypeElement); - if (properties != null && useAnnotationsInXsd) { - //System.out.println("properties found for: " + xmlRootElementName); - sb1.append(" \r\n"); - insertAnnotation(properties, false, "class", sb1, " "); - - sb1.append(" \r\n"); - } /*else { - System.out.println("no properties found for: " + xmlRootElementName); - }*/ - sb1.append(" \n"); - for ( int i = 0; i < xmlElementNodes.getLength(); ++i ) { - - xmlElementElement = (Element)xmlElementNodes.item(i); - childNodes = xmlElementElement.getElementsByTagName("xml-element-wrapper"); - - xmlElementWrapper = null; - if ( childNodes.getLength() > 0 ) { - childElement = (Element)childNodes.item(0); - // get name - attributes = childElement.getAttributes(); - for ( int k = 0; k < attributes.getLength(); ++k ) { - Attr attr = (Attr) attributes.item(k); - String attrName = attr.getNodeName(); - String attrValue = attr.getNodeValue(); - if ( attrName.equals("name")) { - xmlElementWrapper = attrValue; - //System.out.println("found xml-element-wrapper " + xmlElementWrapper); - } - } - - } - attributes = xmlElementElement.getAttributes(); - addType = null; - - - elementName = elementType = elementIsKey = elementIsRequired = elementContainerType = null; - for ( int j = 0; j < attributes.getLength(); ++j ) { - Attr attr = (Attr) attributes.item(j); - String attrName = attr.getNodeName(); - - String attrValue = attr.getNodeValue(); - //System.out.println("For " + xmlRootElementName + " Found xml-element attribute: " + attrName + " with value: " + attrValue); - if ( attrName.equals("name")) { - elementName = attrValue; - } - if ( attrName.equals("type")) { - elementType = attrValue; - if ( attrValue.contains(apiVersionFmt) ) { - addType = attrValue.substring(attrValue.lastIndexOf('.')+1); - if ( !generatedJavaType.containsKey(addType) ) { - generatedJavaType.put(addType, attrValue); - sb.append(processJavaTypeElement( addType, getJavaTypeElement(addType) )); - } - } - - } - - if ( attrName.equals("xml-key")) { - elementIsKey = attrValue; - } - if ( attrName.equals("required")) { - elementIsRequired = attrValue; - } - if ( attrName.equals("container-type")) { - elementContainerType = attrValue; - } - } - - if ( xmlElementWrapper != null ) { - sb1.append(" \n"); - sb1.append(" \n"); - properties = GenerateXsd.locateXmlProperties(javaTypeElement); - if (properties != null && useAnnotationsInXsd) { - sb1.append(" \r\n"); - insertAnnotation(properties, false, "class", sb1, " "); - sb1.append(" \r\n"); - } /*else { - System.out.println("no properties found for: " + xmlElementWrapper); - }*/ - sb1.append(" \n"); - sb1.append(" "); - } - if ("Nodes".equals(addType)) { - //System.out.println ("Skipping nodes, temporary testing"); - continue; - } - if ( addType != null ) { - //sb1.append(" \n"); - if ( useAnnotationsInXsd ) { - sb1.append(" \r\n"); - insertAnnotation(properties, elementIsKey != null, "field", sb1, " "); - sb1.append(" \r\n"); - } - if (xmlElementWrapper== null) { - sb1.append(" \n"); - } - } else { - sb1.append("/>\n"); - } - if ( xmlElementWrapper != null ) { - sb1.append(" \n"); - sb1.append(" \n"); - sb1.append(" \n"); - } - } - /* - if ( xmlRootElementName.equals("notify") || - xmlRootElementName.equals("relationship") || - xmlRootElementName.equals("relationship-data") || - xmlRootElementName.equals("related-to-property") ) - - sb1.append(" \n"); - */ - sb1.append(" \n"); - sb1.append(" \n"); - sb1.append(" \n"); - } - /* - NodeList valNodes = javaTypeElement.getElementsByTagName("xml-root-element"); - Element valElement = (Element) valNodes.item(0); - attributes = valElement.getAttributes(); - for ( int i = 0; i < attributes.getLength(); ++i ) { - Attr attr = (Attr) attributes.item(i); - String attrName = attr.getNodeName(); - - String attrValue = attr.getNodeValue(); - System.out.println("Found xml-root-element attribute: " + attrName + " with value: " + attrValue); - if ( attrValue.equals("name")) - xmlRootElementName = attrValue; - } - */ - - if ( xmlElementNodes.getLength() < 1 ) { - sb.append(" \n"); - sb.append(" \n"); - sb.append(" \n"); - sb.append(" \n"); - sb.append(" \n"); - generatedJavaType.put(javaTypeName, null); - return sb.toString(); - } - - sb.append( sb1 ); - - return sb.toString(); - } - - private static void insertAnnotation(NodeList items, boolean isKey, String target, StringBuffer sb1, String indentation) { - if (items != null || isKey) { - List metadata = new ArrayList<>(); - - String name = ""; - String value = ""; - Element item = null; - if (isKey) { - metadata.add("isKey=true"); - } - if (items != null) { - for (int i = 0; i < items.getLength(); i++) { - item = (Element)items.item(i); - name = item.getAttribute("name"); - value = item.getAttribute("value"); - if (name.equals("abstract")) { - name = "isAbstract"; - } else if (name.equals("extends")) { - name = "extendsFrom"; - } - metadata.add(name + "=\"" + value.replaceAll("&", "&") + "\""); - //System.out.println("property name: " + name); - - } - } - sb1.append( - indentation + " \r\n" + - indentation + " @org.openecomp.aai.annotations.Metadata(" + Joiner.on(",").join(metadata) + ")\r\n" + - indentation + " \r\n"); - } - - } - - private static Element getJavaTypeElement( String javaTypeName ) - { - - String attrName, attrValue; - Attr attr; - Element javaTypeElement; - for ( int i = 0; i < javaTypeNodes.getLength(); ++ i ) { - javaTypeElement = (Element) javaTypeNodes.item(i); - NamedNodeMap attributes = javaTypeElement.getAttributes(); - for ( int j = 0; j < attributes.getLength(); ++j ) { - attr = (Attr) attributes.item(j); - attrName = attr.getNodeName(); - attrValue = attr.getNodeValue(); - if ( attrName.equals("name") && attrValue.equals(javaTypeName)) - return javaTypeElement; - } - } - System.out.println( "oxm file format error, missing java-type " + javaTypeName); - return (Element) null; - } - - private static Element getJavaTypeElementSwagger( String javaTypeName ) - { - - String attrName, attrValue; - Attr attr; - Element javaTypeElement; - for ( int i = 0; i < javaTypeNodes.getLength(); ++ i ) { - javaTypeElement = (Element) javaTypeNodes.item(i); - NamedNodeMap attributes = javaTypeElement.getAttributes(); - for ( int j = 0; j < attributes.getLength(); ++j ) { - attr = (Attr) attributes.item(j); - attrName = attr.getNodeName(); - attrValue = attr.getNodeValue(); - if ( attrName.equals("name") && attrValue.equals(javaTypeName)) - return javaTypeElement; - } - } - System.out.println( "oxm file format error, missing java-type " + javaTypeName); - return (Element) null; - } - private static String getXmlRootElementName( String javaTypeName ) - { - - String attrName, attrValue; - Attr attr; - Element javaTypeElement; - for ( int i = 0; i < javaTypeNodes.getLength(); ++ i ) { - javaTypeElement = (Element) javaTypeNodes.item(i); - NamedNodeMap attributes = javaTypeElement.getAttributes(); - for ( int j = 0; j < attributes.getLength(); ++j ) { - attr = (Attr) attributes.item(j); - attrName = attr.getNodeName(); - attrValue = attr.getNodeValue(); - if ( attrName.equals("name") && attrValue.equals(javaTypeName)) { - NodeList valNodes = javaTypeElement.getElementsByTagName("xml-root-element"); - Element valElement = (Element) valNodes.item(0); - attributes = valElement.getAttributes(); - for ( int k = 0; k < attributes.getLength(); ++k ) { - attr = (Attr) attributes.item(k); - attrName = attr.getNodeName(); - - attrValue = attr.getNodeValue(); - //System.out.println("Found xml-root-element attribute: " + attrName + " with value: " + attrValue); - if ( attrName.equals("name")) - return (attrValue); - } - } - } - } - System.out.println( "oxm file format error, missing java-type " + javaTypeName); - return null; - } - - - public static String processOxmFile( File oxmFile, Version v ) - { - StringBuilder sb = new StringBuilder(); - sb.append("\n"); - String namespace = "org.openecomp"; - if ( useAnnotationsInXsd ) { - sb.append("\n\n"); - } else { - sb.append("\n\n"); - } - - try { - - DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); - dbFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); - DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); - Document doc = dBuilder.parse(oxmFile); - - NodeList bindingsNodes = doc.getElementsByTagName("xml-bindings"); - Element bindingElement; - NodeList javaTypesNodes; - Element javaTypesElement; - - Element javaTypeElement; - - - if ( bindingsNodes == null || bindingsNodes.getLength() == 0 ) { - System.out.println( "missing in " + oxmFile ); - return null; - } - - bindingElement = (Element) bindingsNodes.item(0); - javaTypesNodes = bindingElement.getElementsByTagName("java-types"); - if ( javaTypesNodes.getLength() < 1 ) { - System.out.println( "missing in " + oxmFile ); - return null; - } - javaTypesElement = (Element) javaTypesNodes.item(0); - javaTypeNodes = javaTypesElement.getElementsByTagName("java-type"); - if ( javaTypeNodes.getLength() < 1 ) { - System.out.println( "missing in " + oxmFile ); - return null; - } - - String javaTypeName; - String attrName, attrValue; - Attr attr; - for ( int i = 0; i < javaTypeNodes.getLength(); ++ i ) { - javaTypeElement = (Element) javaTypeNodes.item(i); - NamedNodeMap attributes = javaTypeElement.getAttributes(); - javaTypeName = null; - for ( int j = 0; j < attributes.getLength(); ++j ) { - attr = (Attr) attributes.item(j); - attrName = attr.getNodeName(); - attrValue = attr.getNodeValue(); - if ( attrName.equals("name")) - javaTypeName = attrValue; - } - if ( javaTypeName == null ) { - System.out.println( " has no name attribute in " + oxmFile ); - return null; - } - if ("Nodes".equals(javaTypeName)) { - //System.out.println("skipping Nodes entry (temporary feature)"); - continue; - } - if ( !generatedJavaType.containsKey(javaTypeName) ) { - generatedJavaType.put(javaTypeName, null); - sb.append(processJavaTypeElement( javaTypeName, javaTypeElement )); - } - } - - } catch (Exception e) { - e.printStackTrace(); - return null; - } - sb.append("\n"); - return sb.toString(); - } - - private static boolean isStandardType( String elementType ) - { - switch ( elementType ) { - case "java.lang.String": - case "java.lang.Long": - case "java.lang.Integer": - case"java.lang.Boolean": - return true; - } - return false; - } - - private static Vector getIndexedProps( String attrValue ) - { - if ( attrValue == null ) - return null; - StringTokenizer st = new StringTokenizer( attrValue, ","); - if ( st.countTokens() == 0 ) - return null; - Vector result = new Vector(); - while ( st.hasMoreTokens()) { - result.add(st.nextToken()); - } - return result; - } - - /** - * Guaranteed to at least return non null but empty collection of edge descriptions - * @param nodeName name of the vertex whose edge relationships to return - * @return collection of node neighbors based on DbEdgeRules - **/ - private static Collection getEdgeRulesFromJson( String path, boolean skipMatch ) - { - - ArrayList result = new ArrayList<>(); - Iterator> edgeRulesIterator; - try { - - GenerateXsd x = new GenerateXsd(); - - List> inEdges = JsonPath.parse(jsonEdges).read(path); - - edgeRulesIterator = inEdges.iterator(); - Map edgeMap; - String fromNode; - String toNode; - String ruleKey; - String direction; - String multiplicity; - String isParent; - String hasDelTarget; - EdgeDescription edgeDes; - - while( edgeRulesIterator.hasNext() ){ - edgeMap = edgeRulesIterator.next(); - fromNode = (String)edgeMap.get("from"); - toNode = (String)edgeMap.get("to"); - if ( skipMatch ) { - if ( fromNode.equals(toNode)) { - continue; - } - } - edgeDes = x.new EdgeDescription(); - edgeDes.setRuleKey(fromNode + "|" + toNode); - direction = (String)edgeMap.get("direction"); - edgeDes.setDirection(direction); - multiplicity = (String)edgeMap.get("multiplicity"); - edgeDes.setMultiplicity(multiplicity); - isParent = (String)edgeMap.get(EdgeProperty.CONTAINS.toString()); - if ( "${direction}".equals(isParent)) { - edgeDes.setType(LineageType.PARENT); - } else { - edgeDes.setType(LineageType.UNRELATED); - } - hasDelTarget = (String)edgeMap.get(EdgeProperty.DELETE_OTHER_V.toString()); - edgeDes.setHasDelTarget(hasDelTarget); - result.add(edgeDes); - - } - } catch (Exception ex) { - ex.printStackTrace(); - } - return result; - - } - - /** - * Guaranteed to at least return non null but empty collection of edge descriptions - * @param nodeName name of the vertex whose edge relationships to return - * @return collection of node neighbors based on DbEdgeRules - **/ - private static Collection getEdgeRules( String nodeName ) - { - String fromRulesPath = "$['rules'][?(@['from']=='" + nodeName + "')]"; - String toRulesPath = "$['rules'][?(@['to']=='" + nodeName + "')]"; - Collection fromEdges = getEdgeRulesFromJson( fromRulesPath, false ); - Collection edges = getEdgeRulesFromJson( toRulesPath, true ); - edges.addAll(fromEdges); - return edges; - } - - public static String processJavaTypeElementSwagger( String javaTypeName, Element javaTypeElement, - StringBuffer pathSb, StringBuffer definitionsSb, String path, String tag, String opId, - String getItemName, StringBuffer pathParams, String queryParams, String validEdges) { - - String xmlRootElementName = null; - - //Map addJavaType = new HashMap(); - String useTag = null; - String useOpId = null; - - if ( tag != null ) { - switch ( tag ) { - case "Network": - case "ServiceDesignAndCreation": - case "Business": - case "LicenseManagement": - case "CloudInfrastructure": - case "ExternalSystem": - break; - default: - return null; - } - } - /* - if ( path == null ) - System.out.println( "processJavaTypeElementSwagger called with null path for javaTypeName " + javaTypeName); - */ - /* - if ( path == null || !(path.contains("cloud-infrastructure"))) - switch ( javaTypeName) { - case "Inventory": - useTag = null; - break; - - case "CloudInfrastructure": - case "Search": - case "Actions": - case "ServiceDesignAndCreation": - case "LicenseManagement": - case "Network": - if ( tag == null ) - useTag = javaTypeName; - - break; - default: - return null; - - } - */ - - if ( !javaTypeName.equals("Inventory") ) { - if ( javaTypeName.equals("AaiInternal")) - return null; - if ( opId == null ) - useOpId = javaTypeName; - else - useOpId = opId + javaTypeName; - if ( tag == null ) - useTag = javaTypeName; - } - - /* - if ( javaTypeName.equals("GenericVnf")) - System.out.println( "Processing " + javaTypeName); - else if ( javaTypeName.equals("Service")) - System.out.println( "Processing " + javaTypeName); - else if ( javaTypeName.equals("SitePair")) - System.out.println( "Processing " + javaTypeName); - */ - NodeList parentNodes = javaTypeElement.getElementsByTagName("java-attributes"); - - if ( parentNodes.getLength() == 0 ) { - //System.out.println( "no java-attributes for java-type " + javaTypeName); - return ""; - - } - - NamedNodeMap attributes; - - NodeList valNodes = javaTypeElement.getElementsByTagName("xml-root-element"); - Element valElement = (Element) valNodes.item(0); - attributes = valElement.getAttributes(); - for ( int i = 0; i < attributes.getLength(); ++i ) { - Attr attr = (Attr) attributes.item(i); - String attrName = attr.getNodeName(); - - String attrValue = attr.getNodeValue(); - //System.out.println("Found xml-root-element attribute: " + attrName + " with value: " + attrValue); - if ( attrName.equals("name")) - xmlRootElementName = attrValue; - } - /* - if ( xmlRootElementName.equals("oam-networks")) - System.out.println( "xmlRootElement oam-networks with getItemData [" + getItemName + "]"); - */ - //already processed - /* - if ( generatedJavaType.containsKey(xmlRootElementName) ) { - return null; - } - */ - NodeList childNodes; - Element childElement; - NodeList xmlPropNodes = javaTypeElement.getElementsByTagName("xml-properties"); - Element xmlPropElement; - String pathDescriptionProperty = null; - - - Vector indexedProps = null; - - /*System.out.println( "javaTypeName " + javaTypeName + " has xml-properties length " + xmlPropNodes.getLength()); - if ( path != null && path.equals("/network/generic-vnfs")) - System.out.println("path is " + "/network/generic-vnfs with getItemName " + getItemName); - */ - if ( xmlPropNodes.getLength() > 0 ) { - - for ( int i = 0; i < xmlPropNodes.getLength(); ++i ) { - xmlPropElement = (Element)xmlPropNodes.item(i); - if ( !xmlPropElement.getParentNode().isSameNode(javaTypeElement)) - continue; - childNodes = xmlPropElement.getElementsByTagName("xml-property"); - - if ( childNodes.getLength() > 0 ) { - for ( int j = 0; j < childNodes.getLength(); ++j ) { - childElement = (Element)childNodes.item(j); - // get name - int useValue = VALUE_NONE; - attributes = childElement.getAttributes(); - for ( int k = 0; k < attributes.getLength(); ++k ) { - Attr attr = (Attr) attributes.item(k); - String attrName = attr.getNodeName(); - String attrValue = attr.getNodeValue(); - if ( attrName == null || attrValue == null ) - continue; - if ( attrName.equals("name") && attrValue.equals("description")) { - useValue = VALUE_DESCRIPTION; - } - if ( useValue == VALUE_DESCRIPTION && attrName.equals("value")) { - pathDescriptionProperty = attrValue; - //break; - //System.out.println("found xml-element-wrapper " + xmlElementWrapper); - } - if ( attrValue.equals("indexedProps")) { - useValue = VALUE_INDEXED_PROPS; - } - if ( useValue == VALUE_INDEXED_PROPS && attrName.equals("value")) { - indexedProps = getIndexedProps( attrValue ); - } - } - } - } - } - } - //System.out.println("javaTypeName " + javaTypeName + " description " + pathDescriptionProperty); - - /* - if ( javaTypeName.equals("RelationshipList")) { - System.out.println( "Skipping " + javaTypeName); - generatedJavaType.put(javaTypeName, null); - return ""; - } - */ - - Element parentElement = (Element)parentNodes.item(0); - NodeList xmlElementNodes = parentElement.getElementsByTagName("xml-element"); - - - String attrDescription = null; - - Element xmlElementElement; - String addType = null; - String elementType = null, elementIsKey = null, elementIsRequired, elementContainerType = null; - String elementName = null; - StringBuffer sbParameters = new StringBuffer(); - - StringBuffer sbRequired = new StringBuffer(); - int requiredCnt = 0; - int propertyCnt = 0; - StringBuffer sbProperties = new StringBuffer(); - StringBuffer sbIndexedParams = new StringBuffer(); - - - StringTokenizer st; - if ( xmlRootElementName.equals("inventory")) - path = ""; - else if ( path == null ) - //path = "/aai/" + apiVersion; - path = "/" + xmlRootElementName; - else - path += "/" + xmlRootElementName; - st = new StringTokenizer(path, "/"); - /* - if ( path.equals("/business/customers/customer/{global-customer-id}/service-subscriptions/service-subscription")) - System.out.println("processing path /business/customers/customer/{global-customer-id}/service-subscriptions with tag " + tag); - */ - boolean genPath = false; - /* - if ( path != null && path.equals("/network/generic-vnfs/generic-vnf")) - System.out.println("path is " + "/network/generic-vnfs/generic-vnf"); - */ - if ( st.countTokens() > 1 && getItemName == null ) { - if ( appliedPaths.containsKey(path)) - return null; - appliedPaths.put(path, null); - genPath = true; - if ( path.contains("/relationship/") ) { // filter paths with relationship-list - genPath = false; - } - if ( path.endsWith("/relationship-list")) { - genPath = false; - } - - } - - Vector addTypeV = null; - if ( xmlElementNodes.getLength() > 0 ) { - - for ( int i = 0; i < xmlElementNodes.getLength(); ++i ) { - xmlElementElement = (Element)xmlElementNodes.item(i); - if ( !xmlElementElement.getParentNode().isSameNode(parentElement)) - continue; - /*childNodes = xmlElementElement.getElementsByTagName("xml-element-wrapper"); - if ( childNodes.getLength() > 0 ) { - childElement = (Element)childNodes.item(0); - // get name - attributes = childElement.getAttributes(); - for ( int k = 0; k < attributes.getLength(); ++k ) { - Attr attr = (Attr) attributes.item(k); - String attrName = attr.getNodeName(); - String attrValue = attr.getNodeValue(); - if ( attrName.equals("name")) { - xmlElementWrapper = attrValue; - //System.out.println("found xml-element-wrapper " + xmlElementWrapper); - } - } - - } - */ - valNodes = xmlElementElement.getElementsByTagName("xml-properties"); - attrDescription = null; - if ( valNodes.getLength() > 0 ) { - for ( int j = 0; j < valNodes.getLength(); ++j ) { - valElement = (Element)valNodes.item(j); - if ( !valElement.getParentNode().isSameNode(xmlElementElement)) - continue; - childNodes = valElement.getElementsByTagName("xml-property"); - if ( childNodes.getLength() > 0 ) { - childElement = (Element)childNodes.item(0); - // get name - attributes = childElement.getAttributes(); - attrDescription = null; - boolean useValue = false; - for ( int k = 0; k < attributes.getLength(); ++k ) { - Attr attr = (Attr) attributes.item(k); - String attrName = attr.getNodeName(); - String attrValue = attr.getNodeValue(); - if ( attrName.equals("name") && attrValue.equals("description")) { - useValue = true; - } - if ( useValue && attrName.equals("value")) { - attrDescription = attrValue; - //System.out.println("found xml-element-wrapper " + xmlElementWrapper); - } - } - - } - } - } - - attributes = xmlElementElement.getAttributes(); - addTypeV = null; // vector of 1 - addType = null; - - elementName = elementType = elementIsKey = elementIsRequired = elementContainerType = null; - for ( int j = 0; j < attributes.getLength(); ++j ) { - Attr attr = (Attr) attributes.item(j); - String attrName = attr.getNodeName(); - - String attrValue = attr.getNodeValue(); - //System.out.println("For " + xmlRootElementName + " Found xml-element attribute: " + attrName + " with value: " + attrValue); - if ( attrName.equals("name")) { - elementName = attrValue; - - } - if ( attrName.equals("type") && getItemName == null ) { - elementType = attrValue; - if ( attrValue.contains(apiVersionFmt) ) { - addType = attrValue.substring(attrValue.lastIndexOf('.')+1); - if ( addTypeV == null ) - addTypeV = new Vector(); - addTypeV.add(addType); - } - - } - if ( attrName.equals("xml-key")) { - elementIsKey = attrValue; - path += "/{" + elementName + "}"; - } - if ( attrName.equals("required")) { - elementIsRequired = attrValue; - } - if ( attrName.equals("container-type")) { - elementContainerType = attrValue; - } - } - if ( getItemName != null ) { - if ( getItemName.equals("array") ) { - if ( elementContainerType != null && elementContainerType.equals("java.util.ArrayList")) { - //System.out.println( " returning array " + elementName ); - return elementName; - } - - } else { // not an array check - if ( elementContainerType == null || !elementContainerType.equals("java.util.ArrayList")) { - //System.out.println( " returning object " + elementName ); - return elementName; - } - - } - //System.out.println( " returning null" ); - return null; - } - if ( elementIsRequired != null ) { - if ( requiredCnt == 0 ) - sbRequired.append(" required:\n"); - ++requiredCnt; - if ( addTypeV != null ) { - for ( int k = 0; k < addTypeV.size(); ++i ) { - sbRequired.append(" - " + getXmlRootElementName(addTypeV.elementAt(k)) + ":\n"); - } - } else - sbRequired.append(" - " + elementName + "\n"); - - } - - if ( elementIsKey != null ) { - sbParameters.append((" - name: " + elementName + "\n")); - sbParameters.append((" in: path\n")); - if ( attrDescription != null && attrDescription.length() > 0 ) - sbParameters.append((" description: " + attrDescription + "\n")); - sbParameters.append((" required: true\n")); - if ( elementType.equals("java.lang.String")) - sbParameters.append(" type: string\n"); - if ( elementType.equals("java.lang.Long")) { - sbParameters.append(" type: integer\n"); - sbParameters.append(" format: int64\n"); - } - if ( elementType.equals("java.lang.Integer")) { - sbParameters.append(" type: integer\n"); - sbParameters.append(" format: int32\n"); - } - if ( elementType.equals("java.lang.Boolean")) - sbParameters.append(" type: boolean\n"); - - - } else if ( indexedProps != null - && indexedProps.contains(elementName ) ) { - sbIndexedParams.append((" - name: " + elementName + "\n")); - sbIndexedParams.append((" in: query\n")); - if ( attrDescription != null && attrDescription.length() > 0 ) - sbIndexedParams.append((" description: " + attrDescription + "\n")); - sbIndexedParams.append((" required: false\n")); - if ( elementType.equals("java.lang.String")) - sbIndexedParams.append(" type: string\n"); - if ( elementType.equals("java.lang.Long")) { - sbIndexedParams.append(" type: integer\n"); - sbIndexedParams.append(" format: int64\n"); - } - if ( elementType.equals("java.lang.Integer")) { - sbIndexedParams.append(" type: integer\n"); - sbIndexedParams.append(" format: int32\n"); - } - if ( elementType.equals("java.lang.Boolean")) - sbIndexedParams.append(" type: boolean\n"); - } - - /* - if ( elementName != null && elementName.equals("inventory-item")) - System.out.println( "processing inventory-item elementName"); - */ - - if ( isStandardType(elementType)) { - sbProperties.append(" " + elementName + ":\n"); - ++propertyCnt; - sbProperties.append(" type: "); - - if ( elementType.equals("java.lang.String")) - sbProperties.append("string\n"); - else if ( elementType.equals("java.lang.Long")) { - sbProperties.append("integer\n"); - sbProperties.append(" format: int64\n"); - } - else if ( elementType.equals("java.lang.Integer")){ - sbProperties.append("integer\n"); - sbProperties.append(" format: int32\n"); - } - else if ( elementType.equals("java.lang.Boolean")) - sbProperties.append("boolean\n"); - if ( attrDescription != null && attrDescription.length() > 0 ) - sbProperties.append(" description: " + attrDescription + "\n"); - } - - //if ( addType != null && elementContainerType != null && elementContainerType.equals("java.util.ArrayList") ) { - - if ( addTypeV != null ) { - StringBuffer newPathParams = null; - if ( pathParams != null ) { - newPathParams = new StringBuffer(); - newPathParams.append(pathParams); - } - if ( sbParameters.toString().length() > 0 ) { - if ( newPathParams == null ) - newPathParams = new StringBuffer(); - newPathParams.append(sbParameters); - } - String newQueryParams = null; - if ( sbIndexedParams.toString().length() > 0 ) { - if ( queryParams == null ) - newQueryParams = sbIndexedParams.toString(); - else - newQueryParams = queryParams + sbIndexedParams.toString(); - } else { - newQueryParams = queryParams; - } - for ( int k = 0; k < addTypeV.size(); ++k ) { - addType = addTypeV.elementAt(k); - - if ( opId == null || !opId.contains(addType)) { - processJavaTypeElementSwagger( addType, getJavaTypeElementSwagger(addType), - pathSb, definitionsSb, path, tag == null ? useTag : tag, useOpId, null, - newPathParams, newQueryParams, validEdges); - } - // need item name of array - String itemName = processJavaTypeElementSwagger( addType, getJavaTypeElementSwagger(addType), - pathSb, definitionsSb, path, tag == null ? useTag : tag, useOpId, - "array", null, null, null ); - - if ( itemName != null ) { - if ( addType.equals("AaiInternal") ) { - //System.out.println( "addType AaiInternal, skip properties"); - - } else if ( getItemName == null) { - ++propertyCnt; - sbProperties.append(" " + getXmlRootElementName(addType) + ":\n"); - sbProperties.append(" type: array\n items:\n"); - sbProperties.append(" $ref: \"#/definitions/" + itemName + "\"\n"); - if ( attrDescription != null && attrDescription.length() > 0 ) - sbProperties.append(" description: " + attrDescription + "\n"); - } - } else { - /*itemName = processJavaTypeElementSwagger( addType, getJavaTypeElementSwagger(addType), - pathSb, definitionsSb, path, tag == null ? useTag : tag, useOpId, "other" ); - if ( itemName != null ) { - */ - if ( elementContainerType != null && elementContainerType.equals("java.util.ArrayList")) { - // need properties for getXmlRootElementName(addType) - newPathParams = null; - if ( pathParams != null ) { - newPathParams = new StringBuffer(); - newPathParams.append(pathParams); - } - if ( sbParameters.toString().length() > 0 ) { - if ( newPathParams == null ) - newPathParams = new StringBuffer(); - newPathParams.append(sbParameters); - } - newQueryParams = null; - if ( sbIndexedParams.toString().length() > 0 ) { - if ( queryParams == null ) - newQueryParams = sbIndexedParams.toString(); - else - newQueryParams = queryParams + sbIndexedParams.toString(); - } else { - newQueryParams = queryParams; - } - processJavaTypeElementSwagger( addType, getJavaTypeElementSwagger(addType), - pathSb, definitionsSb, path, tag == null ? useTag : tag, useOpId, - null, newPathParams, newQueryParams, validEdges ); - sbProperties.append(" " + getXmlRootElementName(addType) + ":\n"); - sbProperties.append(" type: array\n items: \n"); - sbProperties.append(" $ref: \"#/definitions/" + getXmlRootElementName(addType) + "\"\n"); - } else { - sbProperties.append(" " + getXmlRootElementName(addType) + ":\n"); - sbProperties.append(" type: object\n"); - sbProperties.append(" $ref: \"#/definitions/" + getXmlRootElementName(addType) + "\"\n"); - } - if ( attrDescription != null && attrDescription.length() > 0 ) - sbProperties.append(" description: " + attrDescription + "\n"); - ++propertyCnt; - /*} - else { - System.out.println(" unable to define swagger object for " + addType); - } - */ - } - //if ( getItemName == null) looking for missing properties - //generatedJavaType.put(addType, null); - } - } - } - } - if ( genPath ) { - /* - if ( useOpId.equals("CloudInfrastructureComplexesComplexCtagPools")) - System.out.println( "adding path CloudInfrastructureComplexesComplexCtagPools"); - */ - - if ( !path.endsWith("/relationship") ) { - pathSb.append(" " + path + ":\n" ); - pathSb.append(" get:\n"); - pathSb.append(" tags:\n"); - pathSb.append(" - " + tag + "\n"); - pathSb.append(" summary: returns " + xmlRootElementName + "\n"); - - pathSb.append(" description: returns " + xmlRootElementName + "\n"); - pathSb.append(" operationId: get" + useOpId + "\n"); - pathSb.append(" produces:\n"); - pathSb.append(" - application/json\n"); - pathSb.append(" - application/xml\n"); - - pathSb.append(" responses:\n"); - pathSb.append(" \"200\":\n"); - pathSb.append(" description: successful operation\n"); - pathSb.append(" schema:\n"); - pathSb.append(" $ref: \"#/definitions/" + xmlRootElementName + "\"\n"); - pathSb.append(" \"default\":\n"); - pathSb.append(" " + responsesUrl); - /* - pathSb.append(" \"200\":\n"); - pathSb.append(" description: successful operation\n"); - pathSb.append(" schema:\n"); - pathSb.append(" $ref: \"#/definitions/" + xmlRootElementName + "\"\n"); - pathSb.append(" \"404\":\n"); - pathSb.append(" description: resource was not found\n"); - pathSb.append(" \"400\":\n"); - pathSb.append(" description: bad request\n"); - */ - if ( path.indexOf('{') > 0 ) { - - if ( sbParameters.toString().length() > 0 ) { - if ( pathParams == null ) - pathParams = new StringBuffer(); - pathParams.append(sbParameters); - } - if ( pathParams != null) { - pathSb.append(" parameters:\n"); - pathSb.append(pathParams); - } else - System.out.println( "null pathParams for " + useOpId); - if ( sbIndexedParams.toString().length() > 0 ) { - if ( queryParams == null ) - queryParams = sbIndexedParams.toString(); - else - queryParams = queryParams + sbIndexedParams.toString(); - } - if ( queryParams != null ) { - if ( pathParams == null ) { - pathSb.append(" parameters:\n"); - } - pathSb.append(queryParams); - } - } - } - boolean skipPutDelete = false; // no put or delete for "all" - if ( !path.endsWith("/relationship") ) { - if ( !path.endsWith("}") ){ - skipPutDelete = true; - } - - } - if ( path.indexOf('{') > 0 && !opId.startsWith("Search") &&!skipPutDelete) { - // add PUT - if ( path.endsWith("/relationship") ) { - pathSb.append(" " + path + ":\n" ); - } - pathSb.append(" put:\n"); - pathSb.append(" tags:\n"); - pathSb.append(" - " + tag + "\n"); - - if ( path.endsWith("/relationship") ) { - pathSb.append(" summary: see node definition for valid relationships\n"); - } else { - pathSb.append(" summary: create or update an existing " + xmlRootElementName + "\n"); - pathSb.append(" description: create or update an existing " + xmlRootElementName + "\n"); - } - pathSb.append(" operationId: createOrUpdate" + useOpId + "\n"); - pathSb.append(" consumes:\n"); - pathSb.append(" - application/json\n"); - pathSb.append(" - application/xml\n"); - pathSb.append(" produces:\n"); - pathSb.append(" - application/json\n"); - pathSb.append(" - application/xml\n"); - pathSb.append(" responses:\n"); - pathSb.append(" \"default\":\n"); - pathSb.append(" " + responsesUrl); - /* - pathSb.append(" responses:\n"); - pathSb.append(" \"200\":\n"); - pathSb.append(" description: existing resource has been modified and there is a response buffer\n"); - pathSb.append(" \"201\":\n"); - pathSb.append(" description: new resource is created\n"); - pathSb.append(" \"202\":\n"); - pathSb.append(" description: action requested but may have taken other actions as well, which are returned in the response payload\n"); - pathSb.append(" \"204\":\n"); - pathSb.append(" description: existing resource has been modified and there is no response buffer\n"); - pathSb.append(" \"400\":\n"); - pathSb.append(" description: Bad Request will be returned if headers are missing\n"); - pathSb.append(" \"404\":\n"); - pathSb.append(" description: Not Found will be returned if an unknown URL is used\n"); - */ - pathSb.append(" parameters:\n"); - //pathSb.append(" - in: path\n"); - pathSb.append(pathParams); // for nesting - pathSb.append(" - name: body\n"); - pathSb.append(" in: body\n"); - pathSb.append(" description: " + xmlRootElementName + " object that needs to be created or updated\n"); - pathSb.append(" required: true\n"); - pathSb.append(" schema:\n"); - pathSb.append(" $ref: \"#/definitions/" + xmlRootElementName + "\"\n"); - /* - if ( queryParams != null ) { - pathSb.append(queryParams); - } - */ - // add DELETE - pathSb.append(" delete:\n"); - pathSb.append(" tags:\n"); - pathSb.append(" - " + tag + "\n"); - pathSb.append(" summary: delete an existing " + xmlRootElementName + "\n"); - - pathSb.append(" description: delete an existing " + xmlRootElementName + "\n"); - - pathSb.append(" operationId: delete" + useOpId + "\n"); - pathSb.append(" consumes:\n"); - pathSb.append(" - application/json\n"); - pathSb.append(" - application/xml\n"); - pathSb.append(" produces:\n"); - pathSb.append(" - application/json\n"); - pathSb.append(" - application/xml\n"); - pathSb.append(" responses:\n"); - pathSb.append(" \"default\":\n"); - pathSb.append(" " + responsesUrl); - /* - pathSb.append(" responses:\n"); - pathSb.append(" \"200\":\n"); - pathSb.append(" description: successful, the response includes an entity describing the status\n"); - pathSb.append(" \"204\":\n"); - pathSb.append(" description: successful, action has been enacted but the response does not include an entity\n"); - pathSb.append(" \"400\":\n"); - pathSb.append(" description: Bad Request will be returned if headers are missing\n"); - pathSb.append(" \"404\":\n"); - pathSb.append(" description: Not Found will be returned if an unknown URL is used\n"); - */ - pathSb.append(" parameters:\n"); - //pathSb.append(" - in: path\n"); - pathSb.append(pathParams); // for nesting - if ( !path.endsWith("/relationship") ) { - pathSb.append(" - name: resource-version\n"); - - pathSb.append(" in: query\n"); - pathSb.append(" description: resource-version for concurrency\n"); - pathSb.append(" required: true\n"); - pathSb.append(" type: string\n"); - } - /* - if ( queryParams != null ) { - pathSb.append(queryParams); - } - */ - } - - } - if ( generatedJavaType.containsKey(xmlRootElementName) ) { - return null; - } - - definitionsSb.append(" " + xmlRootElementName + ":\n"); - Collection edges = getEdgeRules(xmlRootElementName ); - if ( edges.size() > 0 ) { - StringBuffer sbEdge = new StringBuffer(); - sbEdge.append(" ###### Related Nodes\n"); - for (EdgeDescription ed : edges) { - if ( ed.getRuleKey().startsWith(xmlRootElementName)) { - sbEdge.append(" - TO ").append(ed.getRuleKey().substring(ed.getRuleKey().indexOf("|")+1)); - sbEdge.append(ed.getRelationshipDescription("TO", xmlRootElementName)); - sbEdge.append("\n"); - } - } - for (EdgeDescription ed : edges) { - if ( ed.getRuleKey().endsWith(xmlRootElementName)) { - sbEdge.append(" - FROM ").append(ed.getRuleKey().substring(0, ed.getRuleKey().indexOf("|"))); - sbEdge.append(ed.getRelationshipDescription("FROM", xmlRootElementName)); - sbEdge.append("\n"); - } - } - validEdges = sbEdge.toString(); - } - - // Handle description property. Might have a description OR valid edges OR both OR neither. - // Only put a description: tag if there is at least one. - if (pathDescriptionProperty != null || validEdges != null) { - definitionsSb.append(" description: |\n"); - - if ( pathDescriptionProperty != null ) - definitionsSb.append(" " + pathDescriptionProperty + "\n" ); - if (validEdges != null) - definitionsSb.append(validEdges); - } - - if ( requiredCnt > 0 ) - definitionsSb.append(sbRequired); - if ( propertyCnt > 0 ) { - definitionsSb.append(" properties:\n"); - definitionsSb.append(sbProperties); - } - generatedJavaType.put(xmlRootElementName, null); - return null; - } - - public static String generateSwaggerFromOxmFile( File oxmFile ) - { - - StringBuffer sb = new StringBuffer(); - sb.append("swagger: \"2.0\"\ninfo:\n description: |\n Copyright © 2017 AT&T Intellectual Property. All rights reserved.\n\n Licensed under the Creative Commons License, Attribution 4.0 Intl. (the "License"); you may not use this documentation except in compliance with the License.\n\n You may obtain a copy of the License at\n\n (https://creativecommons.org/licenses/by/4.0/)\n\n 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.\n\n ECOMP and OpenECOMP are trademarks and service marks of AT&T Intellectual Property.\n\n This document is best viewed with Firefox or Chrome. Nodes can be found by appending /#/definitions/node-type-to-find to the path to this document. Edge definitions can be found with the node definitions.\n version: \"" + apiVersion +"\"\n"); - sb.append(" title: Active and Available Inventory REST API\n"); - sb.append(" license:\n name: Apache 2.0\n url: http://www.apache.org/licenses/LICENSE-2.0.html\n"); - sb.append(" contact:\n name:\n url:\n email:\n"); - sb.append("host:\nbasePath: /aai/" + apiVersion + "\n"); - sb.append("schemes:\n - https\npaths:\n"); - /* - sb.append("responses:\n"); - sb.append(" \"200\":\n"); - sb.append(" description: successful operation\n"); - sb.append(" \"404\":\n"); - sb.append(" description: resource was not found\n"); - sb.append(" \"400\":\n"); - sb.append(" description: bad request\n"); - */ - try { - File initialFile = new File("src/main/resources/dbedgerules/DbEdgeRules_" + apiVersion + ".json"); - InputStream is = new FileInputStream(initialFile); - - Scanner scanner = new Scanner(is); - jsonEdges = scanner.useDelimiter("\\Z").next(); - scanner.close(); - is.close(); - - DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); - dbFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); - DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); - Document doc = dBuilder.parse(oxmFile); - - NodeList bindingsNodes = doc.getElementsByTagName("xml-bindings"); - Element bindingElement; - NodeList javaTypesNodes; - Element javaTypesElement; - - Element javaTypeElement; - - - if ( bindingsNodes == null || bindingsNodes.getLength() == 0 ) { - System.out.println( "missing in " + oxmFile ); - return null; - } - - bindingElement = (Element) bindingsNodes.item(0); - javaTypesNodes = bindingElement.getElementsByTagName("java-types"); - if ( javaTypesNodes.getLength() < 1 ) { - System.out.println( "missing in " + oxmFile ); - return null; - } - javaTypesElement = (Element) javaTypesNodes.item(0); - - javaTypeNodes = javaTypesElement.getElementsByTagName("java-type"); - if ( javaTypeNodes.getLength() < 1 ) { - System.out.println( "missing in " + oxmFile ); - return null; - } - - String javaTypeName; - String attrName, attrValue; - Attr attr; - StringBuffer pathSb = new StringBuffer(); - - StringBuffer definitionsSb = new StringBuffer("definitions:\n"); - - for ( int i = 0; i < javaTypeNodes.getLength(); ++ i ) { - javaTypeElement = (Element) javaTypeNodes.item(i); - NamedNodeMap attributes = javaTypeElement.getAttributes(); - javaTypeName = null; - for ( int j = 0; j < attributes.getLength(); ++j ) { - attr = (Attr) attributes.item(j); - attrName = attr.getNodeName(); - attrValue = attr.getNodeValue(); - if ( attrName.equals("name")) - javaTypeName = attrValue; - } - if ( javaTypeName == null ) { - System.out.println( " has no name attribute in " + oxmFile ); - return null; - } - if ( !generatedJavaType.containsKey(getXmlRootElementName(javaTypeName)) ) { - - //generatedJavaType.put(javaTypeName, null); - //if ( javaTypeName.equals("search")||javaTypeName.equals("actions")) - - processJavaTypeElementSwagger( javaTypeName, javaTypeElement, pathSb, - definitionsSb, null, null, null, null, null, null, null); - } - } - sb.append(pathSb); - //System.out.println( "definitions block\n" + definitionsSb.toString()); - sb.append(definitionsSb.toString()); - //sb.append(definitionsSb); - - } catch (Exception e) { - e.printStackTrace(); - return null; - } - //System.out.println("generated " + sb.toString()); - return sb.toString(); - } - - private static NodeList locateXmlProperties(Element element) { - XPathExpression expr; - NodeList result = null; - try { - expr = xpath.compile("xml-properties"); - if (expr != null) { - Object nodeset = expr.evaluate(element, XPathConstants.NODESET); - if (nodeset != null) { - NodeList nodes = (NodeList) nodeset; - if (nodes.getLength() > 0) { - Element xmlProperty = (Element)nodes.item(0); - result = xmlProperty.getElementsByTagName("xml-property"); - } - } - } - } catch (XPathExpressionException e) { - e.printStackTrace(); - } - return result; - - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/util/HbaseSaltPrefixer.java b/aai-core/src/main/java/org/openecomp/aai/util/HbaseSaltPrefixer.java deleted file mode 100644 index ba1575c4..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/util/HbaseSaltPrefixer.java +++ /dev/null @@ -1,60 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.util; - -/* - * logging to hbase encountered hotspotting issues, so per - * http://archive.cloudera.com/cdh5/cdh/5/hbase-0.98.6-cdh5.3.8/book/rowkey.design.html - * we decided to salt the rowkeys - * 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 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; - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/util/HttpsAuthClient.java b/aai-core/src/main/java/org/openecomp/aai/util/HttpsAuthClient.java deleted file mode 100644 index 664620e2..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/util/HttpsAuthClient.java +++ /dev/null @@ -1,135 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.util; - -import java.io.FileInputStream; -import java.security.KeyManagementException; -import java.security.KeyStore; - -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.HttpsURLConnection; -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.openecomp.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/openecomp/aai/util/KeyValueList.java b/aai-core/src/main/java/org/openecomp/aai/util/KeyValueList.java deleted file mode 100644 index 9628f99b..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/util/KeyValueList.java +++ /dev/null @@ -1,138 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.util; - -import 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 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" -}) -public class KeyValueList { - - @JsonProperty("key") - private String key; - @JsonProperty("value") - private String value; - @JsonIgnore - private Map additionalProperties = new HashMap(); - - /** - * - * @return - * The key - */ - @JsonProperty("key") - public String getKey() { - return key; - } - - /** - * - * @param key - * The key - */ - @JsonProperty("key") - public void setKey(String key) { - this.key = key; - } - - public KeyValueList withKey(String key) { - this.key = key; - return this; - } - - /** - * - * @return - * The value - */ - @JsonProperty("value") - public String getValue() { - return value; - } - - /** - * - * @param value - * The value - */ - @JsonProperty("value") - public void setValue(String value) { - this.value = value; - } - - public KeyValueList withValue(String value) { - this.value = value; - return this; - } - - @Override - public String toString() { - return ToStringBuilder.reflectionToString(this); - } - - @JsonAnyGetter - public Map getAdditionalProperties() { - return this.additionalProperties; - } - - @JsonAnySetter - public void setAdditionalProperty(String name, Object value) { - this.additionalProperties.put(name, value); - } - - public KeyValueList withAdditionalProperty(String name, Object value) { - this.additionalProperties.put(name, value); - return this; - } - - @Override - public int hashCode() { - return new HashCodeBuilder().append(key).append(value).append(additionalProperties).toHashCode(); - } - - @Override - public boolean equals(Object other) { - if (other == this) { - return true; - } - if ((other instanceof KeyValueList) == false) { - return false; - } - KeyValueList rhs = ((KeyValueList) other); - 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/openecomp/aai/util/MapperUtil.java b/aai-core/src/main/java/org/openecomp/aai/util/MapperUtil.java deleted file mode 100644 index 0579964d..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/util/MapperUtil.java +++ /dev/null @@ -1,115 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.util; - -import org.openecomp.aai.exceptions.AAIException; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.databind.*; -import com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule; - -public class MapperUtil { - - - /** - * Read as object of. - * - * @param the generic type - * @param clazz the clazz - * @param value the value - * @return the t - * @throws AAIException the AAI exception - */ - public static T readAsObjectOf(Class clazz, String value) throws AAIException { - com.fasterxml.jackson.databind.ObjectMapper MAPPER = new ObjectMapper(); - try { - return MAPPER.readValue(value, clazz); - } catch (Exception e) { - throw new AAIException("AAI_4007", e); - } - } - - /** - * Read with dashes as object of. - * - * @param the generic type - * @param clazz the clazz - * @param value the value - * @return the t - * @throws AAIException the AAI exception - */ - public static T readWithDashesAsObjectOf(Class clazz, String value) throws AAIException { - com.fasterxml.jackson.databind.ObjectMapper MAPPER = new ObjectMapper(); - try { - MAPPER.registerModule(new JaxbAnnotationModule()); - MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - MAPPER.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, false); - - return MAPPER.readValue(value, clazz); - } catch (Exception e) { - throw new AAIException("AAI_4007", e); - } - } - - /** - * Write as JSON string. - * - * @param obj the obj - * @return the string - * @throws AAIException the AAI exception - */ - public static String writeAsJSONString(Object obj) throws AAIException { - com.fasterxml.jackson.databind.ObjectMapper MAPPER = new ObjectMapper(); - try { - String s = MAPPER.writeValueAsString(obj); - return s; - //readValue(value, clazz); - } catch (Exception e) { - throw new AAIException("AAI_4008", e); - } - } - - /** - * Write as JSON string with dashes. - * - * @param obj the obj - * @return the string - * @throws AAIException the AAI exception - */ - public static String writeAsJSONStringWithDashes(Object obj) throws AAIException { - com.fasterxml.jackson.databind.ObjectMapper MAPPER = new ObjectMapper(); - try { - 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.registerModule(new JaxbAnnotationModule()); - String s = MAPPER.writeValueAsString(obj); - return s; - } catch (Exception e) { - throw new AAIException("AAI_4008", e); - } - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/util/PojoUtils.java b/aai-core/src/main/java/org/openecomp/aai/util/PojoUtils.java deleted file mode 100644 index 8840f412..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/util/PojoUtils.java +++ /dev/null @@ -1,82 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.util; - -import java.io.IOException; - -import org.apache.commons.io.output.ByteArrayOutputStream; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.core.JsonGenerationException; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; -import com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule; - -public class PojoUtils { - /** - * Gets the json from object. - * - * @param 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 String getJsonFromObject(T clazz) throws JsonGenerationException, JsonMappingException, IOException { - return getJsonFromObject(clazz, false, true); - } - - /** - * Gets the json from object. - * - * @param 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 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(); - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/util/Request.java b/aai-core/src/main/java/org/openecomp/aai/util/Request.java deleted file mode 100644 index 327fab74..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/util/Request.java +++ /dev/null @@ -1,160 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.util; - -import java.io.UnsupportedEncodingException; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URLEncoder; -import java.nio.charset.StandardCharsets; - -import javax.ws.rs.core.UriBuilder; - -import org.openecomp.aai.exceptions.AAIException; - -public class Request { - - public static final String V2 = "v2"; - public static final String V3 = "v3"; - public static final String V4 = "v4"; - public static final String V5 = "v5"; - public final String fromAppId; - public final String transactionId; - public final String path; - public final RestObject restObj; - public final boolean oldServer; - public final String apiVersion; - - - /** - * Instantiates a new request. - * - * @param builder the builder - */ - public Request(RequestBuilder 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 { - private String fromAppId; - private String transactionId; - private String path; - private RestObject restObj; - private boolean oldServer; - private String apiVersion = Request.V4; - - - /** - * Sets the from app id. - * - * @param fromAppId the from app id - * @return the request builder - */ - public RequestBuilder setFromAppId(String fromAppId) { - this.fromAppId = fromAppId; - return this; - } - - /** - * Sets the transaction id. - * - * @param transactionId the transaction id - * @return the request builder - */ - public RequestBuilder setTransactionId(String transactionId) { - this.transactionId = transactionId; - return this; - - } - - /** - * Sets the path. - * - * @param path the path - * @return the request builder - */ - public RequestBuilder setPath(String path) { - - this.path = path; - return this; - - } - - /** - * Sets the restcore obj. - * - * @param restObj the restcore obj - * @return the request builder - */ - public RequestBuilder setRestObj(RestObject restObj) { - this.restObj = restObj; - return this; - - } - - /** - * Sets the old server. - * - * @param oldServer the old server - * @return the request builder - */ - public RequestBuilder setOldServer(boolean oldServer) { - this.oldServer = oldServer; - return this; - - } - - /** - * Sets the api version. - * - * @param apiVersion the api version - * @return the request builder - */ - public RequestBuilder setApiVersion(String apiVersion) { - this.apiVersion = apiVersion; - return this; - } - - /** - * Builds the. - * - * @return the request - */ - public Request build() { - return new Request(this); - } - - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/util/RestObject.java b/aai-core/src/main/java/org/openecomp/aai/util/RestObject.java deleted file mode 100644 index a1cc2a14..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/util/RestObject.java +++ /dev/null @@ -1,46 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.util; - -public class RestObject { - - /** - * Generic version of the RestObject class. - * @param the type of the value being called for the Rest object interface - */ - // T stands for "Type" - private T t; - - /** - * Sets the. - * - * @param t the t - */ - public void set(T t) { this.t = t; } - - /** - * Gets the. - * - * @return the t - */ - public T get() { return t; } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/util/RestURLEncoder.java b/aai-core/src/main/java/org/openecomp/aai/util/RestURLEncoder.java deleted file mode 100644 index 46a1f48e..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/util/RestURLEncoder.java +++ /dev/null @@ -1,41 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.util; - -import java.io.UnsupportedEncodingException; -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"); - } -} - diff --git a/aai-core/src/main/java/org/openecomp/aai/util/StoreNotificationEvent.java b/aai-core/src/main/java/org/openecomp/aai/util/StoreNotificationEvent.java deleted file mode 100644 index 29fa69dc..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/util/StoreNotificationEvent.java +++ /dev/null @@ -1,336 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.util; - -import java.io.StringWriter; -import java.util.Iterator; -import java.util.UUID; - -import javax.xml.bind.Marshaller; - -import org.eclipse.persistence.dynamic.DynamicEntity; -import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext; -import org.json.JSONException; -import org.json.JSONObject; -import org.openecomp.aai.dmaap.AAIDmaapEventJMSProducer; -import org.openecomp.aai.domain.notificationEvent.NotificationEvent; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.introspection.exceptions.AAIUnknownObjectException; - -public class StoreNotificationEvent { - - private AAIDmaapEventJMSProducer messageProducer; - private String fromAppId = ""; - private String transId = ""; - private final String transactionId; - private final String sourceOfTruth; - /** - * Instantiates a new store notification event. - */ - public StoreNotificationEvent(String transactionId, String sourceOfTruth) { - this.messageProducer = new AAIDmaapEventJMSProducer(); - this.transactionId = transactionId; - this.sourceOfTruth = sourceOfTruth; - } - - /** - * Store event. - * - * @param eh - * the eh - * @param obj - * the obj - * @throws AAIException - * the AAI exception - */ - public void storeEvent(NotificationEvent.EventHeader eh, Object obj) throws AAIException { - - if (obj == null) { - throw new AAIException("AAI_7350"); - } - - org.openecomp.aai.domain.notificationEvent.ObjectFactory factory = new org.openecomp.aai.domain.notificationEvent.ObjectFactory(); - - org.openecomp.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); - } 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 void 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", AAIConstants.UEB_PUB_PARTITION_AAI); - } - - notificationEvent.setValue("event-header", eventHeader.getUnderlyingObject()); - notificationEvent.setValue("entity", obj.getUnderlyingObject()); - - String entityJson = notificationEvent.marshal(false); - sendToDmaapJmsQueue(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 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/openecomp/aai/util/UniquePropertyCheck.java b/aai-core/src/main/java/org/openecomp/aai/util/UniquePropertyCheck.java deleted file mode 100644 index a2b77506..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/util/UniquePropertyCheck.java +++ /dev/null @@ -1,267 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.util; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.Properties; -import java.util.UUID; - -import org.apache.tinkerpop.gremlin.structure.Direction; -import org.apache.tinkerpop.gremlin.structure.Edge; -import org.apache.tinkerpop.gremlin.structure.Graph; -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.apache.tinkerpop.gremlin.structure.VertexProperty; -import org.openecomp.aai.exceptions.AAIException; -import org.slf4j.MDC; - -import com.att.eelf.configuration.Configuration; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.thinkaurelius.titan.core.TitanFactory; -import com.thinkaurelius.titan.core.TitanGraph; - - - -public class UniquePropertyCheck { - - - private static final String FROMAPPID = "AAI-UTILS"; - private static final String TRANSID = UUID.randomUUID().toString(); - private static final String COMPONENT = "UniquePropertyCheck"; - - /** - * The main method. - * - * @param args the arguments - */ - public static void main(String[] args) { - - - Properties props = System.getProperties(); - props.setProperty(Configuration.PROPERTY_LOGGING_FILE_NAME, "uniquePropertyCheck-logback.xml"); - props.setProperty(Configuration.PROPERTY_LOGGING_FILE_PATH, AAIConstants.AAI_HOME_ETC_APP_PROPERTIES); - EELFLogger logger = EELFManager.getInstance().getLogger(UniquePropertyCheck.class.getSimpleName()); - MDC.put("logFilenameAppender", UniquePropertyCheck.class.getSimpleName()); - - if( args == null || args.length != 1 ){ - String msg = "usage: UniquePropertyCheck propertyName \n"; - System.out.println(msg); - logAndPrint(logger, msg ); - System.exit(1); - } - String propertyName = args[0]; - Graph graph = null; - - try { - AAIConfig.init(); - System.out.println(" ---- NOTE --- about to open graph (takes a little while)--------\n"); - TitanGraph tGraph = TitanFactory.open(AAIConstants.REALTIME_DB_CONFIG); - - if( tGraph == null ) { - logAndPrint(logger, " Error: Could not get TitanGraph "); - System.exit(1); - } - - graph = tGraph.newTransaction(); - if( graph == null ){ - logAndPrint(logger, "could not get graph object in UniquePropertyCheck() \n"); - System.exit(0); - } - } - catch (AAIException e1) { - String msg = "Threw Exception: [" + e1.toString() + "]"; - logAndPrint(logger, msg); - System.exit(0); - } - catch (Exception e2) { - String msg = "Threw Exception: [" + e2.toString() + "]"; - logAndPrint(logger, msg); - System.exit(0); - } - - runTheCheckForUniqueness( TRANSID, FROMAPPID, graph, propertyName, logger ); - System.exit(0); - - }// End main() - - - /** - * Run the check for uniqueness. - * - * @param transId the trans id - * @param fromAppId the from app id - * @param graph the graph - * @param propertyName the property name - * @param logger the logger - * @return the boolean - */ - public static Boolean runTheCheckForUniqueness( String transId, String fromAppId, Graph graph, - String propertyName, EELFLogger logger ){ - - // Note - property can be found in more than one nodetype - // our uniqueness constraints are always across the entire db - so this - // tool looks across all nodeTypes that the property is found in. - Boolean foundDupesFlag = false; - - HashMap valuesAndVidHash = new HashMap (); - HashMap dupeHash = new HashMap (); - - int propCount = 0; - int dupeCount = 0; - Iterator vertItor = graph.traversal().V().has(propertyName); - while( vertItor.hasNext() ){ - propCount++; - Vertex v = vertItor.next(); - String thisVid = v.id().toString(); - Object val = (v.property(propertyName)).orElse(null); - if( valuesAndVidHash.containsKey(val) ){ - // We've seen this one before- track it in our dupe hash - dupeCount++; - if( dupeHash.containsKey(val) ){ - // This is not the first one being added to the dupe hash for this value - String updatedDupeList = dupeHash.get(val) + "|" + thisVid; - dupeHash.put(val.toString(), updatedDupeList); - } - else { - // This is the first time we see this value repeating - String firstTwoVids = valuesAndVidHash.get(val) + "|" + thisVid; - dupeHash.put(val.toString(), firstTwoVids); - } - } - else { - valuesAndVidHash.put(val.toString(), thisVid); - } - } - - - String info = "\n Found this property [" + propertyName + "] " + propCount + " times in our db."; - logAndPrint(logger, info); - info = " Found " + dupeCount + " cases of duplicate values for this property.\n\n"; - logAndPrint(logger, info); - - try { - if( ! dupeHash.isEmpty() ){ - Iterator dupeItr = dupeHash.entrySet().iterator(); - while( dupeItr.hasNext() ){ - Map.Entry pair = (Map.Entry) dupeItr.next(); - String dupeValue = pair.getKey().toString();; - String vidsStr = pair.getValue().toString(); - String[] vidArr = vidsStr.split("\\|"); - logAndPrint(logger, "\n\n -------------- Found " + vidArr.length - + " nodes with " + propertyName + " of this value: [" + dupeValue + "]. Node details: "); - - for( int i = 0; i < vidArr.length; i++ ){ - String vidString = vidArr[i]; - Long idLong = Long.valueOf(vidString); - Vertex tvx = graph.traversal().V(idLong).next(); - showPropertiesAndEdges( TRANSID, FROMAPPID, tvx, logger ); - } - } - } - } - catch( Exception e2 ){ - logAndPrint(logger, "Threw Exception: [" + e2.toString() + "]"); - } - finally { - if( graph != null ){ - graph.tx().rollback(); - } - } - - return foundDupesFlag; - - }// end of runTheCheckForUniqueness() - - - /** - * Show properties and edges. - * - * @param transId the trans id - * @param fromAppId the from app id - * @param tVert the t vert - * @param logger the logger - */ - private static void showPropertiesAndEdges( String transId, String fromAppId, Vertex tVert, - EELFLogger logger ){ - - if( tVert == null ){ - logAndPrint(logger, "Null node passed to showPropertiesAndEdges."); - } - else { - String nodeType = ""; - Object ob = tVert.property("aai-node-type").orElse(null); - if( ob == null ){ - nodeType = "null"; - } - else{ - nodeType = ob.toString(); - } - - logAndPrint(logger, " AAINodeType/VtxID for this Node = [" + nodeType + "/" + tVert.id() + "]"); - logAndPrint(logger, " Property Detail: "); - Iterator> pI = tVert.properties(); - while( pI.hasNext() ){ - VertexProperty tp = pI.next(); - Object val = tp.value(); - logAndPrint(logger, "Prop: [" + tp.key() + "], val = [" + val + "] "); - } - - Iterator eI = tVert.edges(Direction.BOTH); - if( ! eI.hasNext() ){ - logAndPrint(logger, "No edges were found for this vertex. "); - } - while( eI.hasNext() ){ - Edge ed = eI.next(); - String lab = ed.label(); - Vertex vtx; - if (tVert.equals(ed.inVertex())) { - vtx = ed.outVertex(); - } else { - vtx = ed.inVertex(); - } - if( vtx == null ){ - logAndPrint(logger, " >>> COULD NOT FIND VERTEX on the other side of this edge edgeId = " + ed.id() + " <<< "); - } - else { - String nType = vtx.property("aai-node-type").orElse(null); - String vid = vtx.id().toString(); - logAndPrint(logger, "Found an edge (" + lab + ") from this vertex to a [" + nType + "] node with VtxId = " + vid); - } - } - } - } // End of showPropertiesAndEdges() - - - /** - * Log and print. - * - * @param logger the logger - * @param msg the msg - */ - protected static void logAndPrint(EELFLogger logger, String msg) { - System.out.println(msg); - logger.info(msg); - } - -} - - diff --git a/aai-core/src/main/java/org/openecomp/aai/util/swagger/Api.java b/aai-core/src/main/java/org/openecomp/aai/util/swagger/Api.java deleted file mode 100644 index 241be43a..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/util/swagger/Api.java +++ /dev/null @@ -1,310 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.util.swagger; - -import java.util.List; -import java.util.Map; - -public class Api { - - private String path; - - private List httpMethods; - - private String tag; - - public List getHttpMethods() { - return httpMethods; - } - - public void setHttpMethods(List httpMethods) { - this.httpMethods = httpMethods; - } - - public String getTag(){ - - if(this.tag != null){ - return this.tag; - } - - if(this.httpMethods != null){ - if(this.httpMethods.size() != 0){ - if(this.httpMethods.get(0).getTags() != null){ - if(this.httpMethods.get(0).getTags().size() != 0){ - this.tag = this.httpMethods.get(0).getTags().get(0); - } - } - } - } - - if(this.tag == null){ - this.tag = ""; - } - - return this.tag; - } - - @Override - public String toString() { - return "Api{" + - "path='" + path + '\'' + - ", httpMethods=" + httpMethods + - '}'; - } - - public void setPath(String path) { - this.path = path; - } - - public String getPath() { - return this.path; - } - - public String getOperation(){ - - if(this.path != null){ - return this.path.replaceAll("[^a-zA-Z0-9\\-]", "-") + "-"; - } - - return ""; - } - - public static class HttpVerb { - - private List tags; - - private String type; - - private String summary; - - private String operationId; - - private List consumes; - - private boolean consumerEnabled; - - private List produces; - - private List responses; - - private List> parameters; - - private Map bodyParameters; - - private boolean bodyParametersEnabled; - - private boolean parametersEnabled; - - private String schemaLink; - - private String schemaType; - - private boolean hasReturnSchema; - - private String returnSchemaLink; - - private String returnSchemaObject; - - public void setConsumerEnabled(boolean consumerEnabled){ - this.consumerEnabled = consumerEnabled; - } - - public boolean isConsumerEnabled() { - return consumerEnabled; - } - - - public List getTags() { - return tags; - } - - public void setTags(List tags) { - this.tags = tags; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public String getSummary() { - return summary; - } - - public void setSummary(String summary) { - this.summary = summary; - } - - public String getOperationId() { - return operationId; - } - - public void setOperationId(String operationId) { - this.operationId = operationId; - } - - public List getConsumes() { - return consumes; - } - - public void setConsumes(List consumes) { - this.consumes = consumes; - } - - public List getProduces() { - return produces; - } - - public void setProduces(List produces) { - this.produces = produces; - } - - public List getResponses() { - return responses; - } - - public void setResponses(List responses) { - this.responses = responses; - } - - public List> getParameters() { - return parameters; - } - - public void setParameters(List> parameters) { - this.parameters = parameters; - } - - @Override - public String toString() { - return "HttpVerb{" + - "tags=" + tags + - ", type='" + type + '\'' + - ", summary='" + summary + '\'' + - ", operationId='" + operationId + '\'' + - ", consumes=" + consumes + - ", produces=" + produces + - ", responses=" + responses + - ", parameters=" + parameters + - '}'; - } - - public void setParametersEnabled(boolean b) { - this.parametersEnabled = b; - } - - public boolean isParametersEnabled() { - return parametersEnabled; - } - - public boolean isBodyParametersEnabled() { - return bodyParametersEnabled; - } - - public void setBodyParametersEnabled(boolean bodyParametersEnabled) { - this.bodyParametersEnabled = bodyParametersEnabled; - } - - public Map getBodyParameters() { - return bodyParameters; - } - - public void setBodyParameters(Map bodyParameters) { - this.bodyParameters = bodyParameters; - } - - public String getSchemaLink() { - return schemaLink; - } - - public void setSchemaLink(String schemaLink) { - this.schemaLink = schemaLink; - } - - public String getSchemaType() { - return schemaType; - } - - public void setSchemaType(String schemaType) { - this.schemaType = schemaType; - } - - public boolean isHasReturnSchema() { - return hasReturnSchema; - } - - public void setHasReturnSchema(boolean hasReturnSchema) { - this.hasReturnSchema = hasReturnSchema; - } - - public String getReturnSchemaLink() { - return returnSchemaLink; - } - - public void setReturnSchemaLink(String returnSchemaLink) { - this.returnSchemaLink = returnSchemaLink; - } - - public String getReturnSchemaObject() { - return returnSchemaObject; - } - - public void setReturnSchemaObject(String returnSchemaObject) { - this.returnSchemaObject = returnSchemaObject; - } - - public static class Response { - - private String responseCode; - - private String description; - - public String getResponseCode() { - return responseCode; - } - - public void setResponseCode(String responseCode) { - this.responseCode = responseCode; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - @Override - public String toString() { - return "Response{" + - "responseCode='" + responseCode + '\'' + - ", description='" + description + '\'' + - '}'; - } - } - - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/util/swagger/Definition.java b/aai-core/src/main/java/org/openecomp/aai/util/swagger/Definition.java deleted file mode 100644 index 31c38c56..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/util/swagger/Definition.java +++ /dev/null @@ -1,199 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.util.swagger; - -import java.util.List; - -public class Definition { - - private String definitionName; - - private String definitionDescription; - - private List propertyList; - - private List schemaPropertyList; - - private List regularPropertyList; - - private boolean hasDescription; - - public String getDefinitionName() { - return definitionName; - } - - public void setDefinitionName(String definitionName) { - this.definitionName = definitionName; - } - - public List getPropertyList() { - return propertyList; - } - - public void setPropertyList(List propertyList) { - this.propertyList = propertyList; - } - - public String getDefinitionDescription() { - return definitionDescription; - } - - public void setDefinitionDescription(String definitionDescription) { - this.definitionDescription = definitionDescription; - } - - @Override - public String toString() { - return "Definition{" + - "definitionName='" + definitionName + '\'' + - ", definitionDescription='" + definitionDescription + '\'' + - ", propertyList=" + propertyList + - '}'; - } - - public boolean isHasDescription() { - return hasDescription; - } - - public void setHasDescription(boolean hasDescription) { - this.hasDescription = hasDescription; - } - - public List getSchemaPropertyList() { - return schemaPropertyList; - } - - public void setSchemaPropertyList(List schemaPropertyList) { - this.schemaPropertyList = schemaPropertyList; - } - - public List getRegularPropertyList() { - return regularPropertyList; - } - - public void setRegularPropertyList(List regularPropertyList) { - this.regularPropertyList = regularPropertyList; - } - - public static class Property { - - private String propertyName; - - private String propertyDescription; - - private boolean hasPropertyDescription; - - private String propertyType; - - private boolean hasType; - - private String propertyReference; - - private String propertyReferenceObjectName; - - private boolean isRequired; - - private boolean hasPropertyReference; - - public Property(){} - - public String getPropertyName() { - return propertyName; - } - - public void setPropertyName(String propertyName) { - this.propertyName = propertyName; - } - - public String getPropertyType() { - return propertyType; - } - - public void setPropertyType(String propertyType) { - this.propertyType = propertyType; - } - - public String getPropertyReference() { - return propertyReference; - } - - public void setPropertyReference(String propertyReference) { - this.propertyReference = propertyReference; - } - - @Override - public String toString() { - return "Property{" + - "propertyName='" + propertyName + '\'' + - ", propertyType='" + propertyType + '\'' + - ", propertyReference='" + propertyReference + '\'' + - '}'; - } - - public boolean isHasType() { - return hasType; - } - - public void setHasType(boolean hasType) { - this.hasType = hasType; - } - - public boolean isRequired() { - return isRequired; - } - - public void setRequired(boolean required) { - isRequired = required; - } - - public boolean isHasPropertyReference() { - return hasPropertyReference; - } - - public void setHasPropertyReference(boolean hasPropertyReference) { - this.hasPropertyReference = hasPropertyReference; - } - - public String getPropertyReferenceObjectName() { - return propertyReferenceObjectName; - } - - public void setPropertyReferenceObjectName(String propertyReferenceObjectName) { - this.propertyReferenceObjectName = propertyReferenceObjectName; - } - - public String getPropertyDescription() { - return propertyDescription; - } - - public void setPropertyDescription(String propertyDescription) { - this.propertyDescription = propertyDescription; - } - - public boolean isHasPropertyDescription() { - return hasPropertyDescription; - } - - public void setHasPropertyDescription(boolean hasPropertyDescription) { - this.hasPropertyDescription = hasPropertyDescription; - } - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/util/swagger/GenerateSwagger.java b/aai-core/src/main/java/org/openecomp/aai/util/swagger/GenerateSwagger.java deleted file mode 100644 index 5731485e..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/util/swagger/GenerateSwagger.java +++ /dev/null @@ -1,432 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.util.swagger; - -import com.fasterxml.jackson.dataformat.yaml.snakeyaml.Yaml; -import com.fasterxml.jackson.dataformat.yaml.snakeyaml.constructor.SafeConstructor; -import freemarker.template.Configuration; -import freemarker.template.Template; -import freemarker.template.TemplateException; - -import java.io.*; -import java.util.*; -import java.util.stream.Collectors; - -public class GenerateSwagger { - - public static final String LINE_SEPARATOR = System.getProperty("line.separator"); - public static final String DEFAULT_WIKI = ""; - - public static final String DEFAULT_SCHEMA_DIR = "../aai-schema"; - public static final String CURRENT_VERSION = "v11"; - - public static void main(String[] args) throws IOException, TemplateException { - - String schemaDir = System.getProperty("aai.schema.dir"); - String versionToGenerate = System.getProperty("aai.generate.version"); - String wikiLink = System.getProperty("aai.wiki.link"); - - if(schemaDir == null){ - System.out.println("Warning: Schema directory is not set so using default schema dir: " + DEFAULT_SCHEMA_DIR); - schemaDir = DEFAULT_SCHEMA_DIR; - } - - if(versionToGenerate == null){ - System.out.println("Warning: Version to generate is not set so using default version: " + CURRENT_VERSION); - versionToGenerate = CURRENT_VERSION; - } - - if(wikiLink == null){ - System.out.println("Warning: aai.wiki.link property is not set so using default"); - wikiLink = DEFAULT_WIKI; - } - - String yamlFile = schemaDir + "/src/main/resources/aai_swagger_yaml/aai_swagger_" + versionToGenerate + ".yaml"; - File swaggerYamlFile = new File(yamlFile); - - if(!swaggerYamlFile.exists()){ - System.err.println("Unable to find the swagger yaml file: " + swaggerYamlFile); - System.exit(1); - } - - Yaml yaml = new Yaml(new SafeConstructor()); - Map swaggerMap = null; - - try (BufferedReader reader = new BufferedReader(new FileReader(swaggerYamlFile))){ - swaggerMap = (Map) yaml.load(reader); - } catch(IOException ex){ - ex.printStackTrace(); - } - - if(null == swaggerMap) { - throw new IOException(); - } - - Map map = (Map) swaggerMap.get("paths"); - Map schemaDefinitionmap = (Map) swaggerMap.get("definitions"); - Map infoMap = (Map) swaggerMap.get("info"); - Map> tagMap = new LinkedHashMap<>(); - - List apis = convertToApi(map); - apis.forEach((api) -> { - if(!tagMap.containsKey(api.getTag())){ - List newApis = new ArrayList<>(); - newApis.add(api); - tagMap.put(api.getTag(), newApis); - } else { - tagMap.get(api.getTag()).add(api); - } - }); - - Map> sortedTagMap = new TreeMap<>(tagMap); - sortedTagMap.forEach((key, value) -> { - value.sort(Comparator.comparing(Api::getPath)); - }); - - Map resultMap = new HashMap<>(); - - List definitionList = convertToDefinition(schemaDefinitionmap); - - definitionList = definitionList - .stream().sorted(Comparator.comparing(Definition::getDefinitionName)).collect(Collectors.toList()); - - resultMap.put("aaiApis", tagMap); - resultMap.put("sortedAaiApis", sortedTagMap); - resultMap.put("wikiLink", wikiLink); - resultMap.put("definitions", definitionList); - if (infoMap.containsKey("description")) { - String infoDescription = infoMap.get("description").toString(); - - infoDescription = Arrays.stream(infoDescription.split("\n")) - .map(line -> { - line = line.trim(); - String hyperLink = ""; - if(line.trim().contains("https://")){ - int startIndex = line.indexOf("https://"); - int endIndex = line.lastIndexOf("/"); - hyperLink = line.substring(startIndex, endIndex); - return String.format("%s
    ", hyperLink, line); - } - return String.format("%s
    ", line); - }) - - .collect(Collectors.joining(LINE_SEPARATOR)); - - resultMap.put("description", infoDescription); - } - - Configuration configuration = new Configuration(); - configuration.setClassForTemplateLoading(Api.class, "/"); - configuration.setDirectoryForTemplateLoading(new File("src/main/resources/")); - - Template template = configuration.getTemplate("swagger.html.ftl"); - - String outputDirStr = schemaDir + "/src/main/resources/aai_swagger_html"; - - File outputDir = new File(outputDirStr); - - if(!outputDir.exists()){ - boolean resp = outputDir.mkdir(); - if(!resp){ - System.err.println("Unable to create the directory: " + outputDirStr); - System.exit(1); - } - } else if(outputDir.isFile()){ - System.err.println("Unable to create the directory: " + outputDirStr + " since a filename with that string exists"); - System.exit(1); - } - - Writer file = new FileWriter(new File(outputDirStr + "/aai_swagger_" + versionToGenerate + ".html")); - template.process(resultMap, file); - } - - public static List convertToApi(Map pathMap){ - - if(pathMap == null) - throw new IllegalArgumentException(); - - List apis = new ArrayList<>(); - - pathMap.forEach( (pathKey, pathValue) -> { - - Api api = new Api(); - Map httpVerbMap = (Map) pathValue; - List httpVerbs = new ArrayList<>(); - - api.setPath(pathKey); - - httpVerbMap.forEach((httpVerbKey, httpVerbValue) -> { - - Api.HttpVerb httpVerb = new Api.HttpVerb(); - - Map httpVerbValueMap = (Map)httpVerbValue; - - httpVerb.setType(httpVerbKey); - - if(httpVerbValueMap.containsKey("tags")){ - httpVerb.setTags((List)httpVerbValueMap.get("tags")); - } - - if(httpVerbValueMap.containsKey("summary")){ - httpVerb.setSummary((String)httpVerbValueMap.get("summary")); - } - - if(httpVerbValueMap.containsKey("operationId")){ - httpVerb.setOperationId((String)httpVerbValueMap.get("operationId")); - } - - if(httpVerbValueMap.containsKey("consumes")){ - httpVerb.setConsumes((List)httpVerbValueMap.get("consumes")); - if(httpVerb.getConsumes() != null){ - httpVerb.setConsumerEnabled(true); - } - } - - if(httpVerbValueMap.containsKey("produces")){ - httpVerb.setProduces((List)httpVerbValueMap.get("produces")); - } - - if(httpVerbValueMap.containsKey("parameters")){ - List> parameters = (List>) httpVerbValueMap.get("parameters"); - List> requestParameters = parameters - .stream() - .filter((parameter) -> !parameter.get("name").equals("body")) - .collect(Collectors.toList()); - httpVerb.setParameters(requestParameters); - if(httpVerb.getParameters() != null){ - httpVerb.setParametersEnabled(true); - } - - List> requestBodyList = parameters - .stream() - .filter((parameter) -> parameter.get("name").equals("body")) - .collect(Collectors.toList()); - - Map requestBody = null; - - if(requestBodyList != null && requestBodyList.size() == 1){ - requestBody = requestBodyList.get(0); - httpVerb.setBodyParametersEnabled(true); - httpVerb.setBodyParameters(requestBody); - - if(requestBody != null && requestBody.containsKey("schema")){ - Map schemaMap = (Map)requestBody.get("schema"); - if(schemaMap != null && schemaMap.containsKey("$ref")){ - String schemaLink = schemaMap.get("$ref").toString(); - httpVerb.setSchemaLink(schemaLink); - int retCode = schemaLink.lastIndexOf('/'); - if(retCode != -1 && retCode != schemaLink.length()){ - httpVerb.setSchemaType(schemaLink.substring(retCode)); - } - } - } - } - } - - if(httpVerbValueMap.containsKey("responses")){ - - List responses = new ArrayList(); - - Map responsesMap = (Map) httpVerbValueMap.get("responses"); - - responsesMap - .entrySet() - .stream() - .filter((res) -> !"default".equalsIgnoreCase(res.getKey())) - .forEach((responseMap) -> { - - Map responseValueMap = (Map)responseMap.getValue(); - - Api.HttpVerb.Response response = new Api.HttpVerb.Response(); - - response.setResponseCode(responseMap.getKey()); - response.setDescription((String) responseValueMap.get("description")); - - if(responseValueMap != null && responseValueMap.containsKey("schema")){ - Map schemaMap = (Map)responseValueMap.get("schema"); - if(schemaMap != null && schemaMap.containsKey("$ref")){ - String schemaLink = schemaMap.get("$ref").toString(); - httpVerb.setHasReturnSchema(true); - httpVerb.setReturnSchemaLink(schemaLink); - int retCode = schemaLink.lastIndexOf('/'); - if(retCode != -1 && retCode != schemaLink.length()){ - httpVerb.setReturnSchemaObject(schemaLink.substring(retCode)); - } - } - } - - responses.add(response); - } - ); - - httpVerb.setResponses(responses); - } - - httpVerbs.add(httpVerb); - }); - - api.setHttpMethods(httpVerbs); - apis.add(api); - }); - - return apis; - } - - public static List convertToDefinition(Map definitionMap) { - - if(definitionMap == null) - throw new IllegalArgumentException(); - - List defintionsList = new ArrayList<>(); - - definitionMap - .entrySet() - .forEach((entry) -> { - - Definition definition = new Definition(); - String key = entry.getKey(); - Map valueMap = (Map) entry.getValue(); - - definition.setDefinitionName(key); - - if(valueMap.containsKey("description")){ - String description = valueMap.get("description").toString(); - description = formatDescription(description); - definition.setDefinitionDescription(description); - definition.setHasDescription(true); - } - - List definitionProperties = new ArrayList<>(); - - List requiredProperties = (valueMap.get("required") == null) ? new ArrayList<>() : (List) valueMap.get("required"); - - Set requiredPropsSet = requiredProperties.stream().collect(Collectors.toSet()); - - valueMap - .entrySet() - .stream() - .filter( (e) -> "properties".equals(e.getKey())) - .forEach((propertyEntries) -> { - Map propertyRealEntries = (Map) propertyEntries.getValue(); - propertyRealEntries - .entrySet() - .forEach((propertyEntry) -> { - Definition.Property definitionProperty = new Definition.Property(); - String propertyKey = propertyEntry.getKey(); - if(requiredPropsSet.contains(propertyKey)){ - definitionProperty.setRequired(true); - } - definitionProperty.setPropertyName(propertyKey); - Map definitionPropertyMap = (Map) propertyEntry.getValue(); - - if(definitionPropertyMap.containsKey("description")){ - definitionProperty.setPropertyDescription(definitionPropertyMap.get("description").toString()); - definitionProperty.setHasPropertyDescription(true); - } - if(definitionPropertyMap.containsKey("type")){ - String type = definitionPropertyMap.get("type").toString(); - definitionProperty.setPropertyType(type); - definitionProperty.setHasType(true); - if ("array".equals(type)) { - definitionProperty.setPropertyType("object[]"); - if(!definitionPropertyMap.containsKey("items")){ - throw new RuntimeException("Unable to find the property items even though the type is array for " + propertyEntry.getKey()); - } else { - Map itemMap = (Map) definitionPropertyMap.get("items"); - if(itemMap.containsKey("$ref")){ - definitionProperty.setHasPropertyReference(true); - String refItem = itemMap.get("$ref").toString(); - int retCode = refItem.lastIndexOf('/'); - if(retCode != -1 && retCode != refItem.length()){ - definitionProperty.setPropertyReferenceObjectName(refItem.substring(retCode + 1)); - } - definitionProperty.setPropertyReference(refItem); - } - } - } else { - if(definitionPropertyMap.containsKey("$ref")){ - definitionProperty.setHasPropertyReference(true); - String refItem = definitionPropertyMap.get("$ref").toString(); - int retCode = refItem.lastIndexOf('/'); - if(retCode != -1 && retCode != refItem.length()){ - definitionProperty.setPropertyReferenceObjectName(refItem.substring(retCode + 1)); - } - definitionProperty.setPropertyReference(refItem); - } - } - } - definitionProperties.add(definitionProperty); - }); - }); - - definition.setPropertyList(definitionProperties); - - List schemaProperties = definitionProperties. - stream() - .filter((o) -> o.isHasPropertyReference()) - .collect(Collectors.toList()); - - List regularProperties = definitionProperties. - stream() - .filter((o) -> !o.isHasPropertyReference()) - .collect(Collectors.toList()); - - definition.setRegularPropertyList(regularProperties); - definition.setSchemaPropertyList(schemaProperties); - - defintionsList.add(definition); - }); - return defintionsList; - } - - public static String formatDescription(String description){ - - description = Arrays.stream(description.split("\n")) - .map((line) -> { - line = line.trim(); - if(line.contains("######")){ - line = line.replaceAll("#", ""); - line = line.trim(); - String headerId = line.toLowerCase().replaceAll("\\s", "-"); - - if(line.contains("Related Nodes")){ - return String.format("
    %s
    %s
      ", headerId, line, LINE_SEPARATOR); - } else { - return String.format("
      %s
      ", headerId, line); - } - } else if(line.startsWith("-")){ - line = line.replaceFirst("-", ""); - line = line.trim(); - return String.format("
    • %s
    • ", line); - } else { - return String.format("

      %s

      ", line); - } - }) - .collect(Collectors.joining(LINE_SEPARATOR)); - - if(description.contains("
        ")){ - description = description + "
      "; - } - - return description; - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/workarounds/LegacyURITransformer.java b/aai-core/src/main/java/org/openecomp/aai/workarounds/LegacyURITransformer.java deleted file mode 100644 index f79bae60..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/workarounds/LegacyURITransformer.java +++ /dev/null @@ -1,93 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.workarounds; - -import java.net.MalformedURLException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class LegacyURITransformer { - - private final Pattern legacyUriPattern = Pattern.compile("/aai/servers/(?v[23])/(?.*?)/vservers/(?[^/]*?$)"); - private final Pattern currentUriPattern = Pattern.compile("/aai/(?v\\d+)/cloud-infrastructure/tenants/tenant/(?.*?)/vservers/vserver/(?[^/]*?$)"); - /** - * Instantiates a new legacy URL transformer. - */ - private LegacyURITransformer() { - - } - - private static class Helper { - private static final LegacyURITransformer INSTANCE = new LegacyURITransformer(); - } - - /** - * Gets the single instance of LegacyURLTransformer. - * - * @return single instance of LegacyURLTransformer - */ - public static LegacyURITransformer getInstance() { - return Helper.INSTANCE; - } - - /** - * Gets the legacy URL. - * - * @param url the url - * @return the legacy URL - * @throws URISyntaxException - * @throws MalformedURLException the malformed URL exception - */ - public URI getLegacyURI(URI url) throws URISyntaxException { - String replacement = "/aai/servers/${version}/${tenantKey}/vservers/${vserverKey}"; - String result = url.toString(); - Matcher m = currentUriPattern.matcher(result); - if (m.find()) { - result = m.replaceFirst(replacement); - - } - - return new URI(result); - - } - - /** - * Gets the current URL. - * - * @param url the url - * @return the current URL - * @throws URISyntaxException - * @throws MalformedURLException the malformed URL exception - */ - public URI getCurrentURI(URI url) throws URISyntaxException { - String replacement = "/aai/${version}/cloud-infrastructure/tenants/tenant/${tenantKey}/vservers/vserver/${vserverKey}"; - String result = url.toString(); - Matcher m = legacyUriPattern.matcher(result); - if (m.find()) { - result = m.replaceFirst(replacement); - - } - - return new URI(result); - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/workarounds/NamingExceptions.java b/aai-core/src/main/java/org/openecomp/aai/workarounds/NamingExceptions.java deleted file mode 100644 index 7ce063ed..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/workarounds/NamingExceptions.java +++ /dev/null @@ -1,79 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.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; - - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/workarounds/RemoveDME2QueryParams.java b/aai-core/src/main/java/org/openecomp/aai/workarounds/RemoveDME2QueryParams.java deleted file mode 100644 index b829639b..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/workarounds/RemoveDME2QueryParams.java +++ /dev/null @@ -1,65 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.workarounds; - -import javax.ws.rs.core.MultivaluedMap; - -public class RemoveDME2QueryParams { - - private final String[] blacklist = {"version", "envContext", "routeOffer"}; - - - /** - * Should remove query params. - * - * @param params the params - * @return true, if successful - */ - public boolean shouldRemoveQueryParams(MultivaluedMap params) { - boolean remove = true; - - for (String param : blacklist) { - if (!params.containsKey(param)) { - remove = false; - break; - } - } - - return remove; - - } - - /** - * Removes the query params. - * - * @param params the params - */ - public void removeQueryParams(MultivaluedMap params) { - - - for (String param : blacklist) { - params.remove(param); - } - - - } - -} diff --git a/aai-core/src/main/resources/EdgeRules.ftl b/aai-core/src/main/resources/EdgeRules.ftl index 837f9377..b29cd314 100644 --- a/aai-core/src/main/resources/EdgeRules.ftl +++ b/aai-core/src/main/resources/EdgeRules.ftl @@ -1,23 +1,26 @@ <#-- - ============LICENSE_START======================================================= - org.openecomp.aai - ================================================================================ - Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - ================================================================================ - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - ============LICENSE_END========================================================= ---> + ============LICENSE_START======================================================= + org.onap.aai + ================================================================================ + Copyright © 2017 AT&T Intellectual Property. All rights reserved. + ================================================================================ + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + ============LICENSE_END========================================================= + + ECOMP is a trademark and service mark of AT&T Intellectual Property. + +--> public static final Multimap EdgeRules = new ImmutableSetMultimap.Builder() <#list edgeRules as edgeRule> .putAll("${edgeRule["nodes"]}", diff --git a/aai-core/src/main/resources/swagger.html.ftl b/aai-core/src/main/resources/swagger.html.ftl index 0506783f..64bd3a45 100644 --- a/aai-core/src/main/resources/swagger.html.ftl +++ b/aai-core/src/main/resources/swagger.html.ftl @@ -1,23 +1,26 @@ <#-- - ============LICENSE_START======================================================= - org.openecomp.aai - ================================================================================ - Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - ================================================================================ - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - ============LICENSE_END========================================================= ---> + ============LICENSE_START======================================================= + org.onap.aai + ================================================================================ + Copyright © 2017 AT&T Intellectual Property. All rights reserved. + ================================================================================ + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + ============LICENSE_END========================================================= + + ECOMP is a trademark and service mark of AT&T Intellectual Property. + +--> diff --git a/aai-core/src/test/java/org/onap/aai/AAISetup.java b/aai-core/src/test/java/org/onap/aai/AAISetup.java new file mode 100644 index 00000000..f531cea3 --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/AAISetup.java @@ -0,0 +1,36 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai; + +import org.junit.BeforeClass; +import org.onap.aai.serialization.queryformats.QueryFormatTestHelper; +import org.onap.aai.util.AAIConstants; + +public abstract class AAISetup { + + @BeforeClass + public static void setupBundleconfig() throws Exception { + System.setProperty("AJSC_HOME", "."); + System.setProperty("BUNDLECONFIG_DIR", "src/test/resources/bundleconfig-local"); + QueryFormatTestHelper.setFinalStatic(AAIConstants.class.getField("AAI_HOME_ETC_OXM"), "src/test/resources/bundleconfig-local/etc/oxm/"); + } +} diff --git a/aai-core/src/test/java/org/onap/aai/exceptions/AAIExceptionTest.java b/aai-core/src/test/java/org/onap/aai/exceptions/AAIExceptionTest.java new file mode 100644 index 00000000..36757e23 --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/exceptions/AAIExceptionTest.java @@ -0,0 +1,114 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.exceptions; + +import org.junit.Test; +import org.onap.aai.AAISetup; + +import static org.junit.Assert.assertEquals; + +public class AAIExceptionTest extends AAISetup { + + private static final String code = "4004"; + private static final String details = "This is a detailed description of the exception."; + private static final Throwable cause = new RuntimeException("This is a runtime exception."); + private static final Throwable noMessage = new RuntimeException(); + + /** + * Test constructor with 0 params. + * + * @throws Exception the exception + */ + @Test + public void testConstructorWith0Params() throws Exception { + AAIException exception = new AAIException(); + assertEquals(exception, exception); + } + + /** + * Test constructor with 1 params. + * + * @throws Exception the exception + */ + @Test + public void testConstructorWith1Params() throws Exception { + AAIException exception = new AAIException(code); + assertEquals(exception, exception); + } + + /** + * Test constructor with 2 params details. + * + * @throws Exception the exception + */ + @Test + public void testConstructorWith2ParamsDetails() throws Exception { + AAIException exception = new AAIException(code, details); + assertEquals(details, exception.getMessage()); + } + + /** + * Test constructor with 2 params cause. + * + * @throws Exception the exception + */ + @Test + public void testConstructorWith2ParamsCause() throws Exception { + AAIException exception = new AAIException(code, cause); + assertEquals("java.lang.RuntimeException: This is a runtime exception.", exception.getMessage()); + } + + /** + * Test constructor with 2 params null message. + * + * @throws Exception the exception + */ + @Test + public void testConstructorWith2ParamsNullMessage() throws Exception { + AAIException exception = new AAIException(code, noMessage); + assertEquals(noMessage.toString(), exception.getMessage()); + } + + /** + * Test constructor with 3 params. + * + * @throws Exception the exception + */ + @Test + public void testConstructorWith3Params() throws Exception { + AAIException exception = new AAIException(code, cause, details); + String details = "This is a detailed description of the exception."; + assertEquals(details, exception.getMessage()); + } + + /** + * Test constructor with 3 params null message. + * + * @throws Exception the exception + */ + @Test + public void testConstructorWith3ParamsNullMessage() throws Exception { + AAIException exception = new AAIException(code, noMessage, details); + String detailString = new String(details); + assertEquals(detailString, exception.getMessage()); + } +} diff --git a/aai-core/src/test/java/org/onap/aai/exceptions/AAIExceptionWithInfoTest.java b/aai-core/src/test/java/org/onap/aai/exceptions/AAIExceptionWithInfoTest.java new file mode 100644 index 00000000..961bf688 --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/exceptions/AAIExceptionWithInfoTest.java @@ -0,0 +1,148 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.exceptions; + +import org.junit.Test; +import org.onap.aai.AAISetup; + +import java.util.HashMap; + +import static org.junit.Assert.assertEquals; + +public class AAIExceptionWithInfoTest extends AAISetup { + + + private static final HashMap map = new HashMap(); + + { + map.put("itemInteger", 1); + map.put("itemString", "Two"); + map.put("itemThree", Boolean.TRUE); + } + + private static final String info = "An error has occurred."; + private static final String code = "AAI_4004"; + private static final String details = "This is a detailed description of the exception."; + private static final Throwable cause = new RuntimeException("This is a runtime exception."); + + /** + * Test constructor with 2 params. + * + * @throws Exception the exception + */ + @Test + public void testConstructorWith2Params() throws Exception { + AAIExceptionWithInfo exception = new AAIExceptionWithInfo(map, info); + + assertEquals(map, exception.getInfoHash()); + assertEquals(info, exception.getInfo()); + } + + /** + * Test constructor with 3 params. + * + * @throws Exception the exception + */ + @Test + public void testConstructorWith3Params() throws Exception { + AAIExceptionWithInfo exception = new AAIExceptionWithInfo(code, map, info); + + assertEquals("4004", exception.getErrorObject().getErrorCode()); + assertEquals(map, exception.getInfoHash()); + assertEquals(info, exception.getInfo()); + } + + /** + * Test constructor with 4 params I. + * + * @throws Exception the exception + */ + @Test + public void testConstructorWith4ParamsI() throws Exception { + AAIExceptionWithInfo exception = new AAIExceptionWithInfo(code, details, map, info); + + assertEquals("4004", exception.getErrorObject().getErrorCode()); + assertEquals(details, exception.getMessage()); + assertEquals(map, exception.getInfoHash()); + assertEquals(info, exception.getInfo()); + } + + /** + * Test constructor with 4 params II. + * + * @throws Exception the exception + */ + @Test + public void testConstructorWith4ParamsII() throws Exception { + AAIExceptionWithInfo exception = new AAIExceptionWithInfo(code, cause, map, info); + + assertEquals("4004", exception.getErrorObject().getErrorCode()); + assertEquals(cause.toString(), exception.getMessage()); + assertEquals(map, exception.getInfoHash()); + assertEquals(info, exception.getInfo()); + } + + /** + * Test constructor with 5 params. + * + * @throws Exception the exception + */ + @Test + public void testConstructorWith5Params() throws Exception { + AAIExceptionWithInfo exception = new AAIExceptionWithInfo(code, cause, details, map, info); + + assertEquals("4004", exception.getErrorObject().getErrorCode()); + assertEquals(details, exception.getMessage()); + assertEquals(map, exception.getInfoHash()); + assertEquals(info, exception.getInfo()); + } + + /** + * Test set info hash. + */ + @Test + public void testSetInfoHash() { + AAIExceptionWithInfo exception = new AAIExceptionWithInfo(map, info); + + HashMap newMap = new HashMap(); + newMap.put("itemInteger", 2); + exception.setInfoHash(newMap); + + assertEquals(newMap, exception.getInfoHash()); + assertEquals(info, exception.getInfo()); + } + + /** + * Test set info. + */ + @Test + public void testSetInfo() { + AAIExceptionWithInfo exception = new AAIExceptionWithInfo(map, info); + + String newInfo = "This is updated info."; + exception.setInfo(newInfo); + + assertEquals(map, exception.getInfoHash()); + assertEquals(newInfo, exception.getInfo()); + } + +} diff --git a/aai-core/src/test/java/org/onap/aai/introspection/IntrospectorTestSpec.java b/aai-core/src/test/java/org/onap/aai/introspection/IntrospectorTestSpec.java new file mode 100644 index 00000000..d3a982d5 --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/introspection/IntrospectorTestSpec.java @@ -0,0 +1,59 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.introspection; + +import org.onap.aai.AAISetup; +import org.onap.aai.introspection.exceptions.AAIUnknownObjectException; + +import static org.junit.Assert.assertEquals; + +public class IntrospectorTestSpec extends AAISetup { + + + + /** + * Container test set. + * + * @param wrappedPortGroups the wrapped port groups + * @throws AAIUnknownObjectException + */ + protected void containerTestSet(Introspector wrappedPortGroups) throws AAIUnknownObjectException { + + assertEquals( + "isContainer", + true, + wrappedPortGroups.isContainer()); + + assertEquals( + "newInstanceOfNestedProperty", + "PortGroup", + wrappedPortGroups.newInstanceOfNestedProperty("port-group").getClass().getSimpleName()); + + assertEquals( + "isComplexGenericType", + true, + wrappedPortGroups.isComplexGenericType("port-group")); + + + } + +} diff --git a/aai-core/src/test/java/org/onap/aai/introspection/MoxyEngineTest.java b/aai-core/src/test/java/org/onap/aai/introspection/MoxyEngineTest.java new file mode 100644 index 00000000..e3c15fc2 --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/introspection/MoxyEngineTest.java @@ -0,0 +1,46 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.introspection; + +import org.junit.Test; +import org.onap.aai.introspection.exceptions.AAIUnknownObjectException; + +public class MoxyEngineTest extends IntrospectorTestSpec { + + /** + * Container object. + * @throws AAIUnknownObjectException + */ + @Test + public void containerObject() throws AAIUnknownObjectException { + + Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v9); + + Introspector obj = loader.introspectorFromName("port-groups"); + + this.containerTestSet(obj); + + } + + + +} diff --git a/aai-core/src/test/java/org/onap/aai/introspection/PojoInjestorTest.java b/aai-core/src/test/java/org/onap/aai/introspection/PojoInjestorTest.java new file mode 100644 index 00000000..4f78f7bd --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/introspection/PojoInjestorTest.java @@ -0,0 +1,60 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.introspection; + +import org.junit.Test; +import org.onap.aai.db.props.AAIProperties; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Marshaller; + +import static org.junit.Assert.*; + +public class PojoInjestorTest { + + @Test + public void getVersionTest() { + String latestVersion = "org.onap.aai.yang.VnfImage"; + PojoInjestor testPI = new PojoInjestor(); + assertEquals("", AAIProperties.LATEST, testPI.getVersion(latestVersion)); + + String oldVersion = "org.onap.aai.yang.v8.VnfImage"; + assertEquals("", Version.v8, testPI.getVersion(oldVersion)); + } + + @Test + public void getContextForVersionTest() { + PojoInjestor testPI = new PojoInjestor(); + JAXBContext context = testPI.getContextForVersion(Version.v9); + try { + Marshaller marshaller = context.createMarshaller(); + //this will fail if the context wasn't initialized successfully (I think) + marshaller.setProperty(org.eclipse.persistence.jaxb.MarshallerProperties.MEDIA_TYPE, "application/json"); + } catch (JAXBException e) { + e.printStackTrace(); + fail("failed on setting marshaller property"); + } + //if we get to here that means everything went ok + assertTrue(true); + } +} diff --git a/aai-core/src/test/java/org/onap/aai/introspection/PojoLoaderTest.java b/aai-core/src/test/java/org/onap/aai/introspection/PojoLoaderTest.java new file mode 100644 index 00000000..bcd809dd --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/introspection/PojoLoaderTest.java @@ -0,0 +1,53 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.introspection; + +import org.junit.Test; +import org.onap.aai.AAISetup; +import org.onap.aai.domain.yang.v9.VnfImage; +import org.onap.aai.introspection.exceptions.AAIUnmarshallingException; +import org.onap.aai.restcore.MediaType; + +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +public class PojoLoaderTest extends AAISetup { + + + @Test + public void test() { + Loader pojoLoader = LoaderFactory.createLoaderForVersion(ModelType.POJO, Version.v9); + String payload = "{\"vnf-image-uuid\":\"myuuid\",\"application\":\"testApp\",\"application-vendor\":\"testVendor\",\"application-version\":\"versionTest\"}"; + try { + Introspector intro = pojoLoader.unmarshal("vnf-image", payload, MediaType.APPLICATION_JSON_TYPE); + VnfImage myVnfImage = (VnfImage) intro.getUnderlyingObject(); + assertTrue("myuuid".equals(myVnfImage.getVnfImageUuid())); + assertTrue("testApp".equals(myVnfImage.getApplication())); + assertTrue("testVendor".equals(myVnfImage.getApplicationVendor())); + assertTrue("versionTest".equals(myVnfImage.getApplicationVersion())); + } catch (AAIUnmarshallingException e) { + e.printStackTrace(); + fail("AAIUnmarshallingException thrown"); + } + } + +} diff --git a/aai-core/src/test/java/org/onap/aai/introspection/PojoStrategyTest.java b/aai-core/src/test/java/org/onap/aai/introspection/PojoStrategyTest.java new file mode 100644 index 00000000..66832704 --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/introspection/PojoStrategyTest.java @@ -0,0 +1,44 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.introspection; + +import org.junit.Test; +import org.onap.aai.domain.yang.CloudRegion; +import org.onap.aai.domain.yang.VolumeGroup; +import org.onap.aai.schema.enums.ObjectMetadata; + +import static org.junit.Assert.assertEquals; + +public class PojoStrategyTest { + + @Test + public void getMetadataTest() { + Introspector cloudregion = IntrospectorFactory.newInstance(ModelType.POJO, new CloudRegion()); + assertEquals("cloud-infrastructure", cloudregion.getMetadata(ObjectMetadata.NAMESPACE)); + assertEquals("cloud-regions", cloudregion.getMetadata(ObjectMetadata.CONTAINER)); + + Introspector volumegroup = IntrospectorFactory.newInstance(ModelType.POJO, new VolumeGroup()); + assertEquals("cloud-region", volumegroup.getMetadata(ObjectMetadata.DEPENDENT_ON)); + assertEquals("", volumegroup.getMetadata(ObjectMetadata.NAMESPACE)); + } + +} diff --git a/aai-core/src/test/java/org/onap/aai/introspection/PropertyPredicatesTest.java b/aai-core/src/test/java/org/onap/aai/introspection/PropertyPredicatesTest.java new file mode 100644 index 00000000..0250bbb3 --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/introspection/PropertyPredicatesTest.java @@ -0,0 +1,75 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.introspection; + +import org.junit.Before; +import org.junit.Test; +import org.onap.aai.AAISetup; +import org.onap.aai.introspection.exceptions.AAIUnknownObjectException; + +import java.util.Set; + +import static org.hamcrest.Matchers.hasItems; +import static org.hamcrest.Matchers.not; +import static org.junit.Assert.assertThat; + +public class PropertyPredicatesTest extends AAISetup { + + private final Version version = Version.getLatest(); + + private Loader loader; + private ModelType introspectorFactoryType = ModelType.MOXY; + private Introspector obj; + + @Before + public void setup() throws Exception { + loader = LoaderFactory.createLoaderForVersion(introspectorFactoryType, version); + obj = loader.introspectorFromName("test-object"); + } + + @Test + public void includeInTestGeneration() throws AAIUnknownObjectException { + + Set props = obj.getProperties(PropertyPredicates.includeInTestGeneration()); + + assertThat("props not found", props, + not(hasItems("persona-model-ver", "not-visible-test-element", "model-invariant-id", "model-version-id"))); + } + + @Test + public void isVisible() throws AAIUnknownObjectException { + + Set props = obj.getProperties(PropertyPredicates.isVisible()); + + assertThat("props not found", props, not(hasItems("persona-model-ver"))); + } + + @Test + public void all() throws AAIUnknownObjectException { + + Set props = obj.getProperties(); + + assertThat("all found", props, hasItems("persona-model-ver", "not-visible-test-element")); + } + + +} diff --git a/aai-core/src/test/java/org/onap/aai/introspection/ReflectionEngineTest.java b/aai-core/src/test/java/org/onap/aai/introspection/ReflectionEngineTest.java new file mode 100644 index 00000000..6869fd71 --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/introspection/ReflectionEngineTest.java @@ -0,0 +1,47 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.introspection; + +import org.junit.Test; +import org.onap.aai.introspection.exceptions.AAIUnknownObjectException; + +public class ReflectionEngineTest extends IntrospectorTestSpec { + + /** + * Container object. + * + * @throws InstantiationException the instantiation exception + * @throws IllegalAccessException the illegal access exception + * @throws ClassNotFoundException the class not found exception + * @throws AAIUnknownObjectException + */ + @Test + public void containerObject() throws InstantiationException, IllegalAccessException, ClassNotFoundException, AAIUnknownObjectException { + Object javaObj = null; + String className = "org.onap.aai.domain.yang.PortGroups"; + javaObj = Class.forName(className).newInstance(); + + Introspector obj = IntrospectorFactory.newInstance(ModelType.POJO, javaObj); + +// this.containerTestSet(obj); + } +} diff --git a/aai-core/src/test/java/org/onap/aai/introspection/sideeffect/DataCopyTest.java b/aai-core/src/test/java/org/onap/aai/introspection/sideeffect/DataCopyTest.java new file mode 100644 index 00000000..7dbf2392 --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/introspection/sideeffect/DataCopyTest.java @@ -0,0 +1,268 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.introspection.sideeffect; + +import com.thinkaurelius.titan.core.TitanFactory; +import com.thinkaurelius.titan.core.TitanGraph; +import org.apache.commons.io.IOUtils; +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; +import org.apache.tinkerpop.gremlin.structure.Graph; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.apache.tinkerpop.gremlin.structure.VertexProperty; +import org.junit.*; +import org.junit.rules.ExpectedException; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.aai.db.props.AAIProperties; +import org.onap.aai.dbmap.DBConnectionType; +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.*; +import org.onap.aai.introspection.sideeffect.exceptions.AAIMissingRequiredPropertyException; +import org.onap.aai.parsers.query.QueryParser; +import org.onap.aai.serialization.db.DBSerializer; +import org.onap.aai.serialization.db.EdgeProperty; +import org.onap.aai.serialization.engines.QueryStyle; +import org.onap.aai.serialization.engines.TitanDBEngine; +import org.onap.aai.serialization.engines.TransactionalGraphEngine; + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.lang.reflect.InvocationTargetException; +import java.net.MalformedURLException; +import java.net.URISyntaxException; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + +public class DataCopyTest { + + private static TitanGraph graph; + private final static Version version = Version.getLatest(); + private final static ModelType introspectorFactoryType = ModelType.MOXY; + private final static QueryStyle queryStyle = QueryStyle.TRAVERSAL; + private final static DBConnectionType type = DBConnectionType.REALTIME; + private static Loader loader; + private static TransactionalGraphEngine dbEngine; + @Mock private Vertex self; + @Mock private VertexProperty prop; + @Mock private QueryParser uriQuery; + @Rule + public ExpectedException thrown = ExpectedException.none(); + + + @BeforeClass + public static void setup() throws NoSuchFieldException, SecurityException, Exception { + graph = TitanFactory.build().set("storage.backend","inmemory").open(); + System.setProperty("AJSC_HOME", "."); + System.setProperty("BUNDLECONFIG_DIR", "src/test/resources/bundleconfig-local"); + loader = LoaderFactory.createLoaderForVersion(introspectorFactoryType, version); + dbEngine = new TitanDBEngine( + queryStyle, + type, + loader); + + graph.traversal().addV("aai-node-type", "model", "model-invariant-id", "key1").as("v1") + .addV("aai-node-type", "model-ver", "model-ver", "myValue", "model-version-id", "key2", "model-version", "testValue").addInE("has", "v1", EdgeProperty.CONTAINS.toString(), true) + .addV("aai-node-type", "model", "model-invariant-id", "key3").as("v2") + .addV("aai-node-type", "model-ver", "model-ver", "myValue", "model-version-id", "key4").addInE("has", "v2", EdgeProperty.CONTAINS.toString(), true) + .next(); + graph.tx().commit(); + } + + @AfterClass + public static void tearDown() { + graph.tx().rollback(); + graph.close(); + } + + @Before + public void initMock() { + MockitoAnnotations.initMocks(this); + } + + @Test + public void runPopulatePersonaModelVer() throws URISyntaxException, AAIException, UnsupportedEncodingException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException, InstantiationException, NoSuchMethodException, MalformedURLException { + + final Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.getLatest()); + final Introspector obj = loader.introspectorFromName("test-object"); + obj.setValue("vnf-id", "myId"); + obj.setValue("model-invariant-id", "key1"); + obj.setValue("model-version-id", "key2"); + TransactionalGraphEngine spy = spy(dbEngine); + TransactionalGraphEngine.Admin adminSpy = spy(dbEngine.asAdmin()); + Graph g = graph.newTransaction(); + GraphTraversalSource traversal = g.traversal(); + when(spy.asAdmin()).thenReturn(adminSpy); + when(adminSpy.getTraversalSource()).thenReturn(traversal); + when(self.property(AAIProperties.AAI_URI)).thenReturn(prop); + when(prop.orElse(null)).thenReturn(obj.getURI()); + DBSerializer serializer = new DBSerializer(version, spy, introspectorFactoryType, "AAI_TEST"); + SideEffectRunner runner = new SideEffectRunner + .Builder(spy, serializer).addSideEffect(DataCopy.class).build(); + + runner.execute(obj, self); + + assertEquals("value populated", "testValue", obj.getValue("persona-model-ver")); + + g.tx().rollback(); + + + } + + @Test + public void runPopulateModelVersionId() throws URISyntaxException, AAIException, UnsupportedEncodingException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException, InstantiationException, NoSuchMethodException, MalformedURLException { + + final Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v9); + final Introspector obj = loader.introspectorFromName("test-object"); + obj.setValue("vnf-id", "myId"); + obj.setValue("persona-model-id", "key1"); + obj.setValue("persona-model-version", "testValue"); + TransactionalGraphEngine spy = spy(dbEngine); + TransactionalGraphEngine.Admin adminSpy = spy(dbEngine.asAdmin()); + Graph g = graph.newTransaction(); + GraphTraversalSource traversal = g.traversal(); + when(spy.asAdmin()).thenReturn(adminSpy); + when(adminSpy.getTraversalSource()).thenReturn(traversal); + when(self.property(AAIProperties.AAI_URI)).thenReturn(prop); + when(prop.orElse(null)).thenReturn(obj.getURI()); + DBSerializer serializer = new DBSerializer(version, spy, introspectorFactoryType, "AAI_TEST"); + SideEffectRunner runner = new SideEffectRunner + .Builder(spy, serializer).addSideEffect(DataCopy.class).build(); + + runner.execute(obj, self); + + assertEquals("value populated", "key2", obj.getValue("model-version-id")); + + g.tx().rollback(); + } + + @Test + public void verifyNestedSideEffect() throws URISyntaxException, AAIException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException, InstantiationException, NoSuchMethodException, IOException { + + final Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.getLatest()); + final Introspector obj = loader.unmarshal("customer", this.getJsonString("nested-case.json")); + System.out.println(obj.marshal(true)); + TransactionalGraphEngine spy = spy(dbEngine); + TransactionalGraphEngine.Admin adminSpy = spy(dbEngine.asAdmin()); + Graph g = graph.newTransaction(); + GraphTraversalSource traversal = g.traversal(); + when(spy.tx()).thenReturn(g); + when(spy.asAdmin()).thenReturn(adminSpy); + when(adminSpy.getTraversalSource()).thenReturn(traversal); + when(self.property(AAIProperties.AAI_URI)).thenReturn(prop); + when(prop.orElse(null)).thenReturn(obj.getURI()); + when(uriQuery.isDependent()).thenReturn(false); + DBSerializer serializer = new DBSerializer(version, spy, introspectorFactoryType, "AAI_TEST"); + Vertex v= serializer.createNewVertex(obj); + serializer.serializeToDb(obj, v, uriQuery, obj.getURI(), "test"); + + assertEquals("nested value populated", "testValue", g.traversal().V().has("service-instance-id", "nested-instance-key").next().property("persona-model-version").orElse("")); + + g.tx().rollback(); + + } + + @Test + public void expectedMissingPropertyExceptionInURI() throws AAIException, UnsupportedEncodingException { + + final Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.getLatest()); + final Introspector obj = loader.introspectorFromName("test-object"); + obj.setValue("vnf-id", "myId"); + obj.setValue("model-invariant-id", "key1"); + + TransactionalGraphEngine spy = spy(dbEngine); + TransactionalGraphEngine.Admin adminSpy = spy(dbEngine.asAdmin()); + Graph g = graph.newTransaction(); + GraphTraversalSource traversal = g.traversal(); + when(spy.asAdmin()).thenReturn(adminSpy); + when(adminSpy.getTraversalSource()).thenReturn(traversal); + when(self.property(AAIProperties.AAI_URI)).thenReturn(prop); + when(prop.orElse(null)).thenReturn(obj.getURI()); + DBSerializer serializer = new DBSerializer(version, spy, introspectorFactoryType, "AAI_TEST"); + SideEffectRunner runner = new SideEffectRunner + .Builder(spy, serializer).addSideEffect(DataCopy.class).build(); + + thrown.expect(AAIMissingRequiredPropertyException.class); + runner.execute(obj, self); + } + + @Test + public void expectedMissingPropertyExceptionForResultingObject() throws AAIException, UnsupportedEncodingException { + final Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.getLatest()); + final Introspector obj = loader.introspectorFromName("test-object"); + obj.setValue("vnf-id", "myId"); + obj.setValue("model-invariant-id", "key3"); + obj.setValue("model-version-id", "key4"); + + TransactionalGraphEngine spy = spy(dbEngine); + TransactionalGraphEngine.Admin adminSpy = spy(dbEngine.asAdmin()); + Graph g = graph.newTransaction(); + GraphTraversalSource traversal = g.traversal(); + when(spy.asAdmin()).thenReturn(adminSpy); + when(adminSpy.getTraversalSource()).thenReturn(traversal); + when(self.property(AAIProperties.AAI_URI)).thenReturn(prop); + when(prop.orElse(null)).thenReturn(obj.getURI()); + DBSerializer serializer = new DBSerializer(version, spy, introspectorFactoryType, "AAI_TEST"); + SideEffectRunner runner = new SideEffectRunner + .Builder(spy, serializer).addSideEffect(DataCopy.class).build(); + + thrown.expect(AAIMissingRequiredPropertyException.class); + runner.execute(obj, self); + } + + @Test + public void expectNoProcessingWithNoProperties() throws AAIException, UnsupportedEncodingException { + final Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.getLatest()); + final Introspector obj = loader.introspectorFromName("test-object"); + obj.setValue("vnf-id", "myId"); + + TransactionalGraphEngine spy = spy(dbEngine); + TransactionalGraphEngine.Admin adminSpy = spy(dbEngine.asAdmin()); + Graph g = graph.newTransaction(); + GraphTraversalSource traversal = g.traversal(); + when(spy.asAdmin()).thenReturn(adminSpy); + when(adminSpy.getTraversalSource()).thenReturn(traversal); + when(self.property(AAIProperties.AAI_URI)).thenReturn(prop); + when(prop.orElse(null)).thenReturn(obj.getURI()); + DBSerializer serializer = new DBSerializer(version, spy, introspectorFactoryType, "AAI_TEST"); + SideEffectRunner runner = new SideEffectRunner + .Builder(spy, serializer).addSideEffect(DataCopy.class).build(); + + runner.execute(obj, self); + + assertEquals("no model-version-id", true, obj.getValue("model-version-id") == null); + assertEquals("no model-invariant-id", true, obj.getValue("model-invariant-id") == null); + + } + + private String getJsonString(String filename) throws IOException { + + + FileInputStream is = new FileInputStream("src/test/resources/bundleconfig-local/etc/oxm/sideeffect/" + filename); + String s = IOUtils.toString(is, "UTF-8"); + IOUtils.closeQuietly(is); + + return s; + } +} diff --git a/aai-core/src/test/java/org/onap/aai/introspection/sideeffect/DataLinkTest.java b/aai-core/src/test/java/org/onap/aai/introspection/sideeffect/DataLinkTest.java new file mode 100644 index 00000000..b817cc69 --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/introspection/sideeffect/DataLinkTest.java @@ -0,0 +1,259 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.introspection.sideeffect; + +import com.thinkaurelius.titan.core.TitanFactory; +import com.thinkaurelius.titan.core.TitanGraph; +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; +import org.apache.tinkerpop.gremlin.structure.Graph; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.apache.tinkerpop.gremlin.structure.VertexProperty; +import org.junit.*; +import org.junit.rules.ExpectedException; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.aai.db.props.AAIProperties; +import org.onap.aai.dbmap.DBConnectionType; +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.*; +import org.onap.aai.parsers.query.QueryParser; +import org.onap.aai.serialization.db.DBSerializer; +import org.onap.aai.serialization.db.EdgeProperty; +import org.onap.aai.serialization.engines.QueryStyle; +import org.onap.aai.serialization.engines.TitanDBEngine; +import org.onap.aai.serialization.engines.TransactionalGraphEngine; + +import java.io.UnsupportedEncodingException; +import java.lang.reflect.InvocationTargetException; +import java.net.MalformedURLException; +import java.net.URISyntaxException; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + +public class DataLinkTest { + + private static TitanGraph graph; + private final static Version version = Version.getLatest(); + private final static ModelType introspectorFactoryType = ModelType.MOXY; + private final static QueryStyle queryStyle = QueryStyle.TRAVERSAL; + private final static DBConnectionType type = DBConnectionType.REALTIME; + private static Loader loader; + private static TransactionalGraphEngine dbEngine; + @Mock private QueryParser parser; + @Mock private Vertex self; + @Mock private VertexProperty prop; + @Rule + public ExpectedException thrown = ExpectedException.none(); + + + @BeforeClass + public static void setup() throws NoSuchFieldException, SecurityException, Exception { + graph = TitanFactory.build().set("storage.backend","inmemory").open(); + System.setProperty("AJSC_HOME", "."); + System.setProperty("BUNDLECONFIG_DIR", "src/test/resources/bundleconfig-local"); + loader = LoaderFactory.createLoaderForVersion(introspectorFactoryType, version); + dbEngine = new TitanDBEngine( + queryStyle, + type, + loader); + + graph.traversal().addV("aai-node-type", "vpn-binding", "vpn-id", "addKey").as("v1") + .addV("aai-node-type", "vpn-binding", "vpn-id", "modifyKey").as("v2") + .addV("aai-node-type", "route-target", "global-route-target", "modifyTargetKey", "route-target-role", "modifyRoleKey", "linked", true).addInE("has", "v2", EdgeProperty.CONTAINS.toString(), true) + .addV("aai-node-type", "vpn-binding", "vpn-id", "deleteKey").as("v3") + .addV("aai-node-type", "route-target", "global-route-target", "deleteTargetKey", "route-target-role", "deleteRoleKey", "linked", true).addInE("has", "v3", EdgeProperty.CONTAINS.toString(), true) + .addV("aai-node-type", "vpn-binding", "vpn-id", "getKey").as("v4") + .addV("aai-node-type", "route-target", "global-route-target", "getTargetKey", "route-target-role", "getRoleKey", "linked", true).addInE("has", "v4", EdgeProperty.CONTAINS.toString(), true) + .addV("aai-node-type", "vpn-binding", "vpn-id", "getKeyNoLink").as("v5") + .addV("aai-node-type", "route-target", "global-route-target", "getTargetKeyNoLink", "route-target-role", "getRoleKeyNoLink").addInE("has", "v5", EdgeProperty.CONTAINS.toString(), true) + .next(); + graph.tx().commit(); + } + + @AfterClass + public static void tearDown() { + graph.tx().rollback(); + graph.close(); + } + + @Before + public void initMock() { + MockitoAnnotations.initMocks(this); + } + + @Test + public void verifyCreationOfVertex() throws URISyntaxException, AAIException, UnsupportedEncodingException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException, InstantiationException, NoSuchMethodException, MalformedURLException { + + final Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v9); + final Introspector obj = loader.introspectorFromName("vpn-binding"); + obj.setValue("vpn-id", "addKey"); + obj.setValue("global-route-target", "key1"); + obj.setValue("route-target-role", "key2"); + TransactionalGraphEngine spy = spy(dbEngine); + TransactionalGraphEngine.Admin adminSpy = spy(dbEngine.asAdmin()); + Graph g = graph.newTransaction(); + GraphTraversalSource traversal = g.traversal(); + when(spy.asAdmin()).thenReturn(adminSpy); + when(adminSpy.getTraversalSource()).thenReturn(traversal); + when(spy.tx()).thenReturn(g); + when(self.property(AAIProperties.AAI_URI)).thenReturn(prop); + when(prop.orElse(null)).thenReturn(obj.getURI()); + DBSerializer serializer = new DBSerializer(version, spy, introspectorFactoryType, "AAI_TEST"); + SideEffectRunner runner = new SideEffectRunner + .Builder(spy, serializer).addSideEffect(DataLinkWriter.class).build(); + + runner.execute(obj, self); + + assertEquals("route-target vertex found", true, traversal.V() + .has(AAIProperties.NODE_TYPE, "route-target").has("global-route-target", "key1").has("route-target-role", "key2").has("linked", true).hasNext()); + + g.tx().rollback(); + + } + + @Test + public void verifyModificationOfVertex() throws URISyntaxException, AAIException, UnsupportedEncodingException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException, InstantiationException, NoSuchMethodException, MalformedURLException { + + final Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v9); + final Introspector obj = loader.introspectorFromName("vpn-binding"); + obj.setValue("vpn-id", "modifyKey"); + obj.setValue("global-route-target", "modifyTargetKey2"); + obj.setValue("route-target-role", "modifyRoleKey2"); + TransactionalGraphEngine spy = spy(dbEngine); + TransactionalGraphEngine.Admin adminSpy = spy(dbEngine.asAdmin()); + Graph g = graph.newTransaction(); + GraphTraversalSource traversal = g.traversal(); + when(spy.asAdmin()).thenReturn(adminSpy); + when(adminSpy.getTraversalSource()).thenReturn(traversal); + when(spy.tx()).thenReturn(g); + when(self.property(AAIProperties.AAI_URI)).thenReturn(prop); + when(prop.orElse(null)).thenReturn(obj.getURI()); + DBSerializer serializer = new DBSerializer(version, spy, introspectorFactoryType, "AAI_TEST"); + SideEffectRunner runner = new SideEffectRunner + .Builder(spy, serializer).addSideEffect(DataLinkWriter.class).build(); + + runner.execute(obj, self); + + assertEquals("route-target vertex found", true, traversal.V() + .has(AAIProperties.NODE_TYPE, "route-target").has("global-route-target", "modifyTargetKey2").has("route-target-role", "modifyRoleKey2").has("linked", true).hasNext()); + assertEquals("previous link removed", true, traversal.V() + .has(AAIProperties.NODE_TYPE, "route-target").has("global-route-target", "modifyTargetKey").has("route-target-role", "modifyRoleKey").hasNot("linked").hasNext()); + g.tx().rollback(); + + } + + @Test + public void verifyDeleteOfVertex() throws URISyntaxException, AAIException, UnsupportedEncodingException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException, InstantiationException, NoSuchMethodException, MalformedURLException { + + final Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v9); + final Introspector obj = loader.introspectorFromName("vpn-binding"); + obj.setValue("vpn-id", "deleteKey"); + TransactionalGraphEngine spy = spy(dbEngine); + TransactionalGraphEngine.Admin adminSpy = spy(dbEngine.asAdmin()); + Graph g = graph.newTransaction(); + GraphTraversalSource traversal = g.traversal(); + when(spy.asAdmin()).thenReturn(adminSpy); + when(adminSpy.getTraversalSource()).thenReturn(traversal); + when(adminSpy.getReadOnlyTraversalSource()).thenReturn(traversal); + when(spy.tx()).thenReturn(g); + when(self.property(AAIProperties.AAI_URI)).thenReturn(prop); + when(prop.orElse(null)).thenReturn(obj.getURI()); + DBSerializer serializer = new DBSerializer(version, spy, introspectorFactoryType, "AAI_TEST"); + SideEffectRunner runner = new SideEffectRunner + .Builder(spy, serializer).addSideEffect(DataLinkWriter.class).build(); + + runner.execute(obj, self); + + assertEquals("route-target vertex not found", false, traversal.V() + .has(AAIProperties.NODE_TYPE, "route-target").has("global-route-target", "deleteTargetKey").has("route-target-role", "deleteRoleKey").has("linked", true).hasNext()); + g.tx().rollback(); + + } + + @Test + public void verifyPropertyPopulation() throws URISyntaxException, AAIException, UnsupportedEncodingException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException, InstantiationException, NoSuchMethodException, MalformedURLException { + + final Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v9); + final Introspector obj = loader.introspectorFromName("vpn-binding"); + obj.setValue("vpn-id", "getKey"); + TransactionalGraphEngine spy = spy(dbEngine); + TransactionalGraphEngine.Admin adminSpy = spy(dbEngine.asAdmin()); + Graph g = graph.newTransaction(); + GraphTraversalSource traversal = g.traversal(); + when(spy.asAdmin()).thenReturn(adminSpy); + when(adminSpy.getTraversalSource()).thenReturn(traversal); + when(spy.tx()).thenReturn(g); + when(self.property(AAIProperties.AAI_URI)).thenReturn(prop); + when(prop.orElse(null)).thenReturn(obj.getURI()); + DBSerializer serializer = new DBSerializer(version, spy, introspectorFactoryType, "AAI_TEST"); + SideEffectRunner runner = new SideEffectRunner + .Builder(spy, serializer).addSideEffect(DataLinkReader.class).build(); + + runner.execute(obj, self); + + assertEquals("both properties have been populated in target object", true, obj.getValue("global-route-target").equals("getTargetKey") && obj.getValue("route-target-role").equals("getRoleKey")); + g.tx().rollback(); + + } + + @Test + public void verifyPropertyPopulationWithV10OnlyPut() throws URISyntaxException, AAIException, UnsupportedEncodingException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException, InstantiationException, NoSuchMethodException, MalformedURLException { + final Introspector obj = loader.introspectorFromName("vpn-binding"); + obj.setValue("vpn-id", "getKeyNoLink"); + final Introspector routeTargets = loader.introspectorFromName("route-targets"); + obj.setValue("route-targets", routeTargets.getUnderlyingObject()); + List targets = routeTargets.getValue("route-target"); + final Introspector routeTargetOne = loader.introspectorFromName("route-target"); + routeTargetOne.setValue("global-route-target", "getTargetKeyNoLink"); + routeTargetOne.setValue("route-target-role", "getRoleKeyNoLink"); + targets.add(routeTargetOne.getUnderlyingObject()); + final Introspector routeTargetTwo = loader.introspectorFromName("route-target"); + routeTargetTwo.setValue("global-route-target", "getTargetKeyNoLink2"); + routeTargetTwo.setValue("route-target-role", "getRoleKeyNoLink2"); + targets.add(routeTargetTwo.getUnderlyingObject()); + TransactionalGraphEngine spy = spy(dbEngine); + TransactionalGraphEngine.Admin adminSpy = spy(dbEngine.asAdmin()); + Graph g = graph.newTransaction(); + GraphTraversalSource traversal = g.traversal(); + when(spy.tx()).thenReturn(g); + when(spy.asAdmin()).thenReturn(adminSpy); + when(adminSpy.getTraversalSource()).thenReturn(traversal); + when(spy.tx()).thenReturn(g); + when(parser.isDependent()).thenReturn(false); + when(self.property(AAIProperties.AAI_URI)).thenReturn(prop); + when(prop.orElse(null)).thenReturn(obj.getURI()); + DBSerializer serializer = new DBSerializer(version, spy, introspectorFactoryType, "AAI_TEST"); + Vertex v = serializer.createNewVertex(obj); + serializer.serializeToDb(obj, v, parser, obj.getURI(), "testing"); + Vertex routeTargetOneV = traversal.V().has("global-route-target", "getTargetKeyNoLink").next(); + Vertex routeTargetTwoV = traversal.V().has("global-route-target", "getTargetKeyNoLink2").next(); + + assertEquals("first route target put has linked", true, routeTargetOneV.property(AAIProperties.LINKED).orElse(false)); + assertEquals("second route target put does not have linked", false, routeTargetTwoV.property(AAIProperties.LINKED).orElse(false)); + + g.tx().rollback(); + + } +} diff --git a/aai-core/src/test/java/org/onap/aai/introspection/validation/IntrospectorValidationTest.java b/aai-core/src/test/java/org/onap/aai/introspection/validation/IntrospectorValidationTest.java new file mode 100644 index 00000000..db21f578 --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/introspection/validation/IntrospectorValidationTest.java @@ -0,0 +1,96 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.introspection.validation; + +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.*; +import org.onap.aai.introspection.tools.IntrospectorValidator; +import org.onap.aai.introspection.tools.Issue; +import org.onap.aai.introspection.tools.IssueType; +import org.onap.aai.serialization.queryformats.QueryFormatTestHelper; +import org.onap.aai.util.AAIConstants; + +import java.util.List; + +import static org.junit.Assert.assertEquals; + +public class IntrospectorValidationTest { + + + private final static Version version = Version.v10; + private final static ModelType introspectorFactoryType = ModelType.MOXY; + private static Loader loader; + private IntrospectorValidator validator; + @BeforeClass + public static void setUp() throws NoSuchFieldException, SecurityException, Exception { + System.setProperty("AJSC_HOME", "."); + System.setProperty("BUNDLECONFIG_DIR", "bundleconfig-local"); + QueryFormatTestHelper.setFinalStatic(AAIConstants.class.getField("AAI_HOME_ETC_OXM"), "src/test/resources/org.onap.aai/introspection/"); + + loader = LoaderFactory.createLoaderForVersion(introspectorFactoryType, version); + + } + @Before + public void createValidator() { + validator = new IntrospectorValidator.Builder() + .validateRequired(false) + .restrictDepth(10000) + .build(); + } + @Ignore + @Test + public void verifySuccessWhenEmpty() throws AAIException { + Introspector obj = loader.introspectorFromName("test-object"); + obj.setValue("vnf-id", "key1"); + validator.validate(obj); + List issues = validator.getIssues(); + assertEquals("no issues found", true, issues.isEmpty()); + } + + @Ignore + @Test + public void verifyRequiresSingleFieldFailure() throws AAIException { + Introspector obj = loader.introspectorFromName("test-object"); + obj.setValue("vnf-id", "key1"); + obj.setValue("model-invariant-id", "id1"); + validator.validate(obj); + List issues = validator.getIssues(); + assertEquals("issues found", true, issues.size() == 1); + Issue issue = issues.get(0); + assertEquals("found expected issue", IssueType.DEPENDENT_PROP_NOT_FOUND, issue.getType()); + } + @Ignore + @Test + public void verifyRequiresSuccess() throws AAIException { + Introspector obj = loader.introspectorFromName("test-object"); + obj.setValue("vnf-id", "key1"); + obj.setValue("model-invariant-id", "id1"); + obj.setValue("model-version-id", "version-id1"); + validator.validate(obj); + List issues = validator.getIssues(); + assertEquals("no issues found", true, issues.isEmpty()); + } +} diff --git a/aai-core/src/test/java/org/onap/aai/logging/CNNameTest.java b/aai-core/src/test/java/org/onap/aai/logging/CNNameTest.java new file mode 100644 index 00000000..d5cd62cd --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/logging/CNNameTest.java @@ -0,0 +1,138 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.logging; + +import ch.qos.logback.access.spi.IAccessEvent; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.onap.aai.logging.CNName; +import org.onap.aai.serialization.queryformats.QueryFormatTestHelper; +import org.onap.aai.util.AAIConstants; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.agent.PowerMockAgent; + +import javax.security.auth.x500.X500Principal; +import javax.servlet.http.HttpServletRequest; +import java.security.cert.X509Certificate; + +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; + +@PowerMockIgnore("javax.security.auth.x500.X500Principal") +@PrepareForTest({IAccessEvent.class, HttpServletRequest.class, X509Certificate.class}) +public class CNNameTest { + + static { + PowerMockAgent.initializeIfNeeded(); + } + + + IAccessEvent mockAccEvent; + HttpServletRequest mockHttpServletRequest; + CNName cnname; + X509Certificate cert; + + /** + * Initialize. + */ + @Before + public void initialize() throws Exception { + System.setProperty("AJSC_HOME", "."); + System.setProperty("BUNDLECONFIG_DIR", "src/test/resources/bundleconfig-local"); + QueryFormatTestHelper.setFinalStatic(AAIConstants.class.getField("AAI_HOME_ETC_OXM"), "src/test/resources/bundleconfig-local/etc/oxm/"); + mockAccEvent = Mockito.mock(IAccessEvent.class); + mockHttpServletRequest = Mockito.mock(HttpServletRequest.class); + cert = Mockito.mock(X509Certificate.class); + } + + + /** + * Test 'convert' when there is no AccessConverter. + */ + @Test + public void testConvert_withoutAccessConverter(){ + cnname = getTestObj(false); + assertTrue("Conversion failed with no AccessConverter", "INACTIVE_HEADER_CONV".equals(cnname.convert(mockAccEvent))); + } + + /** + * Test 'convert' with no CipherSuite. + */ + @Test + public void testConvert_withNullCipherSuite(){ + setupForCipherSuite(null); + assertTrue("Conversion failed for a null CipherSuite", "-".equals(cnname.convert(mockAccEvent))); + } + + + /** + * Test 'convert' with a non-null CipherSuite. + */ + @Test + public void testConvert_withNotNullCipherSuite(){ + + setupForCipherSuite("StrRepOfAValidSuite"); + + final X500Principal principal = new X500Principal("CN=AAI, OU=DOX, O=BWS, C=CA"); + + Mockito.when(cert.getSubjectX500Principal()).thenReturn(principal); + + final X509Certificate[] certChain = {cert}; + + when(mockHttpServletRequest.getAttribute("javax.servlet.request.X509Certificate")).thenReturn(certChain); + + assertTrue("Conversion failed for a valid CipherSuite", principal.toString().equals(cnname.convert(mockAccEvent))); + } + + + /** + * Helper method to mock IAccessEvent and HttpServletRequest. + * + * @param suite CipherSuite to be used in current test + */ + private void setupForCipherSuite(String suite){ + cnname = getTestObj(true); + when(mockAccEvent.getRequest()).thenReturn(mockHttpServletRequest); + when(mockHttpServletRequest.getAttribute("javax.servlet.request.cipher_suite")).thenReturn(suite); + } + + + /** + * Helper method to create a CNName object with overridden 'start status' . + * + * @param instanceStarted Start status to be used + * @return CNName object to test + */ + private CNName getTestObj(final boolean instanceStarted){ + return new CNName(){ + @Override + public boolean isStarted(){ + return instanceStarted; + } + }; + } +} + + + diff --git a/aai-core/src/test/java/org/onap/aai/logging/CustomLogPatternLayoutTest.java b/aai-core/src/test/java/org/onap/aai/logging/CustomLogPatternLayoutTest.java new file mode 100644 index 00000000..04aaaf0f --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/logging/CustomLogPatternLayoutTest.java @@ -0,0 +1,52 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.logging; + +import org.junit.Test; +import org.onap.aai.logging.CNName; +import org.onap.aai.logging.CustomLogPatternLayout; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class CustomLogPatternLayoutTest { + + /** + * Test null when defaultConverterMap doesn't have corresponding entry. + */ + @Test + public void testNull(){ + String s = CustomLogPatternLayout.defaultConverterMap.get("z"); + assertFalse("Entry not found for key 'z'", CNName.class.getName().equals(s)); + } + + /** + * Test defaultConverterMap when valid entry exists. + */ + @Test + public void testEntryFor_Z(){ + CustomLogPatternLayout layout = new CustomLogPatternLayout(); + String s = CustomLogPatternLayout.defaultConverterMap.get("z"); + assertTrue("Entry not found for key 'z'", CNName.class.getName().equals(s)); + } + +} diff --git a/aai-core/src/test/java/org/onap/aai/logging/DME2RestFlagTest.java b/aai-core/src/test/java/org/onap/aai/logging/DME2RestFlagTest.java new file mode 100644 index 00000000..59177efe --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/logging/DME2RestFlagTest.java @@ -0,0 +1,83 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.logging; +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; +import ch.qos.logback.access.spi.IAccessEvent; +import org.junit.*; + + +public class DME2RestFlagTest { + + IAccessEvent mockAccEvent; + DME2RestFlag _DME2RestFlag; + + String[] temp = new String[4]; + + + @Before + public void setUp() throws Exception { + + mockAccEvent = mock(IAccessEvent.class); + _DME2RestFlag= spy(DME2RestFlag.class); + + } + private DME2RestFlag getTestObj(final boolean instanceStarted){ + return new DME2RestFlag(){ + @Override + public + boolean isStarted(){ + return instanceStarted; + } + }; + } + + @Test + public void convertTestAllValid(){ + temp[0]= "temp1"; + temp[1] = "-"; + when(mockAccEvent.getRequestParameter("envContext")).thenReturn(temp); + when(mockAccEvent.getRequestParameter("routeOffer")).thenReturn(temp); + when(mockAccEvent.getRequestParameter("version")).thenReturn(temp); + _DME2RestFlag = getTestObj(true); + assertEquals(_DME2RestFlag.convert(mockAccEvent),"DME2"); + } + + @Test + public void convertMissingRouteTest(){ + temp[0]= ""; + temp[1] = "-"; + when(mockAccEvent.getRequestParameter("envContext")).thenReturn(temp); + when(mockAccEvent.getRequestParameter("routeOffer")).thenReturn(temp); + when(mockAccEvent.getRequestParameter("version")).thenReturn(temp); + _DME2RestFlag = getTestObj(true); + assertEquals(_DME2RestFlag.convert(mockAccEvent),"REST"); + } + + @Test + public void convertIsStartedFalseTest(){ + _DME2RestFlag = getTestObj(false); + assertEquals(_DME2RestFlag.convert(mockAccEvent),"INACTIVE_HEADER_CONV"); + } + + +} diff --git a/aai-core/src/test/java/org/onap/aai/logging/EelfClassOfCallerTest.java b/aai-core/src/test/java/org/onap/aai/logging/EelfClassOfCallerTest.java new file mode 100644 index 00000000..adb29855 --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/logging/EelfClassOfCallerTest.java @@ -0,0 +1,71 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.logging; + +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; +import ch.qos.logback.classic.spi.ILoggingEvent; +import org.junit.*; + +public class EelfClassOfCallerTest { + + EelfClassOfCaller _eelfClassOfCaller; + ILoggingEvent mockEvent; + StackTraceElement[] cdafive = new StackTraceElement[5]; + StackTraceElement[] cdaone = new StackTraceElement[1]; + StackTraceElement[] cdazero = new StackTraceElement[0]; + + + @Before + public void setUp() throws Exception { + + mockEvent = mock(ILoggingEvent.class); + _eelfClassOfCaller= spy(EelfClassOfCaller.class); + + } + + + @Test + public void getFullyQualifiedNameCDALENFiveTest(){ + StackTraceElement temp = new StackTraceElement("classname_five","methodname","filename", 4); + cdafive[2]=temp; + when(mockEvent.getCallerData()).thenReturn(cdafive); + assertEquals(_eelfClassOfCaller.getFullyQualifiedName(mockEvent),"classname_five"); + + } + @Test + public void getFullyQualifiedNameCDALenOneTest(){ + StackTraceElement temp = new StackTraceElement("classname_one","methodname","filename", 4); + cdaone[0]=temp; + when(mockEvent.getCallerData()).thenReturn(cdaone); + assertEquals(_eelfClassOfCaller.getFullyQualifiedName(mockEvent),"classname_one"); + + } + + @Test + public void getFullyQualifiedNameCDALenZeroTest(){ + when(mockEvent.getCallerData()).thenReturn(cdazero); + assertEquals(_eelfClassOfCaller.getFullyQualifiedName(mockEvent),"?"); + + } + +} diff --git a/aai-core/src/test/java/org/onap/aai/logging/ErrorObjectTest.java b/aai-core/src/test/java/org/onap/aai/logging/ErrorObjectTest.java new file mode 100644 index 00000000..1a4c1857 --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/logging/ErrorObjectTest.java @@ -0,0 +1,163 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.logging; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; +import static org.junit.Assert.*; + +import org.junit.*; + +public class ErrorObjectTest { + + ErrorObject newErrorObject = new ErrorObject("disposition","category","severity", 200, "restErrorCode","errorCode","errorText"); + + //Constructor Tests + @Test + public void createObjectTest1(){ + //No HTTP Status argument + ErrorObject errorObject = new ErrorObject("severity","errorcode","errortext","disposition","category"); + assertNotNull(errorObject); + } + @Test + public void createObjectTest2(){ + //HTTP Status code as integer + ErrorObject errorObject = new ErrorObject("severity",200,"errorcode","errortext","disposition","category"); + assertNotNull(errorObject); + } + @Test + public void createObjectTest3(){ + //HTTP Status code as Status + ErrorObject errorObject = new ErrorObject("severity",Status.OK,"errorcode","errortext","disposition","category"); + assertNotNull(errorObject); + } + //Disposition Tests + @Test + public void getDispositionTest() { + assertEquals(newErrorObject.getDisposition(), "disposition"); + } + @Test + public void setDispositionTest() { + newErrorObject.setDisposition("newDisposition"); + assertEquals(newErrorObject.getDisposition(), "newDisposition"); + } + + //Category Tests + @Test + public void getCategoryTest(){ + assertEquals(newErrorObject.getCategory(), "category"); + } + @Test + public void setCategoryTest(){ + newErrorObject.setCategory("newCategory"); + assertEquals(newErrorObject.getCategory(), "newCategory"); + } + + //Severity Tests + @Test + public void getSeverityTest(){ + assertEquals(newErrorObject.getSeverity(), "severity"); + } + @Test + public void setSeverityTest(){ + newErrorObject.setSeverity("newSeverity"); + assertEquals(newErrorObject.getSeverity(), "newSeverity"); + } + + //Error Code Tests + @Test + public void getErrorCodeTest(){ + assertEquals(newErrorObject.getErrorCode(), "errorCode"); + } + @Test + public void SetErrorCodeTest(){ + newErrorObject.setErrorCode("newErrorCode"); + assertEquals(newErrorObject.getErrorCode(), "newErrorCode"); + } + + //HTTP Response Code Tests + @Test + public void getHTTPCodeTest(){ + assertEquals(newErrorObject.getHTTPResponseCode(), Status.OK); + } + @Test + public void setHTTPCodeTest(){ + newErrorObject.setHTTPResponseCode(201); + assertEquals(newErrorObject.getHTTPResponseCode(), Status.CREATED); + } + @Test(expected=IllegalArgumentException.class) + public void invalidHttpCodeTest(){ + newErrorObject.setHTTPResponseCode(6281723); + } + @Test(expected=IllegalArgumentException.class) + public void invalidHttpCodeTest2(){ + newErrorObject.setHTTPResponseCode("82901"); + } + + //Rest Error Code Tests + @Test + public void getRestErrorCodeTest(){ + assertEquals(newErrorObject.getRESTErrorCode(), "restErrorCode"); + } + @Test + public void setRestErrorCodeTest(){ + newErrorObject.setRESTErrorCode("newRestErrorCode"); + assertEquals(newErrorObject.getRESTErrorCode(), "newRestErrorCode"); + } + + //Error Text Tests + @Test + public void getErrorTextTest(){ + assertEquals(newErrorObject.getErrorText(), "errorText"); + } + @Test + public void setErrorTextTest(){ + newErrorObject.setErrorText("newErrorText"); + assertEquals(newErrorObject.getErrorText(), "newErrorText"); + } + @Test + public void getErrorCodeStringTest(){ + assertEquals(newErrorObject.getErrorCodeString(), "disposition.category.errorCode"); + } + @Test + public void getErrorCodeStringDisposition5Test(){ + //get Error Code String while Disposition = 5 + newErrorObject.setDisposition("5"); + assertEquals(newErrorObject.getErrorCodeString(), "ERR.5.category.errorCode"); + } + @Test + public void getSeverityCodeTest(){ + newErrorObject.setSeverity("WARN"); + assertEquals(newErrorObject.getSeverityCode(newErrorObject.getSeverity()), "1"); + + newErrorObject.setSeverity("ERROR"); + assertEquals(newErrorObject.getSeverityCode(newErrorObject.getSeverity()), "2"); + + newErrorObject.setSeverity("FATAL"); + assertEquals(newErrorObject.getSeverityCode(newErrorObject.getSeverity()), "3"); + } + //To String Test + @Test + public void toStringTest(){ + assertEquals(newErrorObject.toString(), "ErrorObject [errorCode=errorCode, errorText=errorText, restErrorCode=restErrorCode, httpResponseCode=OK, severity=severity, disposition=disposition, category=category]"); + } +} diff --git a/aai-core/src/test/java/org/onap/aai/logging/LoggingContextTest.java b/aai-core/src/test/java/org/onap/aai/logging/LoggingContextTest.java new file mode 100644 index 00000000..46ac5997 --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/logging/LoggingContextTest.java @@ -0,0 +1,108 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.logging; + +import org.junit.Test; + +import java.util.*; + +import static org.junit.Assert.*; + +public class LoggingContextTest { + + private static final int MAX_STORED_CONTEXTS = 100; + + @Test + public void testStopWatch() { + try { + LoggingContext.stopWatchStop(); + throw new AssertionError("No exception thrown when LoggingContext.stopWatchStop() called without a prior LoggingContext.stopWatchStart()"); + } catch (StopWatchNotStartedException e) { + //Expected + } + + LoggingContext.stopWatchStart(); + + assertTrue(LoggingContext.stopWatchStop() >= 0); + + try { + LoggingContext.stopWatchStop(); + throw new AssertionError("No exception thrown when LoggingContext.stopWatchStop() twice in succession"); + } catch (StopWatchNotStartedException e) { + //Expected + } + } + + @Test + public void testRequestId() { //AKA Transaction ID + final String sUuid = "57d51eaa-edc6-4f50-a69d-f2d4d2445120"; + + LoggingContext.requestId(sUuid); + + assertEquals(LoggingContext.requestId(), UUID.fromString(sUuid)); + + final UUID uuid = UUID.randomUUID(); + + LoggingContext.requestId(uuid); + + assertEquals(LoggingContext.requestId(), uuid); + + LoggingContext.requestId("foo"); //Illegal - this will result in a new, randomly + //generated UUID as per the logging spec + + assertNotNull(LoggingContext.requestId()); //Make sure ANY UUID was assigned + assertNotEquals(LoggingContext.requestId(), uuid); //Make sure it actually changed from the last + //known valid UUID + } + + @Test + public void testClear() { + LoggingContext.init(); + LoggingContext.clear(); + + assertEquals(Collections.emptyMap(), LoggingContext.getCopy()); + } + + @Test + public void testSaveRestore() { + + final Deque> contexts = new LinkedList> (); + + LoggingContext.init(); + + for (int i = 0; i < MAX_STORED_CONTEXTS; i++) { + LoggingContext.customField1(String.valueOf(i)); + + assertEquals(LoggingContext.customField1(), String.valueOf(i)); + + LoggingContext.save(); + + contexts.push(LoggingContext.getCopy()); + } + + while (contexts.peek() != null) { + LoggingContext.restore(); + + assertEquals(LoggingContext.getCopy(), contexts.pop()); + } + } +} diff --git a/aai-core/src/test/java/org/onap/aai/parsers/query/GraphTraversalTest.java b/aai-core/src/test/java/org/onap/aai/parsers/query/GraphTraversalTest.java new file mode 100644 index 00000000..df9d6122 --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/parsers/query/GraphTraversalTest.java @@ -0,0 +1,815 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.parsers.query; + +import org.apache.tinkerpop.gremlin.process.traversal.P; +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.onap.aai.AAISetup; +import org.onap.aai.db.props.AAIProperties; +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.LoaderFactory; +import org.onap.aai.introspection.ModelType; +import org.onap.aai.introspection.Version; +import org.onap.aai.rest.RestTokens; +import org.onap.aai.serialization.engines.QueryStyle; +import org.onap.aai.serialization.engines.TitanDBEngine; +import org.onap.aai.serialization.engines.TransactionalGraphEngine; + +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.UriBuilder; +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.util.ArrayList; +import java.util.List; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.Matchers.hasProperty; +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertEquals; + +public class GraphTraversalTest extends AAISetup { + + private TransactionalGraphEngine dbEngine; + private TransactionalGraphEngine dbEnginev9; + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + /** + * Configure. + * @throws Exception + * @throws SecurityException + * @throws NoSuchFieldException + */ + @Before + public void configure() throws Exception { + dbEngine = + new TitanDBEngine(QueryStyle.TRAVERSAL, + LoaderFactory.createLoaderForVersion(ModelType.MOXY, AAIProperties.LATEST), + false); + + dbEnginev9 = + new TitanDBEngine(QueryStyle.TRAVERSAL, + LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v9), + false); + } + + /** + * Parent query. + * + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void parentQuery() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("cloud-infrastructure/complexes/complex/key1").build(); + + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); + + GraphTraversal expected = __.start().has("physical-location-id", "key1").has("aai-node-type", "complex"); + assertEquals( + "gremlin query should be " + expected.toString(), + expected.toString(), + query.getQueryBuilder().getQuery().toString()); + assertEquals( + "parent gremlin query should be equal to normal query", + expected.toString(), + query.getQueryBuilder().getParentQuery().getQuery().toString()); + assertEquals( + "result type should be complex", + "complex", + query.getResultType()); + assertEquals( + "result type should be empty", + "", + query.getParentResultType()); + assertEquals("dependent",false, query.isDependent()); + + + } + + /** + * Child query. + * + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void childQuery() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("cloud-infrastructure/complexes/complex/key1/ctag-pools/ctag-pool/key2/key3").build(); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); + GraphTraversal expected = __.start() + .has("physical-location-id", "key1").has("aai-node-type", "complex") + .out("hasCtagPool") + .has("aai-node-type", "ctag-pool") + .has("target-pe", "key2").has("availability-zone-name", "key3"); + GraphTraversal expectedParent = __.start() + .has("physical-location-id", "key1").has("aai-node-type", "complex"); + assertEquals( + "gremlin query should be " + expected.toString(), + expected.toString(), + query.getQueryBuilder().getQuery().toString()); + assertEquals( + "parent gremlin query should be equal the query for complex", + expectedParent.toString(), + query.getQueryBuilder().getParentQuery().getQuery().toString()); + assertEquals( + "result type should be complex", + "complex", + query.getParentResultType()); + assertEquals( + "result type should be ctag-pool", + "ctag-pool", + query.getResultType()); + assertEquals("dependent",true, query.isDependent()); + + + } + + /** + * Naming exceptions. + * + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void namingExceptions() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags/cvlan-tag/655").build(); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); + GraphTraversal expected = __.start() + .has("vnf-id", "key1").has("aai-node-type", "vce") + .out("hasPortGroup") + .has("aai-node-type", "port-group") + .has("interface-id", "key2").out("hasCTag") + .has("aai-node-type", "cvlan-tag") + .has("cvlan-tag", 655); + GraphTraversal expectedParent = __.start() + .has("vnf-id", "key1").has("aai-node-type", "vce") + .out("hasPortGroup") + .has("aai-node-type", "port-group") + .has("interface-id", "key2"); + assertEquals( + "gremlin query should be " + expected.toString(), + expected.toString(), + query.getQueryBuilder().getQuery().toString()); + assertEquals( + "parent gremlin query should be equal the query for port group", + expectedParent.toString(), + query.getQueryBuilder().getParentQuery().getQuery().toString()); + assertEquals( + "result type should be cvlan-tag", + "cvlan-tag", + query.getResultType()); + assertEquals( + "result type should be port-group", + "port-group", + query.getParentResultType()); + assertEquals( + "contaner type should be empty", + "", + query.getContainerType()); + assertEquals("dependent",true, query.isDependent()); + + + } + + /** + * Gets the all. + * + * @return the all + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void getAll() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags").build(); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); + GraphTraversal expected = __.start() + .has("vnf-id", "key1").has("aai-node-type", "vce") + .out("hasPortGroup") + .has("aai-node-type", "port-group") + .has("interface-id", "key2").out("hasCTag") + .has("aai-node-type", "cvlan-tag"); + GraphTraversal expectedParent = __.start() + .has("vnf-id", "key1").has("aai-node-type", "vce") + .out("hasPortGroup") + .has("aai-node-type", "port-group") + .has("interface-id", "key2"); + assertEquals( + "gremlin query should be " + expected.toString(), + expected.toString(), + query.getQueryBuilder().getQuery().toString()); + assertEquals( + "parent gremlin query should be equal the query for port group", + expectedParent.toString(), + query.getQueryBuilder().getParentQuery().getQuery().toString()); + assertEquals( + "result type should be port-group", + "port-group", + query.getParentResultType()); + assertEquals( + "result type should be cvlan-tag", + "cvlan-tag", + query.getResultType()); + assertEquals( + "container type should be cvlan-tags", + "cvlan-tags", + query.getContainerType()); + assertEquals("dependent",true, query.isDependent()); + + + } + + @Test + public void getAllParent() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("cloud-infrastructure/pservers").build(); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); + GraphTraversal expected = __.start() + .has("aai-node-type", "pserver"); + GraphTraversal expectedParent = __.start() + .has("aai-node-type", "pserver"); + assertEquals( + "gremlin query should be " + expected.toString(), + expected.toString(), + query.getQueryBuilder().getQuery().toString()); + assertEquals( + "parent gremlin query should be equal the query for pserver", + expectedParent.toString(), + query.getQueryBuilder().getParentQuery().getQuery().toString()); + assertEquals( + "parent result type should be empty", + "", + query.getParentResultType()); + assertEquals( + "result type should be pserver", + "pserver", + query.getResultType()); + assertEquals( + "container type should be pservers", + "pservers", + query.getContainerType()); + assertEquals("dependent",false, query.isDependent()); + + + } + + + /** + * Gets the via query param. + * + * @return the via query param + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void getViaQueryParam() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("cloud-infrastructure/cloud-regions/cloud-region/mycloudowner/mycloudregionid/tenants/tenant").build(); + MultivaluedMap map = new MultivaluedHashMap<>(); + map.putSingle("tenant-name", "Tenant1"); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri, map); + GraphTraversal expected = __.start() + .has("cloud-owner", "mycloudowner").has("cloud-region-id", "mycloudregionid") + .has("aai-node-type", "cloud-region") + .out("has") + .has("aai-node-type", "tenant") + .has("tenant-name", "Tenant1"); + + GraphTraversal expectedParent = __.start() + .has("cloud-owner", "mycloudowner").has("cloud-region-id", "mycloudregionid") + .has("aai-node-type", "cloud-region"); + + assertEquals( + "gremlin query should be " + expected.toString(), + expected.toString(), + query.getQueryBuilder().getQuery().toString()); + assertEquals( + "parent gremlin query should be equal the query for cloud-region", + expectedParent.toString(), + query.getQueryBuilder().getParentQuery().getQuery().toString()); + assertEquals( + "result type should be cloud-region", + "cloud-region", + query.getParentResultType()); + assertEquals( + "result type should be tenant", + "tenant", + query.getResultType()); + assertEquals( + "container type should be empty", + "", + query.getContainerType()); + assertEquals("dependent",true, query.isDependent()); + + } + + @Test + public void getViaDuplicateQueryParam() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("cloud-infrastructure/cloud-regions/cloud-region/mycloudowner/mycloudregionid/tenants/tenant").build(); + MultivaluedMap map = new MultivaluedHashMap<>(); + List values = new ArrayList<>(); + values.add("Tenant1"); + values.add("Tenant2"); + map.put("tenant-name", values); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri, map); + GraphTraversal expected = __.start() + .has("cloud-owner", "mycloudowner").has("cloud-region-id", "mycloudregionid") + .has("aai-node-type", "cloud-region") + .out("has") + .has("aai-node-type", "tenant") + .has("tenant-name", P.within(values)); + + GraphTraversal expectedParent = __.start() + .has("cloud-owner", "mycloudowner").has("cloud-region-id", "mycloudregionid") + .has("aai-node-type", "cloud-region"); + + assertEquals( + "gremlin query should be " + expected.toString(), + expected.toString(), + query.getQueryBuilder().getQuery().toString()); + assertEquals( + "parent gremlin query should be equal the query for cloud-region", + expectedParent.toString(), + query.getQueryBuilder().getParentQuery().getQuery().toString()); + assertEquals( + "result type should be cloud-region", + "cloud-region", + query.getParentResultType()); + assertEquals( + "result type should be tenant", + "tenant", + query.getResultType()); + assertEquals( + "container type should be empty", + "", + query.getContainerType()); + assertEquals("dependent",true, query.isDependent()); + + } + + /** + * Gets the plural via query param. + * + * @return the plural via query param + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void getPluralViaQueryParam() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("network/vnfcs").build(); + MultivaluedMap map = new MultivaluedHashMap<>(); + map.putSingle("prov-status", "up"); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri, map); + GraphTraversal expected = __.start() + .has("aai-node-type", "vnfc") + .has("prov-status", "up"); + + GraphTraversal expectedParent = __.start() + .has("aai-node-type", "vnfc"); + + assertEquals( + "gremlin query should be " + expected.toString(), + expected.toString(), + query.getQueryBuilder().getQuery().toString()); + assertEquals( + "parent", + expectedParent.toString(), + query.getQueryBuilder().getParentQuery().getQuery().toString()); + assertEquals( + "parent result type should be empty", + "", + query.getParentResultType()); + assertEquals( + "result type should be vnfc", + "vnfc", + query.getResultType()); + assertEquals( + "container type should be empty", + "vnfcs", + query.getContainerType()); + assertEquals("dependent",true, query.isDependent()); + + } + + /** + * Gets the all query param naming exception. + * + * @return the all query param naming exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void getAllQueryParamNamingException() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags").build(); + MultivaluedMap map = new MultivaluedHashMap<>(); + map.putSingle("cvlan-tag", "333"); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri, map); + + GraphTraversal expected = __.start() + .has("vnf-id", "key1").has("aai-node-type", "vce") + .out("hasPortGroup") + .has("aai-node-type", "port-group") + .has("interface-id", "key2").out("hasCTag") + .has("aai-node-type", "cvlan-tag") + .has("cvlan-tag", 333); + GraphTraversal expectedParent = __.start() + .has("vnf-id", "key1").has("aai-node-type", "vce") + .out("hasPortGroup") + .has("aai-node-type", "port-group") + .has("interface-id", "key2"); + assertEquals( + "gremlin query should be " + expected.toString(), + expected.toString(), + query.getQueryBuilder().getQuery().toString()); + assertEquals( + "parent gremlin query should be equal the query for port group", + expectedParent.toString(), + query.getQueryBuilder().getParentQuery().getQuery().toString()); + assertEquals( + "result type should be port-group", + "port-group", + query.getParentResultType()); + assertEquals( + "result type should be cvlan-tag", + "cvlan-tag", + query.getResultType()); + assertEquals( + "container type should be cvlan-tags", + "cvlan-tags", + query.getContainerType()); + assertEquals("dependent",true, query.isDependent()); + + + } + + /** + * Abstract type. + * + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void abstractType() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("vnf/key1").build(); + + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); + + GraphTraversal expected = __.start() + .has("vnf-id", "key1").has(AAIProperties.NODE_TYPE, P.within("vce", "generic-vnf")); + + GraphTraversal expectedParent = expected; + assertEquals( + "gremlin query should be " + expected.toString(), + expected.toString(), + query.getQueryBuilder().getQuery().toString()); + assertEquals( + "parent gremlin query should be equal the query for port group", + expectedParent.toString(), + query.getQueryBuilder().getParentQuery().getQuery().toString()); + assertEquals( + "result type should be empty", + "", + query.getParentResultType()); + assertEquals( + "result type should be vnf", + "vnf", + query.getResultType()); + + assertEquals("dependent",false, query.isDependent()); + + + } + + /** + * Non parent abstract type. + * + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void nonParentAbstractType() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("cloud-infrastructure/pservers/pserver/key2/vnf/key1").build(); + thrown.expect(AAIException.class); + thrown.expectMessage(containsString("not a valid path")); + dbEngine.getQueryBuilder().createQueryFromURI(uri); + } + + @Test + public void parentAbstractTypeWithNesting() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("vnf/key1/vf-modules/vf-module/key2").build(); + + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); + + GraphTraversal expected = __.start() + .has("vnf-id", "key1").has(AAIProperties.NODE_TYPE, P.within("vce", "generic-vnf")) + .union(__.out("has").has(AAIProperties.NODE_TYPE, "vf-module")).has("vf-module-id", "key2"); + + GraphTraversal expectedParent = __.start() + .has("vnf-id", "key1").has(AAIProperties.NODE_TYPE, P.within("vce", "generic-vnf")); + assertEquals( + "gremlin query should be " + expected.toString(), + expected.toString(), + query.getQueryBuilder().getQuery().toString()); + assertEquals( + "parent gremlin query should be equal the query for ", + expectedParent.toString(), + query.getQueryBuilder().getParentQuery().getQuery().toString()); + assertEquals( + "result type should be vnf", + "vnf", + query.getParentResultType()); + assertEquals( + "result type should be vf-module", + "vf-module", + query.getResultType()); + + assertEquals("dependent",true, query.isDependent()); + + } + + @Test + public void getViaBadQueryParam() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("cloud-infrastructure/cloud-regions/cloud-region/a/b/tenants/tenant").build(); + MultivaluedMap map = new MultivaluedHashMap<>(); + map.putSingle("tenant-n231ame", "Tenant1"); + thrown.expect(AAIException.class); + thrown.expect(hasProperty("code", is("AAI_3000"))); + + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri, map); + + } + + @Test + public void getPluralViaBadQueryParam() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("cloud-infrastructure/cloud-regions/cloud-region/a/b/tenants").build(); + MultivaluedMap map = new MultivaluedHashMap<>(); + map.putSingle("tenant-n231ame", "Tenant1"); + thrown.expect(AAIException.class); + thrown.expect(hasProperty("code", is("AAI_3000"))); + + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri, map); + + } + + @Test + public void getPluralViaDuplicateQueryParam() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("network/vnfcs").build(); + MultivaluedMap map = new MultivaluedHashMap<>(); + List values = new ArrayList<>(); + values.add("up"); + values.add("down"); + values.add("left"); + values.add("right"); + values.add("start"); + map.put("prov-status", values); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri, map); + GraphTraversal expected = __.start() + .has("aai-node-type", "vnfc") + .has("prov-status", P.within(values)); + + GraphTraversal expectedParent = __.start() + .has("aai-node-type", "vnfc"); + + assertEquals( + "gremlin query should be " + expected.toString(), + expected.toString(), + query.getQueryBuilder().getQuery().toString()); + assertEquals( + "parent", + expectedParent.toString(), + query.getQueryBuilder().getParentQuery().getQuery().toString()); + assertEquals( + "parent result type should be empty", + "", + query.getParentResultType()); + assertEquals( + "result type should be vnfc", + "vnfc", + query.getResultType()); + assertEquals( + "container type should be empty", + "vnfcs", + query.getContainerType()); + assertEquals("dependent",true, query.isDependent()); + + } + + @Test + public void dbAliasedSearch() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("network/test-objects").build(); + MultivaluedMap map = new MultivaluedHashMap<>(); + map.putSingle("persona-model-customization-id", "key2"); + QueryParser query = dbEnginev9.getQueryBuilder().createQueryFromURI(uri, map); + GraphTraversal expected = __.start() + .has("aai-node-type", "test-object") + .has("model-customization-id", "key2"); + GraphTraversal expectedParent = __.start() + .has("aai-node-type", "test-object"); + + assertEquals( + "gremlin query should be " + expected.toString(), + expected.toString(), + query.getQueryBuilder().getQuery().toString()); + assertEquals( + "parent", + expectedParent.toString(), + query.getQueryBuilder().getParentQuery().getQuery().toString()); + + assertEquals( + "result type should be", + "test-object", + query.getResultType()); + assertEquals( + "result type should be empty", + "", + query.getParentResultType()); + assertEquals("dependent",true, query.isDependent()); + + + } + + @Test + public void dataLinkedSearch() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("network/vpn-bindings").build(); + MultivaluedMap map = new MultivaluedHashMap<>(); + map.putSingle("global-route-target", "key2"); + QueryParser query = dbEnginev9.getQueryBuilder().createQueryFromURI(uri, map); + GraphTraversal expected = __.start() + .has("aai-node-type", "vpn-binding") + .where(__.out("has").has(AAIProperties.NODE_TYPE, "route-target").has("global-route-target", "key2")); + GraphTraversal expectedParent = __.start() + .has("aai-node-type", "vpn-binding"); + + assertEquals( + "gremlin query should be " + expected.toString(), + expected.toString(), + query.getQueryBuilder().getQuery().toString()); + assertEquals( + "parent", + expectedParent.toString(), + query.getQueryBuilder().getParentQuery().getQuery().toString()); + + assertEquals( + "result type should be", + "vpn-binding", + query.getResultType()); + assertEquals( + "result type should be empty", + "", + query.getParentResultType()); + assertEquals("dependent",true, query.isDependent()); + } + + @Test + public void pluralCousin() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("cloud-infrastructure/complexes/complex/key1/related-to/pservers").build(); + + QueryParser query = dbEnginev9.getQueryBuilder().createQueryFromURI(uri); + GraphTraversal expected = __.start() + .has("physical-location-id", "key1") + .has("aai-node-type", "complex") + .in("locatedIn").has("aai-node-type", "pserver"); + GraphTraversal expectedParent = __.start() + .has("physical-location-id", "key1") + .has("aai-node-type", "complex"); + + assertEquals( + "gremlin query should be " + expected.toString(), + expected.toString(), + query.getQueryBuilder().getQuery().toString()); + assertEquals( + "parent", + expectedParent.toString(), + query.getQueryBuilder().getParentQuery().getQuery().toString()); + + assertEquals( + "result type should be", + "pserver", + query.getResultType()); + assertEquals( + "result type should be", + "complex", + query.getParentResultType()); + //this is controversial but we're not allowing writes on this currently + assertEquals("dependent",true, query.isDependent()); + } + + @Test + public void specificCousin() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("cloud-infrastructure/complexes/complex/key1/related-to/pservers/pserver/key2").build(); + + QueryParser query = dbEnginev9.getQueryBuilder().createQueryFromURI(uri); + GraphTraversal expected = __.start() + .has("physical-location-id", "key1") + .has("aai-node-type", "complex") + .in("locatedIn").has("aai-node-type", "pserver") + .has("hostname", "key2"); + GraphTraversal expectedParent = __.start() + .has("physical-location-id", "key1") + .has("aai-node-type", "complex"); + + assertEquals( + "gremlin query should be " + expected.toString(), + expected.toString(), + query.getQueryBuilder().getQuery().toString()); + assertEquals( + "parent", + expectedParent.toString(), + query.getQueryBuilder().getParentQuery().getQuery().toString()); + + assertEquals( + "result type should be", + "pserver", + query.getResultType()); + assertEquals( + "result type should be", + "complex", + query.getParentResultType()); + //this is controversial but we're not allowing writes on this currently + assertEquals("dependent",true, query.isDependent()); + } + + @Test + public void doubleSpecificCousin() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("cloud-infrastructure/complexes/complex/key1/related-to/pservers/pserver/key2/related-to/vservers/vserver/key3").build(); + + QueryParser query = dbEnginev9.getQueryBuilder().createQueryFromURI(uri); + GraphTraversal expected = __.start() + .has("physical-location-id", "key1") + .has("aai-node-type", "complex") + .in("locatedIn").has("aai-node-type", "pserver") + .has("hostname", "key2") + .in("runsOnPserver").has("aai-node-type", "vserver") + .has("vserver-id", "key3"); + GraphTraversal expectedParent = __.start() + .has("physical-location-id", "key1") + .has("aai-node-type", "complex") + .in("locatedIn").has("aai-node-type", "pserver") + .has("hostname", "key2"); + + assertEquals( + "gremlin query should be " + expected.toString(), + expected.toString(), + query.getQueryBuilder().getQuery().toString()); + assertEquals( + "parent", + expectedParent.toString(), + query.getQueryBuilder().getParentQuery().getQuery().toString()); + + assertEquals( + "result type should be", + "vserver", + query.getResultType()); + assertEquals( + "result type should be", + "pserver", + query.getParentResultType()); + //this is controversial but we're not allowing writes on this currently + assertEquals("dependent",true, query.isDependent()); + } + + @Test + public void traversalEndsInRelatedTo() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("cloud-infrastructure/complexes/complex/key1/related-to").build(); + + thrown.expect(AAIException.class); + thrown.expectMessage(containsString(RestTokens.COUSIN.toString())); + QueryParser query = dbEnginev9.getQueryBuilder().createQueryFromURI(uri); + + } + + @Test + public void pluralCousinToPluralCousin() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("cloud-infrastructure/complexes/related-to/pservers").build(); + + thrown.expect(AAIException.class); + thrown.expectMessage(containsString("chain plurals")); + QueryParser query = dbEnginev9.getQueryBuilder().createQueryFromURI(uri); + + } +} diff --git a/aai-core/src/test/java/org/onap/aai/parsers/query/LegacyQueryTest.java b/aai-core/src/test/java/org/onap/aai/parsers/query/LegacyQueryTest.java new file mode 100644 index 00000000..c49aa393 --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/parsers/query/LegacyQueryTest.java @@ -0,0 +1,158 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.parsers.query; + +import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext; +import org.junit.Ignore; +import org.junit.Test; +import org.onap.aai.AAISetup; +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.LoaderFactory; +import org.onap.aai.introspection.ModelInjestor; +import org.onap.aai.introspection.ModelType; +import org.onap.aai.introspection.Version; +import org.onap.aai.serialization.engines.QueryStyle; +import org.onap.aai.serialization.engines.TitanDBEngine; +import org.onap.aai.serialization.engines.TransactionalGraphEngine; + +import javax.ws.rs.core.UriBuilder; +import javax.xml.bind.JAXBException; +import java.io.UnsupportedEncodingException; +import java.net.URI; + +import static org.junit.Assert.assertEquals; + + +@Ignore +public class LegacyQueryTest extends AAISetup { + + private ModelInjestor injestor = ModelInjestor.getInstance(); + + private TransactionalGraphEngine dbEngine = + new TitanDBEngine(QueryStyle.GREMLIN_TRAVERSAL, + LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v8), + false); + private final Version version = Version.v8; + private DynamicJAXBContext context = injestor.getContextForVersion(version); + + + /** + * Parent query. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void parentQuery() throws JAXBException, UnsupportedEncodingException, AAIException { + + URI uri = UriBuilder.fromPath("cloud-infrastructure/pservers/pserver/key1").build(); + + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); + + String expected = + ".has('hostname', 'key1').has('aai-node-type', 'pserver')"; + assertEquals( + "gremlin query should be " + expected, + expected, + query.getQueryBuilder().getQuery()); + assertEquals( + "parent gremlin query should be equal to normal query", + expected, + query.getQueryBuilder().getParentQuery().getQuery()); + assertEquals( + "result type should be pserver", + "pserver", + query.getResultType()); + + } + + /** + * Child query. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void childQuery() throws JAXBException, UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("cloud-infrastructure/pservers/pserver/key1/lag-interfaces/lag-interface/key2").build(); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); + + String expected = + ".has('hostname', 'key1').has('aai-node-type', 'pserver')" + + ".out('hasLAGInterface').has('aai-node-type', 'lag-interface')" + + ".has('interface-name', 'key2')"; + String parentExpected = + ".has('hostname', 'key1').has('aai-node-type', 'pserver')"; + assertEquals( + "gremlin query should be for node", + expected, + query.getQueryBuilder().getQuery()); + assertEquals( + "parent gremlin query should be for parent", + parentExpected, + query.getQueryBuilder().getParentQuery().getQuery()); + assertEquals( + "result type should be lag-interface", + "lag-interface", + query.getResultType()); + } + + /** + * Naming exceptions. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void namingExceptions() throws JAXBException, UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags/cvlan-tag/655").build(); + + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); + String expected = + ".has('vnf-id', 'key1').has('aai-node-type', 'vce')" + + ".in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'port-group')" + + ".has('interface-id', 'key2')" + + ".in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'cvlan-tag')" + + ".has('cvlan-tag', 655)"; + String expectedParent = + ".has('vnf-id', 'key1').has('aai-node-type', 'vce')" + + ".in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'port-group')" + + ".has('interface-id', 'key2')"; + assertEquals( + "gremlin query should be " + expected, + expected, + query.getQueryBuilder().getQuery()); + assertEquals( + "parent gremlin query should be equal the query for port group", + expectedParent, + query.getQueryBuilder().getParentQuery().getQuery()); + assertEquals( + "result type should be cvlan-tag", + "cvlan-tag", + query.getResultType()); + + } + +} diff --git a/aai-core/src/test/java/org/onap/aai/parsers/query/RelationshipGremlinQueryTest.java b/aai-core/src/test/java/org/onap/aai/parsers/query/RelationshipGremlinQueryTest.java new file mode 100644 index 00000000..73108892 --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/parsers/query/RelationshipGremlinQueryTest.java @@ -0,0 +1,663 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.parsers.query; + +import org.eclipse.persistence.dynamic.DynamicEntity; +import org.eclipse.persistence.jaxb.UnmarshallerProperties; +import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext; +import org.junit.Ignore; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.onap.aai.AAISetup; +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.*; +import org.onap.aai.serialization.engines.QueryStyle; +import org.onap.aai.serialization.engines.TitanDBEngine; +import org.onap.aai.serialization.engines.TransactionalGraphEngine; + +import javax.xml.bind.JAXBException; +import javax.xml.bind.Unmarshaller; +import javax.xml.transform.stream.StreamSource; +import java.io.StringReader; +import java.io.UnsupportedEncodingException; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.junit.Assert.assertEquals; + +@Ignore +public class RelationshipGremlinQueryTest extends AAISetup { + + private ModelInjestor injestor = ModelInjestor.getInstance(); + private TransactionalGraphEngine dbEngine = + new TitanDBEngine(QueryStyle.GREMLIN_TRAVERSAL, + LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v8), + false); + private final Version version = Version.v8; + private DynamicJAXBContext context = injestor.getContextForVersion(version); + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + /** + * Parent query. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void parentQuery() throws JAXBException, UnsupportedEncodingException, AAIException { + + String content = + "{" + + "\"related-to\" : \"pserver\"," + + "\"relationship-data\" : [{" + + "\"relationship-key\" : \"pserver.hostname\"," + + "\"relationship-value\" : \"key1\"" + + "}]" + + "}"; + + Unmarshaller unmarshaller = context.createUnmarshaller(); + unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); + unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); + unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); + Object obj = context.newDynamicEntity("Relationship"); + + DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); + + Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); + + String expected = + ".has('hostname', 'key1').has('aai-node-type', 'pserver')"; + assertEquals( + "gremlin query should be " + expected, + expected, + query.getQueryBuilder().getQuery()); + assertEquals( + "parent gremlin query should be equal to normal query", + expected, + query.getQueryBuilder().getParentQuery().getQuery()); + assertEquals( + "result type should be pserver", + "pserver", + query.getResultType()); + + } + + /** + * Child query. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void childQuery() throws JAXBException, UnsupportedEncodingException, AAIException { + String content = + "{" + + "\"related-to\" : \"lag-interface\"," + + "\"relationship-data\" : [{" + + "\"relationship-key\" : \"pserver.hostname\"," + + "\"relationship-value\" : \"key1\"" + + "}, {" + + "\"relationship-key\" : \"lag-interface.interface-name\"," + + "\"relationship-value\" : \"key2\"" + + "}]" + + "}"; + + Unmarshaller unmarshaller = context.createUnmarshaller(); + unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); + unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); + unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); + Object obj = context.newDynamicEntity("Relationship"); + + DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); + + Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); + + String expected = ".has('hostname', 'key1').has('aai-node-type', 'pserver').in('tosca.relationships.BindsTo').has('aai-node-type', 'lag-interface')" + + ".has('interface-name', 'key2')"; + String parentExpected = + ".has('hostname', 'key1').has('aai-node-type', 'pserver')"; + assertEquals( + "gremlin query should be for node", + expected, + query.getQueryBuilder().getQuery()); + assertEquals( + "parent gremlin query should be for parent", + parentExpected, + query.getQueryBuilder().getParentQuery().getQuery()); + assertEquals( + "result type should be lag-interface", + "lag-interface", + query.getResultType()); + } + + /** + * Naming exceptions. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void namingExceptions() throws JAXBException, UnsupportedEncodingException, AAIException { + String content = + "{" + + "\"related-to\" : \"cvlan-tag\"," + + "\"relationship-data\" : [{" + + "\"relationship-key\" : \"vce.vnf-id\"," + + "\"relationship-value\" : \"key1\"" + + "}, {" + + "\"relationship-key\" : \"port-group.interface-id\"," + + "\"relationship-value\" : \"key2\"" + + "},{" + + "\"relationship-key\" : \"cvlan-tag.cvlan-tag\"," + + "\"relationship-value\" : \"655\"" + + "}]" + + "}"; + + Unmarshaller unmarshaller = context.createUnmarshaller(); + unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); + unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); + unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); + Object obj = context.newDynamicEntity("Relationship"); + + DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); + + Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); + String expected = + ".has('vnf-id', 'key1').has('aai-node-type', 'vce')" + + ".in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'port-group')" + + ".has('interface-id', 'key2').in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'cvlan-tag')" + + ".has('cvlan-tag', 655)"; + String expectedParent = + ".has('vnf-id', 'key1').has('aai-node-type', 'vce')" + + ".in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'port-group')" + + ".has('interface-id', 'key2')"; + assertEquals( + "gremlin query should be " + expected, + expected, + query.getQueryBuilder().getQuery()); + assertEquals( + "parent gremlin query should be equal the query for port group", + expectedParent, + query.getQueryBuilder().getParentQuery().getQuery()); + assertEquals( + "result type should be cvlan-tag", + "cvlan-tag", + query.getResultType()); + + } + + /** + * Scrambled relationship. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void scrambledRelationship() throws JAXBException, UnsupportedEncodingException, AAIException { + String content = + "{" + + "\"related-to\" : \"l3-interface-ipv4-address-list\"," + + "\"relationship-data\" : [{" + + "\"relationship-key\" : \"l3-interface-ipv4-address-list.l3-interface-ipv4-address\"," + + "\"relationship-value\" : \"key5\"" + + "},{" + + "\"relationship-key\" : \"lag-interface.interface-name\"," + + "\"relationship-value\" : \"key2\"" + + "},{" + + "\"relationship-key\" : \"l-interface.interface-name\"," + + "\"relationship-value\" : \"key3\"" + + "},{" + + "\"relationship-key\" : \"vlan.vlan-interface\"," + + "\"relationship-value\" : \"key4\"" + + "},{" + + "\"relationship-key\" : \"generic-vnf.vnf-id\"," + + "\"relationship-value\" : \"key1\"" + + "}]" + + "}"; + scrambledRelationshipSpec(content); + } + + /** + * Reversed relationship. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void reversedRelationship() throws JAXBException, UnsupportedEncodingException, AAIException { + String content = + "{" + + "\"related-to\" : \"l3-interface-ipv4-address-list\"," + + "\"relationship-data\" : [{" + + "\"relationship-key\" : \"l3-interface-ipv4-address-list.l3-interface-ipv4-address\"," + + "\"relationship-value\" : \"key5\"" + + "},{" + + "\"relationship-key\" : \"vlan.vlan-interface\"," + + "\"relationship-value\" : \"key4\"" + + "},{" + + "\"relationship-key\" : \"l-interface.interface-name\"," + + "\"relationship-value\" : \"key3\"" + + "},{" + + "\"relationship-key\" : \"lag-interface.interface-name\"," + + "\"relationship-value\" : \"key2\"" + + "},{" + + "\"relationship-key\" : \"generic-vnf.vnf-id\"," + + "\"relationship-value\" : \"key1\"" + + "}]" + + "}"; + scrambledRelationshipSpec(content); + } + + /** + * Ordered ambiguous relationship. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void orderedAmbiguousRelationship() throws JAXBException, UnsupportedEncodingException, AAIException { + String content = + "{" + + "\"related-to\" : \"l3-interface-ipv4-address-list\"," + + "\"relationship-data\" : [{" + + "\"relationship-key\" : \"generic-vnf.vnf-id\"," + + "\"relationship-value\" : \"key1\"" + + "},{" + + "\"relationship-key\" : \"lag-interface.interface-name\"," + + "\"relationship-value\" : \"key2\"" + + "},{" + + "\"relationship-key\" : \"l-interface.interface-name\"," + + "\"relationship-value\" : \"key3\"" + + "},{" + + "\"relationship-key\" : \"vlan.vlan-interface\"," + + "\"relationship-value\" : \"key4\"" + + "},{" + + "\"relationship-key\" : \"l3-interface-ipv4-address-list.l3-interface-ipv4-address\"," + + "\"relationship-value\" : \"key5\"" + + "}]" + + "}"; + scrambledRelationshipSpec(content); + } + + /** + * Scrambled relationship spec. + * + * @param content the content + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + public void scrambledRelationshipSpec(String content) throws JAXBException, UnsupportedEncodingException, AAIException { + + + Unmarshaller unmarshaller = context.createUnmarshaller(); + unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); + unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); + unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); + Object obj = context.newDynamicEntity("Relationship"); + + DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); + + Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); + String expected = + ".has('vnf-id', 'key1').has('aai-node-type', 'generic-vnf')" + + ".in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'lag-interface')" + + ".has('interface-name', 'key2').in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'l-interface')" + + ".has('interface-name', 'key3').out('tosca.relationships.LinksTo').has('aai-node-type', 'vlan')" + + ".has('vlan-interface', 'key4').in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'l3-interface-ipv4-address-list')" + + ".has('l3-interface-ipv4-address', 'key5')"; + String expectedParent = + ".has('vnf-id', 'key1').has('aai-node-type', 'generic-vnf')" + + ".in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'lag-interface')" + + ".has('interface-name', 'key2').in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'l-interface')" + + ".has('interface-name', 'key3').out('tosca.relationships.LinksTo').has('aai-node-type', 'vlan')" + + ".has('vlan-interface', 'key4')"; + assertEquals( + "gremlin query should be " + expected, + expected, + query.getQueryBuilder().getQuery()); + assertEquals( + "parent gremlin query should be equal the query for vlan", + expectedParent, + query.getQueryBuilder().getParentQuery().getQuery()); + assertEquals( + "result type should be l3-interface-ipv4-address-list", + "l3-interface-ipv4-address-list", + query.getResultType()); + + } + + /** + * Short circuit. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void shortCircuit() throws JAXBException, UnsupportedEncodingException, AAIException { + String content = + "{" + + "\"related-to\" : \"cvlan-tag\"," + + "\"related-link\" : \"http://mock-system-name.com:8443/aai/v6/network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags/cvlan-tag/655\"," + + "\"relationship-data\" : [{" + + "\"relationship-key\" : \"vce.vnf-id\"," + + "\"relationship-value\" : \"key1\"" + + "}, {" + + "\"relationship-key\" : \"port-group.interface-id\"," + + "\"relationship-value\" : \"key2\"" + + "},{" + + "\"relationship-key\" : \"cvlan-tag.cvlan-tag\"," + + "\"relationship-value\" : \"655\"" + + "}]" + + "}"; + + Unmarshaller unmarshaller = context.createUnmarshaller(); + unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); + unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); + unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); + Object obj = context.newDynamicEntity("Relationship"); + + DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); + + Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); + String expected = + ".has('vnf-id', 'key1').has('aai-node-type', 'vce')" + + ".in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'port-group')" + + ".has('interface-id', 'key2').in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'cvlan-tag')" + + ".has('cvlan-tag', 655)"; + String expectedParent = + ".has('vnf-id', 'key1').has('aai-node-type', 'vce')" + + ".in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'port-group')" + + ".has('interface-id', 'key2')"; + assertEquals( + "gremlin query should be " + expected, + expected, + query.getQueryBuilder().getQuery()); + assertEquals( + "parent gremlin query should be equal the query for port group", + expectedParent, + query.getQueryBuilder().getParentQuery().getQuery()); + assertEquals( + "result type should be cvlan-tag", + "cvlan-tag", + query.getResultType()); + + } + + @Test + public void shorterCircuit() throws JAXBException, UnsupportedEncodingException, AAIException { + String content = + "{" + + "\"related-to\" : \"cvlan-tag\"," + + "\"related-link\" : \"file:///network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags/cvlan-tag/655\"" + + "}"; + + Unmarshaller unmarshaller = context.createUnmarshaller(); + unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); + unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); + unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); + Object obj = context.newDynamicEntity("Relationship"); + + DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); + + Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); + String expected = + ".has('vnf-id', 'key1').has('aai-node-type', 'vce')" + + ".in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'port-group')" + + ".has('interface-id', 'key2').in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'cvlan-tag')" + + ".has('cvlan-tag', 655)"; + String expectedParent = + ".has('vnf-id', 'key1').has('aai-node-type', 'vce')" + + ".in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'port-group')" + + ".has('interface-id', 'key2')"; + assertEquals( + "gremlin query should be " + expected, + expected, + query.getQueryBuilder().getQuery()); + assertEquals( + "parent gremlin query should be equal the query for port group", + expectedParent, + query.getQueryBuilder().getParentQuery().getQuery()); + assertEquals( + "result type should be cvlan-tag", + "cvlan-tag", + query.getResultType()); + + } + + /** + * Double key. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void doubleKey() throws JAXBException, UnsupportedEncodingException, AAIException { + String content = + "{" + + "\"related-to\" : \"ctag-pool\"," + + "\"relationship-data\" : [{" + + "\"relationship-key\" : \"complex.physical-location-id\"," + + "\"relationship-value\" : \"key1\"" + + " }, { " + + "\"relationship-key\" : \"ctag-pool.target-pe\"," + + " \"relationship-value\" : \"key2\"" + + " },{" + + "\"relationship-key\" : \"ctag-pool.availability-zone-name\"," + + "\"relationship-value\" : \"key3\"" + + "}]" + + "}"; + + + Unmarshaller unmarshaller = context.createUnmarshaller(); + unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); + unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); + unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); + Object obj = context.newDynamicEntity("Relationship"); + + DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); + + Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); + + String expected = + ".has('physical-location-id', 'key1').has('aai-node-type', 'complex')" + + ".in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'ctag-pool')" + + ".has('target-pe', 'key2')" + + ".has('availability-zone-name', 'key3')"; + String expectedParent = + ".has('physical-location-id', 'key1').has('aai-node-type', 'complex')"; + + assertEquals( + "gremlin query should be " + expected, + expected, + query.getQueryBuilder().getQuery()); + assertEquals( + "parent gremlin query should be equal the query for port group", + expectedParent, + query.getQueryBuilder().getParentQuery().getQuery()); + assertEquals( + "result type should be ctag-pool", + "ctag-pool", + query.getResultType()); + + } + + /** + * Abstract type. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void abstractType() throws JAXBException, UnsupportedEncodingException, AAIException { + String content = + "{" + + "\"related-to\" : \"vnf\"," + + "\"relationship-data\" : [{" + + "\"relationship-key\" : \"vnf.vnf-id\"," + + "\"relationship-value\" : \"key1\"" + + " }]" + + "}"; + + + Unmarshaller unmarshaller = context.createUnmarshaller(); + unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); + unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); + unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); + Object obj = context.newDynamicEntity("Relationship"); + + DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); + + Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); + + String expected = + ".has('vnf-id', 'key1')" + + ".has('aai-node-type', P.within('vce','generic-vnf'))"; + + String expectedParent = + ".has('vnf-id', 'key1')" + + ".has('aai-node-type', P.within('vce','generic-vnf'))"; + + assertEquals( + "gremlin query should be " + expected, + expected, + query.getQueryBuilder().getQuery()); + assertEquals( + "parent gremlin query should be equal the query for port group", + expectedParent, + query.getQueryBuilder().getParentQuery().getQuery()); + assertEquals( + "result type should be vnf", + "vnf", + query.getResultType()); + + } + + /** + * Invalid node name. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void invalidNodeName() throws JAXBException, UnsupportedEncodingException, AAIException { + String content = + "{" + + "\"related-to\" : \"l3-interface-ipv4-address-list\"," + + "\"relationship-data\" : [{" + + "\"relationship-key\" : \"generic-vnf.vnf-id\"," + + "\"relationship-value\" : \"key1\"" + + "},{" + + "\"relationship-key\" : \"lag-interface.interface-name\"," + + "\"relationship-value\" : \"key2\"" + + "},{" + + "\"relationship-key\" : \"l-infeaterface.interface-name\"," + + "\"relationship-value\" : \"key3\"" + + "},{" + + "\"relationship-key\" : \"vlan.vlan-interface\"," + + "\"relationship-value\" : \"key4\"" + + "},{" + + "\"relationship-key\" : \"l3-interface-ipv4-address-list.l3-interface-ipv4-address\"," + + "\"relationship-value\" : \"key5\"" + + "}]" + + "}"; + thrown.expect(AAIException.class); + thrown.expectMessage(containsString("invalid object name")); + + Unmarshaller unmarshaller = context.createUnmarshaller(); + unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); + unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); + unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); + Object obj = context.newDynamicEntity("Relationship"); + + DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); + + Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity); + dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); + + } + + /** + * Invalid property name. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void invalidPropertyName() throws JAXBException, UnsupportedEncodingException, AAIException { + String content = + "{" + + "\"related-to\" : \"l3-interface-ipv4-address-list\"," + + "\"relationship-data\" : [{" + + "\"relationship-key\" : \"generic-vnf.vnf-id\"," + + "\"relationship-value\" : \"key1\"" + + "},{" + + "\"relationship-key\" : \"lag-interface.intfdaferface-name\"," + + "\"relationship-value\" : \"key2\"" + + "},{" + + "\"relationship-key\" : \"l-interface.interface-name\"," + + "\"relationship-value\" : \"key3\"" + + "},{" + + "\"relationship-key\" : \"vlan.vlan-interface\"," + + "\"relationship-value\" : \"key4\"" + + "},{" + + "\"relationship-key\" : \"l3-interface-ipv4-address-list.l3-interface-ipv4-address\"," + + "\"relationship-value\" : \"key5\"" + + "}]" + + "}"; + thrown.expect(AAIException.class); + thrown.expectMessage(containsString("invalid property name")); + + Unmarshaller unmarshaller = context.createUnmarshaller(); + unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); + unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); + unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); + Object obj = context.newDynamicEntity("Relationship"); + + DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); + + Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity); + dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); + + } +} diff --git a/aai-core/src/test/java/org/onap/aai/parsers/query/RelationshipQueryTest.java b/aai-core/src/test/java/org/onap/aai/parsers/query/RelationshipQueryTest.java new file mode 100644 index 00000000..7a72bcd0 --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/parsers/query/RelationshipQueryTest.java @@ -0,0 +1,272 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.parsers.query; + +import org.eclipse.persistence.dynamic.DynamicEntity; +import org.eclipse.persistence.jaxb.UnmarshallerProperties; +import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext; +import org.junit.Ignore; +import org.junit.Test; +import org.onap.aai.AAISetup; +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.*; +import org.onap.aai.serialization.engines.QueryStyle; +import org.onap.aai.serialization.engines.TitanDBEngine; +import org.onap.aai.serialization.engines.TransactionalGraphEngine; + +import javax.xml.bind.JAXBException; +import javax.xml.bind.Unmarshaller; +import javax.xml.transform.stream.StreamSource; +import java.io.StringReader; +import java.io.UnsupportedEncodingException; + +import static org.junit.Assert.assertEquals; + +@Ignore +public class RelationshipQueryTest extends AAISetup { + + private ModelInjestor injestor = ModelInjestor.getInstance(); + + private TransactionalGraphEngine dbEngine = + new TitanDBEngine(QueryStyle.GREMLIN_TRAVERSAL, + LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v8), + false); + private final Version version = Version.v8; + private DynamicJAXBContext context = injestor.getContextForVersion(version); + + /** + * Parent query. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void parentQuery() throws JAXBException, UnsupportedEncodingException, AAIException { + + String content = + "{" + + "\"related-to\" : \"pserver\"," + + "\"relationship-data\" : [{" + + "\"relationship-key\" : \"pserver.hostname\"," + + "\"relationship-value\" : \"key1\"" + + "}]" + + "}"; + + Unmarshaller unmarshaller = context.createUnmarshaller(); + unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); + unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); + unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); + Object obj = context.newDynamicEntity("Relationship"); + + DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); + + Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); + + String expected = + ".has('hostname', 'key1').has('aai-node-type', 'pserver')"; + assertEquals( + "gremlin query should be " + expected, + expected, + query.getQueryBuilder().getQuery()); + assertEquals( + "parent gremlin query should be equal to normal query", + expected, + query.getQueryBuilder().getParentQuery().getQuery()); + assertEquals( + "result type should be pserver", + "pserver", + query.getResultType()); + + } + + /** + * Child query. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Ignore + @Test + public void childQuery() throws JAXBException, UnsupportedEncodingException, AAIException { + String content = + "{" + + "\"related-to\" : \"lag-interface\"," + + "\"relationship-data\" : [{" + + "\"relationship-key\" : \"pserver.hostname\"," + + "\"relationship-value\" : \"key1\"" + + "}, {" + + "\"relationship-key\" : \"lag-interface.interface-name\"," + + "\"relationship-value\" : \"key2\"" + + "}]" + + "}"; + + Unmarshaller unmarshaller = context.createUnmarshaller(); + unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); + unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); + unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); + Object obj = context.newDynamicEntity("Relationship"); + + DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); + + Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); + String expected = + ".has('hostname', 'key1').has('aai-node-type', 'pserver').out('hasLAGInterface').has('aai-node-type', 'lag-interface')" + + ".has('interface-name', 'key2')"; + String parentExpected = + ".has('hostname', 'key1').has('aai-node-type', 'pserver')"; + assertEquals( + "gremlin query should be for node", + expected, + query.getQueryBuilder().getQuery()); + assertEquals( + "parent gremlin query should be for parent", + parentExpected, + query.getQueryBuilder().getParentQuery().getQuery()); + assertEquals( + "result type should be lag-interface", + "lag-interface", + query.getResultType()); + } + + /** + * Naming exceptions. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Ignore + @Test + public void namingExceptions() throws JAXBException, UnsupportedEncodingException, AAIException { + String content = + "{" + + "\"related-to\" : \"cvlan-tag\"," + + "\"relationship-data\" : [{" + + "\"relationship-key\" : \"vce.vnf-id\"," + + "\"relationship-value\" : \"key1\"" + + "}, {" + + "\"relationship-key\" : \"port-group.interface-id\"," + + "\"relationship-value\" : \"key2\"" + + "},{" + + "\"relationship-key\" : \"cvlan-tag.cvlan-tag\"," + + "\"relationship-value\" : \"655\"" + + "}]" + + "}"; + + Unmarshaller unmarshaller = context.createUnmarshaller(); + unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); + unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); + unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); + Object obj = context.newDynamicEntity("Relationship"); + + DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); + + Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); + String expected = + ".has('vnf-id', 'key1').has('aai-node-type', 'vce').in('org.onap.relationships.inventory.BelongsTo')" + + ".has('aai-node-type', 'port-group').has('interface-id', 'key2').in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'cvlan-tag')" + + ".has('cvlan-tag', 655)"; + String expectedParent = + ".has('vnf-id', 'key1').has('aai-node-type', 'vce').in('org.onap.relationships.inventory.BelongsTo')" + + ".has('aai-node-type', 'port-group').has('interface-id', 'key2')"; + + assertEquals( + "gremlin query should be " + expected, + expected, + query.getQueryBuilder().getQuery()); + assertEquals( + "parent gremlin query should be equal the query for port group", + expectedParent, + query.getQueryBuilder().getParentQuery().getQuery()); + assertEquals( + "result type should be cvlan-tag", + "cvlan-tag", + query.getResultType()); + + } + + /** + * Double key. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Ignore + @Test + public void doubleKey() throws JAXBException, UnsupportedEncodingException, AAIException { + String content = + "{" + + "\"related-to\" : \"ctag-pool\"," + + "\"relationship-data\" : [{" + + "\"relationship-key\" : \"complex.physical-location-id\"," + + "\"relationship-value\" : \"key1\"" + + " }, { " + + "\"relationship-key\" : \"ctag-pool.target-pe\"," + + " \"relationship-value\" : \"key2\"" + + " },{" + + "\"relationship-key\" : \"ctag-pool.availability-zone-name\"," + + "\"relationship-value\" : \"key3\"" + + "}]" + + "}"; + + + Unmarshaller unmarshaller = context.createUnmarshaller(); + unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); + unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); + unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); + Object obj = context.newDynamicEntity("Relationship"); + + DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); + + Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); + + String expected = + ".has('physical-location-id', 'key1').has('aai-node-type', 'complex')" + + ".in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'ctag-pool')" + + ".has('target-pe', 'key2')" + + ".has('availability-zone-name', 'key3')"; + String expectedParent = + ".has('physical-location-id', 'key1').has('aai-node-type', 'complex')"; + + assertEquals( + "gremlin query should be " + expected, + expected, + query.getQueryBuilder().getQuery()); + assertEquals( + "parent gremlin query should be equal the query for port group", + expectedParent, + query.getQueryBuilder().getParentQuery().getQuery()); + assertEquals( + "result type should be ctag-pool", + "ctag-pool", + query.getResultType()); + + } + +} diff --git a/aai-core/src/test/java/org/onap/aai/parsers/query/UniqueRelationshipQueryTest.java b/aai-core/src/test/java/org/onap/aai/parsers/query/UniqueRelationshipQueryTest.java new file mode 100644 index 00000000..12290861 --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/parsers/query/UniqueRelationshipQueryTest.java @@ -0,0 +1,297 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.parsers.query; + +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.eclipse.persistence.dynamic.DynamicEntity; +import org.eclipse.persistence.jaxb.UnmarshallerProperties; +import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.onap.aai.AAISetup; +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.*; +import org.onap.aai.serialization.engines.QueryStyle; +import org.onap.aai.serialization.engines.TitanDBEngine; +import org.onap.aai.serialization.engines.TransactionalGraphEngine; + +import javax.xml.bind.JAXBException; +import javax.xml.bind.Unmarshaller; +import javax.xml.transform.stream.StreamSource; +import java.io.StringReader; +import java.io.UnsupportedEncodingException; + +import static org.junit.Assert.assertEquals; + +@Ignore +public class UniqueRelationshipQueryTest extends AAISetup { + + private ModelInjestor injestor = ModelInjestor.getInstance(); + private TransactionalGraphEngine dbEngine = + new TitanDBEngine(QueryStyle.GREMLIN_UNIQUE, + LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v8), + false); + private final Version version = Version.v8; + private DynamicJAXBContext context = injestor.getContextForVersion(version); + private Unmarshaller unmarshaller = null; + + /** + * Setup. + * + * @throws JAXBException the JAXB exception + */ + @Before + public void setup() throws JAXBException { + unmarshaller = context.createUnmarshaller(); + unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); + unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); + unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); + } + + /** + * Parent query. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void parentQuery() throws JAXBException, UnsupportedEncodingException, AAIException { + + String content = + "{" + + "\"related-to\" : \"pserver\"," + + "\"relationship-data\" : [{" + + "\"relationship-key\" : \"pserver.hostname\"," + + "\"relationship-value\" : \"key1\"" + + "}]" + + "}"; + + Object obj = context.newDynamicEntity("Relationship"); + + DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); + + Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); + String key = "pserver/key1"; + GraphTraversal expected = + __.start().has("aai-unique-key", key); + String resultType = "pserver"; + String containerType = ""; + + testSet(query, expected, expected, resultType, containerType); + + } + + /** + * Child query. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void childQuery() throws JAXBException, UnsupportedEncodingException, AAIException { + String content = + "{" + + "\"related-to\" : \"lag-interface\"," + + "\"relationship-data\" : [{" + + "\"relationship-key\" : \"pserver.hostname\"," + + "\"relationship-value\" : \"key1\"" + + "}, {" + + "\"relationship-key\" : \"lag-interface.interface-name\"," + + "\"relationship-value\" : \"key2\"" + + "}]" + + "}"; + + Object obj = context.newDynamicEntity("Relationship"); + + DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); + + Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); + + String key = "pserver/key1/lag-interface/key2"; + GraphTraversal expected = + __.start().has("aai-unique-key", key); + GraphTraversal parentExpected = + __.start().has("aai-unique-key", "pserver/key1"); + String resultType = "lag-interface"; + String containerType = ""; + + testSet(query, expected, parentExpected, resultType, containerType); + } + + /** + * Naming exceptions. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void namingExceptions() throws JAXBException, UnsupportedEncodingException, AAIException { + String content = + "{" + + "\"related-to\" : \"cvlan-tag\"," + + "\"relationship-data\" : [{" + + "\"relationship-key\" : \"vce.vnf-id\"," + + "\"relationship-value\" : \"key1\"" + + "}, {" + + "\"relationship-key\" : \"port-group.interface-id\"," + + "\"relationship-value\" : \"key2\"" + + "},{" + + "\"relationship-key\" : \"cvlan-tag.cvlan-tag\"," + + "\"relationship-value\" : \"655\"" + + "}]" + + "}"; + + Object obj = context.newDynamicEntity("Relationship"); + + DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); + + Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); + String key = "vce/key1/port-group/key2/cvlan-tag/655"; + GraphTraversal expected = + __.start().has("aai-unique-key", key); + GraphTraversal parentExpected = + __.start().has("aai-unique-key", "vce/key1/port-group/key2"); + String resultType = "cvlan-tag"; + String containerType = ""; + + testSet(query, expected, parentExpected, resultType, containerType); + + } + + /** + * Double key. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void doubleKey() throws JAXBException, UnsupportedEncodingException, AAIException { + String content = + "{" + + "\"related-to\" : \"service-capability\"," + + "\"relationship-data\" : [{" + + "\"relationship-key\" : \"service-capability.service-type\"," + + "\"relationship-value\" : \"key1\"" + + " }, { " + + "\"relationship-key\" : \"service-capability.vnf-type\"," + + " \"relationship-value\" : \"key2\"" + + " }]" + + "}"; + + Object obj = context.newDynamicEntity("Relationship"); + + DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); + + Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); + + String key = "service-capability/key1/key2"; + GraphTraversal expected = + __.start().has("aai-unique-key", key); + GraphTraversal parentExpected = + __.start().has("aai-unique-key", "service-capability/key1/key2"); + String resultType = "service-capability"; + String containerType = ""; + + testSet(query, expected, parentExpected, resultType, containerType); + + } + + /** + * Short circuit. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void shortCircuit() throws JAXBException, UnsupportedEncodingException, AAIException { + String content = + "{" + + "\"related-to\" : \"cvlan-tag\"," + + "\"related-link\" : \"http://mock-system-name.com:8443/aai/v6/network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags/cvlan-tag/655\"," + + "\"relationship-data\" : [{" + + "\"relationship-key\" : \"vce.hostname\"," + + "\"relationship-value\" : \"key1\"" + + "}, {" + + "\"relationship-key\" : \"port-group.interface-name\"," + + "\"relationship-value\" : \"key2\"" + + "},{" + + "\"relationship-key\" : \"cvlan-tag.-name\"," + + "\"relationship-value\" : \"655\"" + + "}]" + + "}"; + + Object obj = context.newDynamicEntity("Relationship"); + + DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); + + Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); + String key = "vce/key1/port-group/key2/cvlan-tag/655"; + GraphTraversal expected = __.start().has("aai-unique-key", key); + GraphTraversal parentExpected = __.start().has("aai-unique-key", "vce/key1/port-group/key2"); + String resultType = "cvlan-tag"; + String containerType = ""; + + testSet(query, expected, parentExpected, resultType, containerType); + + } + + /** + * Test set. + * + * @param query the query + * @param expected the expected + * @param parentExpected the parent expected + * @param resultType the result type + * @param containerType the container type + */ + public void testSet(QueryParser query, GraphTraversal expected, GraphTraversal parentExpected, String resultType, String containerType) { + assertEquals( + "gremlin query should be " + expected, + expected, + query.getQueryBuilder().getQuery()); + assertEquals( + "parent gremlin query should be " + parentExpected, + parentExpected, + query.getParentQueryBuilder().getParentQuery()); + assertEquals( + "result type should be " + resultType, + resultType, + query.getResultType()); + assertEquals( + "container type should be " + containerType, + containerType, + query.getContainerType()); + } +} diff --git a/aai-core/src/test/java/org/onap/aai/parsers/query/UniqueURIQueryTest.java b/aai-core/src/test/java/org/onap/aai/parsers/query/UniqueURIQueryTest.java new file mode 100644 index 00000000..84e9c6bc --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/parsers/query/UniqueURIQueryTest.java @@ -0,0 +1,195 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.parsers.query; + +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext; +import org.junit.Ignore; +import org.junit.Test; +import org.onap.aai.AAISetup; +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.LoaderFactory; +import org.onap.aai.introspection.ModelInjestor; +import org.onap.aai.introspection.ModelType; +import org.onap.aai.introspection.Version; +import org.onap.aai.serialization.engines.QueryStyle; +import org.onap.aai.serialization.engines.TitanDBEngine; +import org.onap.aai.serialization.engines.TransactionalGraphEngine; + +import javax.ws.rs.core.UriBuilder; +import java.io.UnsupportedEncodingException; +import java.net.URI; + +import static org.junit.Assert.assertEquals; + +@Ignore +public class UniqueURIQueryTest extends AAISetup { + + private ModelInjestor injestor = ModelInjestor.getInstance(); + private TransactionalGraphEngine dbEngine = + new TitanDBEngine(QueryStyle.GREMLIN_UNIQUE, + LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v8), + false); + private final Version version = Version.v8; + private DynamicJAXBContext context = injestor.getContextForVersion(version); + + /** + * Parent query. + * + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void parentQuery() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("cloud-infrastructure/complexes/complex/key1").build(); + String key = "complex/key1"; + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); + GraphTraversal expected = __.start().has("aai-unique-key", key); + String parentResultType = ""; + String resultType = "complex"; + String containerType = ""; + + testSet(query, expected, expected, parentResultType, resultType, containerType); + + } + + /** + * Parent plural query. + * + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void parentPluralQuery() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("cloud-infrastructure/complexes").build(); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); + GraphTraversal expected = __.start().has("aai-node-type", "complex"); + String parentResultType = ""; + String resultType = "complex"; + String containerType = "complexes"; + + testSet(query, expected, expected, parentResultType, resultType, containerType); + + } + + /** + * Child query. + * + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void childQuery() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("cloud-infrastructure/complexes/complex/key1/ctag-pools/ctag-pool/key2/key3").build(); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); + String parentKey = "complex/key1"; + String key = parentKey + "/ctag-pool/key2/key3"; + GraphTraversal expected = __.start().has("aai-unique-key", key); + GraphTraversal parentExpected = __.start().has("aai-unique-key", parentKey); + String parentResultType = "complex"; + String resultType = "ctag-pool"; + String containerType = ""; + + testSet(query, expected, parentExpected, parentResultType, resultType, containerType); + + } + + /** + * Naming exceptions. + * + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void namingExceptions() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags/cvlan-tag/655").build(); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); + String parentKey = "vce/key1/port-group/key2"; + String key = parentKey + "/cvlan-tag/655"; + GraphTraversal expected = __.start().has("aai-unique-key", key); + GraphTraversal parentExpected = __.start().has("aai-unique-key", parentKey); + String parentResultType = "port-group"; + String resultType = "cvlan-tag"; + String containerType = ""; + + testSet(query, expected, parentExpected, parentResultType, resultType, containerType); + + } + + /** + * Gets the all. + * + * @return the all + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void getAll() throws UnsupportedEncodingException, AAIException { + String parentURI = "network/vces/vce/key1/port-groups/port-group/key2"; + String parentKey = "vce/key1/port-group/key2"; + URI uri = UriBuilder.fromPath(parentURI + "/cvlan-tags").build(); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); + GraphTraversal expected = __.start().has("aai-unique-key", parentKey).out("hasCTag").has("aai-node-type", "cvlan-tag"); + GraphTraversal parentExpected = __.start().has("aai-unique-key",parentKey); + String parentResultType = "port-group"; + String resultType = "cvlan-tag"; + String containerType = "cvlan-tags"; + + testSet(query, expected, parentExpected, parentResultType, resultType, containerType); + + } + + /** + * Test set. + * + * @param query the query + * @param expected the expected + * @param parentExpected the parent expected + * @param parentResultType the parent result type + * @param resultType the result type + * @param containerType the container type + */ + public void testSet(QueryParser query, GraphTraversal expected, GraphTraversal parentExpected, String parentResultType, String resultType, String containerType) { + assertEquals( + "gremlin query should be " + expected, + expected, + query.getQueryBuilder().getQuery()); + assertEquals( + "parent gremlin query should be " + parentExpected, + parentExpected, + query.getQueryBuilder().getParentQuery().getQuery()); + assertEquals( + "parent result type should be " + parentResultType, + parentResultType, + query.getParentResultType()); + assertEquals( + "result type should be " + resultType, + resultType, + query.getResultType()); + assertEquals( + "container type should be " + containerType, + containerType, + query.getContainerType()); + } +} diff --git a/aai-core/src/test/java/org/onap/aai/parsers/relationship/RelationshipToURITest.java b/aai-core/src/test/java/org/onap/aai/parsers/relationship/RelationshipToURITest.java new file mode 100644 index 00000000..04727067 --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/parsers/relationship/RelationshipToURITest.java @@ -0,0 +1,225 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.parsers.relationship; + +import org.apache.commons.io.IOUtils; +import org.junit.Ignore; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.onap.aai.AAISetup; +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.*; +import org.onap.aai.parsers.exceptions.AAIIdentityMapParseException; +import org.onap.aai.parsers.exceptions.AmbiguousMapAAIException; + +import java.io.FileInputStream; +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; + +import static org.hamcrest.Matchers.hasProperty; +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertEquals; + +public class RelationshipToURITest extends AAISetup { + + private final ModelType modelType = ModelType.MOXY; + private final Version version10 = Version.v10; + private final Version version9 = Version.v9; + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + @Test + public void onlyLink() throws AAIException, URISyntaxException, IOException { + Loader loader = LoaderFactory.createLoaderForVersion(modelType, version10); + Introspector obj = loader.unmarshal("relationship", this.getJsonString("only-related-link.json")); + URI expected = new URI("/aai/v10/network/test-objects/test-object/key1"); + + RelationshipToURI parse = new RelationshipToURI(loader, obj); + + URI uri = parse.getUri(); + + assertEquals("related-link is equal", expected.getPath(), uri.getPath()); + } + + @Test + public void onlyData() throws AAIException, URISyntaxException, IOException { + Loader loader = LoaderFactory.createLoaderForVersion(modelType, version10); + Introspector obj = loader.unmarshal("relationship", this.getJsonString("only-relationship-data.json")); + URI expected = new URI("/network/test-objects/test-object/key1"); + + RelationshipToURI parse = new RelationshipToURI(loader, obj); + + URI uri = parse.getUri(); + + assertEquals("related-link is equal", expected, uri); + } + + @Test + public void failV10() throws AAIException, URISyntaxException, IOException { + Loader loader = LoaderFactory.createLoaderForVersion(modelType, version10); + Introspector obj = loader.unmarshal("relationship", this.getJsonString("both-failv10-successv9.json")); + URI expected = new URI("/aai/v10/network/test-objects/test-object/key1"); + + thrown.expect(AAIIdentityMapParseException.class); + thrown.expect(hasProperty("code", is("AAI_3000"))); + RelationshipToURI parse = new RelationshipToURI(loader, obj); + URI uri = parse.getUri(); + + } + + @Test + public void successV9() throws AAIException, URISyntaxException, IOException { + Loader loader = LoaderFactory.createLoaderForVersion(modelType, version9); + Introspector obj = loader.unmarshal("relationship", this.getJsonString("both-failv10-successv9.json")); + URI expected = new URI("/network/test-objects/test-object/key2"); + + RelationshipToURI parse = new RelationshipToURI(loader, obj); + URI uri = parse.getUri(); + + assertEquals("related-link is equal", expected, uri); + + + } + + @Test + public void failV9() throws AAIException, URISyntaxException, IOException { + Loader loader = LoaderFactory.createLoaderForVersion(modelType, version9); + Introspector obj = loader.unmarshal("relationship", this.getJsonString("both-successv10-failv9.json")); + URI expected = new URI("/network/test-objects/test-object/key1"); + + thrown.expect(AAIIdentityMapParseException.class); + thrown.expect(hasProperty("code", is("AAI_3000"))); + RelationshipToURI parse = new RelationshipToURI(loader, obj); + + + URI uri = parse.getUri(); + + } + + @Test + public void failNothingToParse() throws AAIException, URISyntaxException, IOException { + Loader loader = LoaderFactory.createLoaderForVersion(modelType, version10); + Introspector obj = loader.unmarshal("relationship", this.getJsonString("nothing-to-parse.json")); + URI expected = new URI("/aai/v10/network/test-objects/test-object/key1"); + + thrown.expect(AAIIdentityMapParseException.class); + thrown.expect(hasProperty("code", is("AAI_3000"))); + RelationshipToURI parse = new RelationshipToURI(loader, obj); + + URI uri = parse.getUri(); + + } + + @Test + public void successV10() throws AAIException, URISyntaxException, IOException { + Loader loader = LoaderFactory.createLoaderForVersion(modelType, version10); + Introspector obj = loader.unmarshal("relationship", this.getJsonString("both-successv10-failv9.json")); + URI expected = new URI("/aai/v10/network/test-objects/test-object/key1"); + + RelationshipToURI parse = new RelationshipToURI(loader, obj); + + + URI uri = parse.getUri(); + + assertEquals("related-link is equal", expected, uri); + + + } + + @Test + public void ambiguousRelationship() throws AAIException, URISyntaxException, IOException { + Loader loader = LoaderFactory.createLoaderForVersion(modelType, version10); + Introspector obj = loader.unmarshal("relationship", this.getJsonString("ambiguous-relationship.json")); + URI expected = new URI("/aai/v10/network/test-objects/test-object/key1"); + + thrown.expect(AmbiguousMapAAIException.class); + thrown.expect(hasProperty("code", is("AAI_6146"))); + + RelationshipToURI parse = new RelationshipToURI(loader, obj); + + URI uri = parse.getUri(); + + assertEquals("related-link is equal", expected, uri); + + + } + + @Ignore + @Test + public void moreItemsThanRequired() throws AAIException, URISyntaxException, IOException { + Loader loader = LoaderFactory.createLoaderForVersion(modelType, version10); + Introspector obj = loader.unmarshal("relationship", this.getJsonString("too-many-items-relationship.json")); + URI expected = new URI("/network/generic-vnfs/generic-vnf/key1/l-interfaces/l-interface/key2"); + + RelationshipToURI parse = new RelationshipToURI(loader, obj); + + URI uri = parse.getUri(); + + assertEquals("related-link is equal", expected.toString(), uri.toString()); + + } + + @Test + public void twoTopLevelNodes() throws AAIException, URISyntaxException, IOException { + Loader loader = LoaderFactory.createLoaderForVersion(modelType, version10); + Introspector obj = loader.unmarshal("relationship", this.getJsonString("two-top-level-relationship.json")); + URI expected = new URI("/network/generic-vnfs/generic-vnf/key1/l-interfaces/l-interface/key2"); + + thrown.expect(AmbiguousMapAAIException.class); + thrown.expect(hasProperty("code", is("AAI_6146"))); + + RelationshipToURI parse = new RelationshipToURI(loader, obj); + + URI uri = parse.getUri(); + + assertEquals("related-link is equal", expected, uri); + + } + + @Test + public void topLevelWithTwoKeys() throws AAIException, URISyntaxException, IOException { + Loader loader = LoaderFactory.createLoaderForVersion(modelType, version10); + Introspector obj = loader.unmarshal("relationship", this.getJsonString("top-level-two-keys-relationship.json")); + URI expected = new URI("/cloud-infrastructure/cloud-regions/cloud-region/key1/key2/availability-zones/availability-zone/key3"); + + RelationshipToURI parse = new RelationshipToURI(loader, obj); + + URI uri = parse.getUri(); + + assertEquals("related-link is equal", expected.toString(), uri.toString()); + + } + + + private String getJsonString(String filename) throws IOException { + + + FileInputStream is = new FileInputStream("src/test/resources/bundleconfig-local/etc/relationship/" + filename); + String s = IOUtils.toString(is, "UTF-8"); + IOUtils.closeQuietly(is); + + return s; + } +} diff --git a/aai-core/src/test/java/org/onap/aai/parsers/uri/URIParserTest.java b/aai-core/src/test/java/org/onap/aai/parsers/uri/URIParserTest.java new file mode 100644 index 00000000..bc3a684b --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/parsers/uri/URIParserTest.java @@ -0,0 +1,102 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.parsers.uri; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.onap.aai.AAISetup; +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.Loader; +import org.onap.aai.introspection.LoaderFactory; +import org.onap.aai.introspection.ModelType; +import org.onap.aai.introspection.Version; + +import javax.ws.rs.core.UriBuilder; +import javax.xml.bind.JAXBException; +import java.io.UnsupportedEncodingException; +import java.net.URI; + +import static org.hamcrest.Matchers.hasProperty; +import static org.hamcrest.Matchers.is; + +public class URIParserTest extends AAISetup { + + private Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v8); + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + /** + * Invalid path. + * + * @throws JAXBException the JAXB exception + * @throws AAIException the AAI exception + * @throws IllegalArgumentException the illegal argument exception + * @throws UnsupportedEncodingException the unsupported encoding exception + */ + @Test + public void invalidPath() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException { + URI uri = UriBuilder.fromPath("/aai/" + loader.getVersion() + "/network/tenants/tenant/key1/vservers/vserver/key2/l-interfaces/l-interface/key3").build(); + + thrown.expect(AAIException.class); + thrown.expect(hasProperty("code", is("AAI_3000"))); + + new URIToDBKey(loader, uri); + } + + /** + * Invalid path no name space. + * + * @throws JAXBException the JAXB exception + * @throws AAIException the AAI exception + * @throws IllegalArgumentException the illegal argument exception + * @throws UnsupportedEncodingException the unsupported encoding exception + */ + @Test + public void invalidPathNoNameSpace() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException { + URI uri = UriBuilder.fromPath("/aai/" + loader.getVersion() + "/tenants/tenant/key1/vservers/vserver/key2/l-interfaces/l-interface/key3").build(); + + thrown.expect(AAIException.class); + thrown.expect(hasProperty("code", is("AAI_3000"))); + + new URIToDBKey(loader, uri); + } + + /** + * Invalid path partial. + * + * @throws JAXBException the JAXB exception + * @throws AAIException the AAI exception + * @throws IllegalArgumentException the illegal argument exception + * @throws UnsupportedEncodingException the unsupported encoding exception + */ + @Test + public void invalidPathPartial() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException { + URI uri = UriBuilder.fromPath("vservers/vserver/key2/l-interfaces/l-interface/key3").build(); + + thrown.expect(AAIException.class); + thrown.expect(hasProperty("code", is("AAI_3000"))); + + new URIToDBKey(loader, uri); + } +} diff --git a/aai-core/src/test/java/org/onap/aai/parsers/uri/URIToDBKeyTest.java b/aai-core/src/test/java/org/onap/aai/parsers/uri/URIToDBKeyTest.java new file mode 100644 index 00000000..7656661b --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/parsers/uri/URIToDBKeyTest.java @@ -0,0 +1,186 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.parsers.uri; + +import org.junit.Ignore; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.onap.aai.AAISetup; +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.parsers.exceptions.DoesNotStartWithValidNamespaceException; +import org.onap.aai.db.props.AAIProperties; +import org.onap.aai.introspection.*; +import org.powermock.core.classloader.annotations.PrepareForTest; + +import javax.ws.rs.core.UriBuilder; +import javax.xml.bind.JAXBException; +import java.io.UnsupportedEncodingException; +import java.net.URI; + +import static org.hamcrest.Matchers.hasProperty; +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertEquals; + + + +@PrepareForTest(ModelInjestor.class) +public class URIToDBKeyTest extends AAISetup { + + private Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, AAIProperties.LATEST); + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + /** + * Uri. + * + * @throws JAXBException the JAXB exception + * @throws AAIException the AAI exception + * @throws IllegalArgumentException the illegal argument exception + * @throws UnsupportedEncodingException the unsupported encoding exception + */ + @Test + public void uri() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException { + URI uri = UriBuilder.fromPath("/aai/" + loader.getVersion() + "/cloud-infrastructure/cloud-regions/cloud-region/cloudOwner-key/cloudRegion-key/tenants/tenant/tenantId-key/vservers/vserver/vserverId-key/l-interfaces/l-interface/key3").build(); + URIToDBKey parse = new URIToDBKey(loader, uri); + Object result = parse.getResult(); + + String expected = "cloud-region/tenant/vserver/l-interface"; + + assertEquals("blah", expected, result); + + } + + /** + * Uri no version. + * + * @throws JAXBException the JAXB exception + * @throws AAIException the AAI exception + * @throws IllegalArgumentException the illegal argument exception + * @throws UnsupportedEncodingException the unsupported encoding exception + */ + @Test + public void uriNoVersion() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException { + URI uri = UriBuilder.fromPath("/cloud-infrastructure/cloud-regions/cloud-region/cloudOwner-key/cloudRegion-key/tenants/tenant/tenantId-key/vservers/vserver/vserverId-key/l-interfaces/l-interface/key3").build(); + URIToDBKey parse = new URIToDBKey(loader, uri); + Object result = parse.getResult(); + + String expected = "cloud-region/tenant/vserver/l-interface"; + + assertEquals("blah", expected, result); + + } + + + /** + * Bad URI. + * + * @throws JAXBException the JAXB exception + * @throws AAIException the AAI exception + * @throws IllegalArgumentException the illegal argument exception + * @throws UnsupportedEncodingException the unsupported encoding exception + */ + @Test + public void badURI() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException { + URI uri = UriBuilder.fromPath("/aai/" + loader.getVersion() + "/cloud-infrastructure/tenants/tenant/key1/vservers/vserver/key2/l-interadsfaces/l-interface/key3").build(); + + thrown.expect(AAIException.class); + thrown.expect(hasProperty("code", is("AAI_3001"))); + + new URIToDBKey(loader, uri); + } + + /** + * NotValid namespace. + * + * @throws JAXBException the JAXB exception + * @throws DoesNotStartWithValidNamespaceException the AAI exception + * @throws IllegalArgumentException the illegal argument exception + * @throws UnsupportedEncodingException the unsupported encoding exception + */ + @Test + public void notValidNamespace() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException { + URI uri = UriBuilder.fromPath("/cloud-region/cloud-regions/cloud-region/cloudOwner-key/cloudRegion-key/tenants/tenant/tenantId-key/vservers/vserver/vserverId-key/l-interfaces/l-interface/key3").build(); + thrown.expect(DoesNotStartWithValidNamespaceException.class); + URIToDBKey parse = new URIToDBKey(loader, uri); + } + + + /** + * No valid tokens. + * + * @throws JAXBException the JAXB exception + * @throws AAIException the AAI exception + * @throws IllegalArgumentException the illegal argument exception + * @throws UnsupportedEncodingException the unsupported encoding exception + */ + @Test + public void noValidTokens() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException { + URI uri = UriBuilder.fromPath("/aai/" + loader.getVersion() + "/cloud/blah/blah").build(); + + thrown.expect(AAIException.class); + thrown.expect(hasProperty("code", is("AAI_3000"))); + + new URIToDBKey(loader, uri); + } + + /** + * Starts with valid namespace. + * + * @throws JAXBException the JAXB exception + * @throws AAIException the AAI exception + * @throws IllegalArgumentException the illegal argument exception + * @throws UnsupportedEncodingException the unsupported encoding exception + */ + @Test + public void startsWithValidNamespace() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException { + URI uri = UriBuilder.fromPath("/aai/" + loader.getVersion() + "/cloud-infrastructure/cloud-regions/cloud-region/cloudOwner-key/cloudRegion-key/tenants/tenant/tenantId-key/vservers/vserver/vserverId-key/l-interfaces/l-interface/key3").build(); + + URIToDBKey parse = new URIToDBKey(loader, uri); + Object result = parse.getResult(); + + String expected = "cloud-region/tenant/vserver/l-interface"; + + assertEquals("blah", expected, result); + } + + /** + * Naming exceptions. + * + * @throws IllegalArgumentException the illegal argument exception + * @throws AAIException the AAI exception + * @throws UnsupportedEncodingException the unsupported encoding exception + */ + @Test + public void namingExceptions() throws IllegalArgumentException, AAIException, UnsupportedEncodingException { + URI uri = UriBuilder.fromPath("network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags/cvlan-tag/655").build(); + URIToDBKey parse = new URIToDBKey(loader, uri); + Object result = parse.getResult(); + + String expected = "vce/port-group/cvlan-tag"; + + assertEquals("blah", expected, result); + + } + +} diff --git a/aai-core/src/test/java/org/onap/aai/parsers/uri/URIToExtensionInformationTest.java b/aai-core/src/test/java/org/onap/aai/parsers/uri/URIToExtensionInformationTest.java new file mode 100644 index 00000000..ce4933a6 --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/parsers/uri/URIToExtensionInformationTest.java @@ -0,0 +1,95 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.parsers.uri; + +import org.junit.Ignore; +import org.junit.Test; +import org.onap.aai.AAISetup; +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.Loader; +import org.onap.aai.introspection.LoaderFactory; +import org.onap.aai.introspection.ModelType; +import org.onap.aai.introspection.Version; +import org.onap.aai.restcore.HttpMethod; + +import javax.ws.rs.core.UriBuilder; +import javax.xml.bind.JAXBException; +import java.io.UnsupportedEncodingException; +import java.net.URI; + +import static org.junit.Assert.assertEquals; + + +public class URIToExtensionInformationTest extends AAISetup { + + private Loader v8Loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v10); + + /** + * Vservers V 7. + * + * @throws JAXBException the JAXB exception + * @throws AAIException the AAI exception + * @throws IllegalArgumentException the illegal argument exception + * @throws UnsupportedEncodingException the unsupported encoding exception + */ + @Test + public void vserversV8() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException { + URI uri = UriBuilder.fromPath("/aai/" + v8Loader.getVersion() + "/cloud-infrastructure/cloud-regions/cloud-region/att-aic/AAIAIC25/tenants/tenant/key1/vservers/vserver/key2").build(); + URIToExtensionInformation parse = new URIToExtensionInformation(v8Loader, uri); + + String namespace = "cloudInfrastructure"; + String preMethodName = "DynamicAddCloudInfrastructureCloudRegionsCloudRegionTenantsTenantVserversVserverPreProc"; + String postMethodName = "DynamicAddCloudInfrastructureCloudRegionsCloudRegionTenantsTenantVserversVserverPostProc"; + String topLevel = "CloudRegion"; + testSpec(parse, HttpMethod.PUT, namespace, preMethodName, postMethodName, topLevel); + + } + + /** + * Test spec. + * + * @param info the info + * @param httpMethod the http method + * @param namespace the namespace + * @param preMethodName the pre method name + * @param postMethodName the post method name + * @param topLevel the top level + */ + private void testSpec(URIToExtensionInformation info, HttpMethod httpMethod, String namespace, String preMethodName, String postMethodName, String topLevel) { + + + String namespaceResult = info.getNamespace(); + String methodNameResult = info.getMethodName(httpMethod, true); + + assertEquals("namespace", namespace, namespaceResult); + assertEquals("preprocess method name", preMethodName, methodNameResult); + methodNameResult = info.getMethodName(httpMethod, false); + + assertEquals("postprocess method name", postMethodName, methodNameResult); + + String topLevelResult = info.getTopObject(); + + assertEquals("topLevel", topLevel, topLevelResult); + } + + +} diff --git a/aai-core/src/test/java/org/onap/aai/parsers/uri/URIToObjectTest.java b/aai-core/src/test/java/org/onap/aai/parsers/uri/URIToObjectTest.java new file mode 100644 index 00000000..d51dcead --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/parsers/uri/URIToObjectTest.java @@ -0,0 +1,249 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.parsers.uri; + +import org.junit.Ignore; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.onap.aai.AAISetup; +import org.onap.aai.db.props.AAIProperties; +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.*; +import org.onap.aai.introspection.exceptions.AAIUnknownObjectException; + +import javax.ws.rs.core.UriBuilder; +import javax.xml.bind.JAXBException; +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.util.HashMap; + +import static org.hamcrest.Matchers.hasProperty; +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertEquals; + + + +public class URIToObjectTest extends AAISetup { + + private Version version = Version.v10; + private Version currentVersion = AAIProperties.LATEST; + private Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, version); + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + /** + * Uri. + * + * @throws JAXBException the JAXB exception + * @throws AAIException the AAI exception + * @throws IllegalArgumentException the illegal argument exception + * @throws UnsupportedEncodingException the unsupported encoding exception + */ + @Test + public void uri() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException { + URI uri = UriBuilder.fromPath("/aai/" + loader.getVersion() + "/cloud-infrastructure/cloud-regions/cloud-region/mycloudowner/mycloudregionid/tenants/tenant/key1/vservers/vserver/key2/l-interfaces/l-interface/key3").build(); + URIToObject parse = new URIToObject(loader, uri); + Introspector result = parse.getTopEntity(); + String expected = "{\"cloud-owner\":\"mycloudowner\",\"cloud-region-id\":\"mycloudregionid\",\"tenants\":{\"tenant\":[{\"tenant-id\":\"key1\",\"vservers\":{\"vserver\":[{\"vserver-id\":\"key2\",\"l-interfaces\":{\"l-interface\":[{\"interface-name\":\"key3\"}]}}]}}]}}"; + String topEntity = "cloud-region"; + String entity = "l-interface"; + + testSet(result.marshal(false), parse, expected, topEntity, entity, version); + + } + + /** + * Uri no version. + * + * @throws JAXBException the JAXB exception + * @throws AAIException the AAI exception + * @throws IllegalArgumentException the illegal argument exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIUnknownObjectException + */ + @Test + public void uriNoVersion() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException, AAIUnknownObjectException { + URI uri = UriBuilder.fromPath("/cloud-infrastructure/cloud-regions/cloud-region/mycloudowner/mycloudregionid/tenants/tenant/key1/vservers/vserver/key2/l-interfaces/l-interface/key3").build(); + HashMap relatedObjects = new HashMap<>(); + Introspector tenantObj = this.loader.introspectorFromName("tenant"); + tenantObj.setValue("tenant-id", "key1"); + tenantObj.setValue("tenant-name", "name1"); + relatedObjects.put(tenantObj.getObjectId(), tenantObj); + Introspector vserverObj = this.loader.introspectorFromName("vserver"); + vserverObj.setValue("vserver-id", "key2"); + vserverObj.setValue("vserver-name", "name2"); + relatedObjects.put(vserverObj.getObjectId(), vserverObj); + + URIToObject parse = new URIToObject(loader, uri, relatedObjects); + Introspector result = parse.getTopEntity(); + String expected = "{\"cloud-owner\":\"mycloudowner\",\"cloud-region-id\":\"mycloudregionid\",\"tenants\":{\"tenant\":[{\"tenant-id\":\"key1\",\"tenant-name\":\"name1\",\"vservers\":{\"vserver\":[{\"vserver-id\":\"key2\",\"vserver-name\":\"name2\",\"l-interfaces\":{\"l-interface\":[{\"interface-name\":\"key3\"}]}}]}}]}}"; + String topEntity = "cloud-region"; + String entity = "l-interface"; + + testSet(result.marshal(false), parse, expected, topEntity, entity, version); + + + } + + + /** + * Bad URI. + * + * @throws JAXBException the JAXB exception + * @throws AAIException the AAI exception + * @throws IllegalArgumentException the illegal argument exception + * @throws UnsupportedEncodingException the unsupported encoding exception + */ + @Test + public void badURI() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException { + URI uri = UriBuilder.fromPath("/aai/" + loader.getVersion() + "/cloud-infrastructure/cloud-regions/cloud-region/mycloudowner/mycloudregionid/tenants/tenant/key1/vservers/vserver/key2/l-interadsfaces/l-interface/key3").build(); + + thrown.expect(AAIException.class); + thrown.expect(hasProperty("code", is("AAI_3000"))); + + new URIToObject(loader, uri); + } + + /** + * Starts with valid namespace. + * + * @throws JAXBException the JAXB exception + * @throws AAIException the AAI exception + * @throws IllegalArgumentException the illegal argument exception + * @throws UnsupportedEncodingException the unsupported encoding exception + */ + @Test + public void startsWithValidNamespace() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException { + URI uri = UriBuilder.fromPath("/cloud-infrastructure/cloud-regions/cloud-region/mycloudowner/mycloudregionid/tenants/tenant/key1/vservers/vserver/key2/l-interfaces/l-interface/key3").build(); + URIToObject parse = new URIToObject(loader, uri); + Introspector result = parse.getTopEntity(); + String expected = "{\"cloud-owner\":\"mycloudowner\",\"cloud-region-id\":\"mycloudregionid\",\"tenants\":{\"tenant\":[{\"tenant-id\":\"key1\",\"vservers\":{\"vserver\":[{\"vserver-id\":\"key2\",\"l-interfaces\":{\"l-interface\":[{\"interface-name\":\"key3\"}]}}]}}]}}"; + String topEntity = "cloud-region"; + String entity = "l-interface"; + + testSet(result.marshal(false), parse, expected, topEntity, entity, version); + } + + /** + * Single top level. + * + * @throws JAXBException the JAXB exception + * @throws AAIException the AAI exception + * @throws IllegalArgumentException the illegal argument exception + * @throws UnsupportedEncodingException the unsupported encoding exception + */ + @Test + public void singleTopLevel() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException { + URI uri = UriBuilder.fromPath("/network/generic-vnfs/generic-vnf/key1").build(); + URIToObject parse = new URIToObject(loader, uri); + Introspector result = parse.getTopEntity(); + String expected = "{\"vnf-id\":\"key1\"}"; + + String topEntity = "generic-vnf"; + String entity = "generic-vnf"; + + testSet(result.marshal(false), parse, expected, topEntity, entity, version); + + } + + /** + * Naming exceptions. + * + * @throws JAXBException the JAXB exception + * @throws AAIException the AAI exception + * @throws IllegalArgumentException the illegal argument exception + * @throws UnsupportedEncodingException the unsupported encoding exception + */ + @Test + @Ignore + public void namingExceptions() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException { + URI uri = UriBuilder.fromPath("network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags/cvlan-tag/655").build(); + URIToObject parse = new URIToObject(loader, uri); + Introspector result = parse.getTopEntity(); + String expected = "{\"vnf-id\":\"key1\",\"port-groups\":{\"port-group\":[{\"interface-id\":\"key2\",\"cvlan-tags\":{\"cvlan-tag-entry\":[{\"cvlan-tag\":655}]}}]}}"; + String topEntity = "vce"; + String entity = "cvlan-tag"; + + testSet(result.marshal(false), parse, expected, topEntity, entity, version); + + } + + /** + * No list object. + * + * @throws IllegalArgumentException the illegal argument exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + @Ignore + public void noListObject() throws IllegalArgumentException, UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("/aai/v6/network/vpls-pes/vpls-pe/0e6189fd-9257-49b9-a3be-d7ba980ccfc9/lag-interfaces/lag-interface/8ae5aa76-d597-4382-b219-04f266fe5e37/l-interfaces/l-interface/9e141d03-467b-437f-b4eb-b3133ec1e205/l3-interface-ipv4-address-list/8f19f0ea-a81f-488e-8d5c-9b7b53696c11").build(); + URIToObject parse = new URIToObject(loader, uri); + Introspector result = parse.getTopEntity(); + String topEntity = "vpls-pe"; + String entity = "l3-interface-ipv4-address-list"; + String expected = "{\"equipment-name\":\"0e6189fd-9257-49b9-a3be-d7ba980ccfc9\",\"lag-interfaces\":{\"lag-interface\":[{\"interface-name\":\"8ae5aa76-d597-4382-b219-04f266fe5e37\",\"l-interfaces\":{\"l-interface\":[{\"interface-name\":\"9e141d03-467b-437f-b4eb-b3133ec1e205\",\"l3-interface-ipv4-address-list\":[{\"l3-interface-ipv4-address\":\"8f19f0ea-a81f-488e-8d5c-9b7b53696c11\"}]}]}}]}}"; + testSet(result.marshal(false), parse, expected, topEntity, entity, version); + + } + + @Test + public void relativePath() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException { + URI uri = UriBuilder.fromPath("./l-interfaces/l-interface/key1").build(); + URIToObject parse = new URIToObject(loader, uri); + Introspector result = parse.getEntity(); + String expected = "{\"interface-name\":\"key1\"}"; + + String topEntity = "l-interface"; + String entity = "l-interface"; + + testSet(result.marshal(false), parse, expected, topEntity, entity, version); + + } + + /** + * Test set. + * + * @param json the json + * @param parse the parse + * @param expected the expected + * @param topEntity the top entity + * @param entity the entity + * @param version the version + */ + public void testSet(String json, URIToObject parse, String expected, String topEntity, String entity, Version version) { + assertEquals("blah", expected, json); + + assertEquals("top entity", topEntity, parse.getTopEntityName()); + + assertEquals("entity", entity, parse.getEntityName()); + + assertEquals("entity object", entity, parse.getEntity().getDbName()); + + assertEquals("parent list object", 1, parse.getParentList().size()); + + assertEquals("object version", version, parse.getObjectVersion()); + } +} diff --git a/aai-core/src/test/java/org/onap/aai/parsers/uri/URIToRelationshipObjectTest.java b/aai-core/src/test/java/org/onap/aai/parsers/uri/URIToRelationshipObjectTest.java new file mode 100644 index 00000000..4f15d278 --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/parsers/uri/URIToRelationshipObjectTest.java @@ -0,0 +1,151 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.parsers.uri; + +import org.junit.Ignore; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.onap.aai.AAISetup; +import org.onap.aai.db.props.AAIProperties; +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.*; + +import javax.ws.rs.core.UriBuilder; +import javax.xml.bind.JAXBException; +import java.io.UnsupportedEncodingException; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; + +import static org.hamcrest.Matchers.hasProperty; +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertTrue; + + +public class URIToRelationshipObjectTest extends AAISetup { + + private Version latest = Version.v10; + private Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, latest); + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + /** + * Uri. + * + * @throws JAXBException the JAXB exception + * @throws AAIException the AAI exception + * @throws IllegalArgumentException the illegal argument exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws URISyntaxException + * @throws MalformedURLException the malformed URL exception + */ + @Test + public void uri() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException, URISyntaxException { + + URI uri = UriBuilder.fromPath("/aai/" + loader.getVersion() + "/cloud-infrastructure/cloud-regions/cloud-region/mycloudregionowner/mycloudregionid/tenants/tenant/key1/vservers/vserver/key2/l-interfaces/l-interface/key3").build(); + URIToRelationshipObject parse = new URIToRelationshipObject(loader, uri); + Introspector result = parse.getResult(); + String expected = "\\{\"related-to\":\"l-interface\",\"related-link\":\"/aai/" + latest + "/cloud-infrastructure/cloud-regions/cloud-region/mycloudregionowner/mycloudregionid/tenants/tenant/key1/vservers/vserver/key2/l-interfaces/l-interface/key3\",\"relationship-data\":\\[\\{\"relationship-key\":\"cloud-region.cloud-owner\",\"relationship-value\":\"mycloudregionowner\"\\},\\{\"relationship-key\":\"cloud-region.cloud-region-id\",\"relationship-value\":\"mycloudregionid\"\\},\\{\"relationship-key\":\"tenant.tenant-id\",\"relationship-value\":\"key1\"\\},\\{\"relationship-key\":\"vserver.vserver-id\",\"relationship-value\":\"key2\"\\},\\{\"relationship-key\":\"l-interface.interface-name\",\"relationship-value\":\"key3\"\\}\\]\\}"; + assertTrue("blah", result.marshal(false).matches(expected)); + + } + + /** + * Uri no version. + * + * @throws JAXBException the JAXB exception + * @throws AAIException the AAI exception + * @throws IllegalArgumentException the illegal argument exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws URISyntaxException + * @throws MalformedURLException the malformed URL exception + */ + @Test + public void uriNoVersion() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException, URISyntaxException { + URI uri = UriBuilder.fromPath("/cloud-infrastructure/cloud-regions/cloud-region/mycloudregionowner/mycloudregionid/tenants/tenant/key1/vservers/vserver/key2/l-interfaces/l-interface/key3").build(); + URIToRelationshipObject parse = new URIToRelationshipObject(loader, uri); + Introspector result = parse.getResult(); + String expected = "\\{\"related-to\":\"l-interface\",\"related-link\":\"/aai/" + latest + "/cloud-infrastructure/cloud-regions/cloud-region/mycloudregionowner/mycloudregionid/tenants/tenant/key1/vservers/vserver/key2/l-interfaces/l-interface/key3\",\"relationship-data\":\\[\\{\"relationship-key\":\"cloud-region.cloud-owner\",\"relationship-value\":\"mycloudregionowner\"\\},\\{\"relationship-key\":\"cloud-region.cloud-region-id\",\"relationship-value\":\"mycloudregionid\"\\},\\{\"relationship-key\":\"tenant.tenant-id\",\"relationship-value\":\"key1\"\\},\\{\"relationship-key\":\"vserver.vserver-id\",\"relationship-value\":\"key2\"\\},\\{\"relationship-key\":\"l-interface.interface-name\",\"relationship-value\":\"key3\"\\}\\]\\}"; + assertTrue("blah", result.marshal(false).matches(expected)); + + + } + + /** + * Double key relationship. + * + * @throws JAXBException the JAXB exception + * @throws AAIException the AAI exception + * @throws IllegalArgumentException the illegal argument exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws URISyntaxException + * @throws MalformedURLException the malformed URL exception + */ + @Test + public void doubleKeyRelationship() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException, URISyntaxException { + URI uri = UriBuilder.fromPath("/aai/" + latest + "/cloud-infrastructure/complexes/complex/key1/ctag-pools/ctag-pool/key2/key3/").build(); + URIToRelationshipObject parse = new URIToRelationshipObject(loader, uri); + Introspector result = parse.getResult(); + String expected = "\\{\"related-to\":\"ctag-pool\",\"related-link\":\"/aai/" + latest + "/cloud-infrastructure/complexes/complex/key1/ctag-pools/ctag-pool/key2/key3\",\"relationship-data\":\\[\\{\"relationship-key\":\"complex.physical-location-id\",\"relationship-value\":\"key1\"\\},\\{\"relationship-key\":\"ctag-pool.target-pe\",\"relationship-value\":\"key2\"\\},\\{\"relationship-key\":\"ctag-pool.availability-zone-name\",\"relationship-value\":\"key3\"\\}\\]\\}"; + assertTrue("blah", result.marshal(false).matches(expected)); + + } + + /** + * Uri with non string key. + * + * @throws JAXBException the JAXB exception + * @throws AAIException the AAI exception + * @throws IllegalArgumentException the illegal argument exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws URISyntaxException + * @throws MalformedURLException the malformed URL exception + */ + @Test + public void uriWithNonStringKey() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException, URISyntaxException { + URI uri = UriBuilder.fromPath("/aai/" + latest + "/network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags/cvlan-tag/144").build(); + URIToRelationshipObject parse = new URIToRelationshipObject(loader, uri); + Introspector result = parse.getResult(); + String expected = "\\{\"related-to\":\"cvlan-tag\",\"related-link\":\"/aai/" + latest + "/network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags/cvlan-tag/144\",\"relationship-data\":\\[\\{\"relationship-key\":\"vce.vnf-id\",\"relationship-value\":\"key1\"\\},\\{\"relationship-key\":\"port-group.interface-id\",\"relationship-value\":\"key2\"\\},\\{\"relationship-key\":\"cvlan-tag.cvlan-tag\",\"relationship-value\":\"144\"\\}\\]\\}"; + assertTrue("blah", result.marshal(false).matches(expected)); + } + /** + * Bad URI. + * + * @throws JAXBException the JAXB exception + * @throws AAIException the AAI exception + * @throws IllegalArgumentException the illegal argument exception + * @throws UnsupportedEncodingException the unsupported encoding exception + */ + @Test + public void badURI() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException { + URI uri = UriBuilder.fromPath("/aai/" + loader.getVersion() + "/cloud-infrastructure/cloud-regions/cloud-region/mycloudregionowner/mycloudregionid/tenants/tenant/key1/vservers/vserver/key2/l-interadsfaces/l-interface/key3").build(); + + thrown.expect(AAIException.class); + thrown.expect(hasProperty("code", is("AAI_3000"))); + + URIToObject parse = new URIToObject(loader, uri); + + } +} diff --git a/aai-core/src/test/java/org/onap/aai/query/builder/SimplePathTest.java b/aai-core/src/test/java/org/onap/aai/query/builder/SimplePathTest.java new file mode 100644 index 00000000..a3515ab9 --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/query/builder/SimplePathTest.java @@ -0,0 +1,124 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.query.builder; + +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; +import org.apache.tinkerpop.gremlin.structure.Graph; +import org.apache.tinkerpop.gremlin.structure.T; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph; +import org.junit.Before; +import org.junit.Test; +import org.onap.aai.AAISetup; +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.Loader; +import org.onap.aai.introspection.LoaderFactory; +import org.onap.aai.introspection.ModelType; +import org.onap.aai.introspection.Version; +import org.onap.aai.serialization.db.EdgeRules; +import org.onap.aai.serialization.db.EdgeType; + +import java.util.List; + +import static org.junit.Assert.assertTrue; + +public class SimplePathTest extends AAISetup { + + public Loader loader; + + @Before + public void setup() throws Exception { + loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.getLatest()); + } + + private QueryBuilder buildTestQuery(QueryBuilder qb) throws AAIException { + return qb.createEdgeTraversal(EdgeType.TREE, "generic-vnf", "l-interface") + .until(qb.newInstance().getVerticesByProperty("aai-node-type", "generic-vnf")) + .repeat(qb.newInstance().union( + qb.newInstance().createEdgeTraversal(EdgeType.TREE, "generic-vnf", "l-interface"), + qb.newInstance().createEdgeTraversal(EdgeType.TREE, "l-interface", "generic-vnf"), + qb.newInstance().createEdgeTraversal(EdgeType.COUSIN, "l-interface", "logical-link"), + qb.newInstance().createEdgeTraversal(EdgeType.COUSIN, "logical-link", "l-interface") + ).simplePath()) + .store("x").cap("x").unfold().dedup(); + } + + private GraphTraversalSource setupGraph() throws AAIException{ + Graph graph = TinkerGraph.open(); + GraphTraversalSource g = graph.traversal(); + EdgeRules rules = EdgeRules.getInstance(); + + Vertex gvnf1 = graph.addVertex(T.label, "generic-vnf", T.id, "00", "aai-node-type", "generic-vnf", + "vnf-id", "gvnf1", "vnf-name", "genvnfname1", "nf-type", "sample-nf-type"); + + Vertex lint1 = graph.addVertex(T.label, "l-interface", T.id, "10", "aai-node-type", "l-interface", + "interface-name", "lint1", "is-port-mirrored", "true", "in-maint", "true", "is-ip-unnumbered", "false"); + + Vertex loglink1 = graph.addVertex(T.label, "logical-link", T.id, "20", "aai-node-type", "logical-link", + "link-name", "loglink1", "in-maint", "false", "link-type", "sausage"); + + Vertex lint2 = graph.addVertex(T.label, "l-interface", T.id, "11", "aai-node-type", "l-interface", + "interface-name", "lint2", "is-port-mirrored", "true", "in-maint", "true", "is-ip-unnumbered", "false"); + + Vertex loglink2 = graph.addVertex(T.label, "logical-link", T.id, "21", "aai-node-type", "logical-link", + "link-name", "loglink2", "in-maint", "false", "link-type", "sausage"); + + Vertex lint3 = graph.addVertex(T.label, "l-interface", T.id, "12", "aai-node-type", "l-interface", + "interface-name", "lint3", "is-port-mirrored", "true", "in-maint", "true", "is-ip-unnumbered", "false"); + + Vertex gvnf2 = graph.addVertex(T.label, "generic-vnf", T.id, "01", "aai-node-type", "generic-vnf", + "vnf-id", "gvnf2", "vnf-name", "genvnfname2", "nf-type", "sample-nf-type"); + + rules.addTreeEdge(g, gvnf1, lint1); + rules.addEdge(g, lint1, loglink1); + rules.addEdge(g, loglink1, lint2); + rules.addEdge(g, lint2, loglink2); + rules.addEdge(g, loglink2, lint3); + rules.addTreeEdge(g, gvnf2, lint3); + + return g; + } + + @Test + public void gremlinQueryTest() throws AAIException { + GraphTraversalSource g = setupGraph(); + List expected = g.V("01").toList(); + Vertex start = g.V("00").toList().get(0); + + GremlinTraversal qb = new GremlinTraversal<>(loader, g, start); + QueryBuilder q = buildTestQuery(qb); + List results = q.toList(); + assertTrue("results match", expected.containsAll(results) && results.containsAll(expected)); + } + + @Test + public void traversalQueryTest() throws AAIException { + GraphTraversalSource g = setupGraph(); + List expected = g.V("01").toList(); + Vertex start = g.V("00").toList().get(0); + + TraversalQuery qb = new TraversalQuery<>(loader, g, start); + QueryBuilder q = buildTestQuery(qb); + List results = q.toList(); + assertTrue("results match", expected.containsAll(results) && results.containsAll(expected)); + } +} diff --git a/aai-core/src/test/java/org/onap/aai/query/builder/TraversalQueryTest.java b/aai-core/src/test/java/org/onap/aai/query/builder/TraversalQueryTest.java new file mode 100644 index 00000000..fa06e17f --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/query/builder/TraversalQueryTest.java @@ -0,0 +1,102 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.query.builder; + +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.mockito.Mock; +import org.onap.aai.AAISetup; +import org.onap.aai.db.props.AAIProperties; +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.Loader; +import org.onap.aai.introspection.LoaderFactory; +import org.onap.aai.introspection.ModelType; + +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.net.URISyntaxException; + +import static org.junit.Assert.assertEquals; + +public class TraversalQueryTest extends AAISetup { + + private Loader loader; + + @Mock + private GraphTraversalSource g; + + @Before + public void configure() throws Exception { + loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, AAIProperties.LATEST); + } + + @Test + public void unionQuery() { + TraversalQuery tQ = new TraversalQuery<>(loader, g); + TraversalQuery tQ2 = new TraversalQuery<>(loader, g); + TraversalQuery tQ3 = new TraversalQuery<>(loader, g); + tQ.union( + tQ2.getVerticesByProperty("test1", "value1"), + tQ3.getVerticesByIndexedProperty("test2", "value2")); + + GraphTraversal expected = __.start() + .union(__.has("test1", "value1"),__.has("test2", "value2")); + + assertEquals("they are equal", expected, tQ.getQuery()); + + } + + @Ignore + @Test + public void traversalClones() throws UnsupportedEncodingException, AAIException, URISyntaxException { + TraversalQuery tQ = new TraversalQuery<>(loader, g); + QueryBuilder builder = tQ.createQueryFromURI(new URI("network/test-objects/test-object/key1")).getQueryBuilder(); + GraphTraversal expected = __.start().has("vnf-id", "key1").has("aai-node-type", "test-object"); + GraphTraversal containerExpected = __.start().has("aai-node-type", "test-object"); + + assertEquals("query object", expected.toString(), builder.getQuery().toString()); + assertEquals("container query object", containerExpected.toString(), builder.getContainerQuery().getQuery().toString()); + + } + + @Ignore + @Test + public void nestedTraversalClones() throws UnsupportedEncodingException, AAIException, URISyntaxException { + + TraversalQuery tQ = new TraversalQuery<>(loader, g); + QueryBuilder builder = tQ.createQueryFromURI(new URI("network/generic-vnfs/generic-vnf/key1/l-interfaces/l-interface/key2")).getQueryBuilder(); + GraphTraversal expected = __.start().has("vnf-id", "key1").has("aai-node-type", "generic-vnf").out("hasLInterface").has(AAIProperties.NODE_TYPE, "l-interface").has("interface-name", "key2"); + GraphTraversal containerExpected = __.start().has("vnf-id", "key1").has("aai-node-type", "generic-vnf").out("hasLInterface").has(AAIProperties.NODE_TYPE, "l-interface"); + + assertEquals("query object", expected.toString(), builder.getQuery().toString()); + assertEquals("container query object", containerExpected.toString(), builder.getContainerQuery().getQuery().toString()); + + } + + + +} diff --git a/aai-core/src/test/java/org/onap/aai/query/builder/UntilTest.java b/aai-core/src/test/java/org/onap/aai/query/builder/UntilTest.java new file mode 100644 index 00000000..d87eb675 --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/query/builder/UntilTest.java @@ -0,0 +1,113 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.query.builder; + +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; +import org.apache.tinkerpop.gremlin.structure.Graph; +import org.apache.tinkerpop.gremlin.structure.T; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph; +import org.junit.Before; +import org.junit.Test; +import org.onap.aai.AAISetup; +import org.onap.aai.db.props.AAIProperties; +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.Loader; +import org.onap.aai.introspection.LoaderFactory; +import org.onap.aai.introspection.ModelType; +import org.onap.aai.serialization.db.EdgeRules; +import org.onap.aai.serialization.db.EdgeType; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.assertTrue; + +public class UntilTest extends AAISetup { + + private Loader loader; + + @Before + public void setup() throws Exception { + loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, AAIProperties.LATEST); + } + + private QueryBuilder buildTestQuery(QueryBuilder qb) throws AAIException{ + return qb.until(qb.newInstance().getVerticesByProperty("aai-node-type", "l-interface")).repeat( + qb.newInstance().union( + qb.newInstance().createEdgeTraversal(EdgeType.TREE, "cloud-region", "tenant"), + qb.newInstance().createEdgeTraversal(EdgeType.TREE, "tenant", "vserver"), + qb.newInstance().createEdgeTraversal(EdgeType.TREE, "vserver", "l-interface") + )).store("x").cap("x").unfold().dedup(); + } + + @Test + public void gremlinQueryUntilTest() throws AAIException { + Graph graph = TinkerGraph.open(); + EdgeRules rules = EdgeRules.getInstance(); + GraphTraversalSource g = graph.traversal(); + + Vertex v1 = graph.addVertex(T.id, 1, "aai-node-type", "cloud-region"); + Vertex v2 = graph.addVertex(T.id, 2, "aai-node-type", "tenant"); + Vertex v3 = graph.addVertex(T.id, 3, "aai-node-type", "vserver"); + Vertex v4 = graph.addVertex(T.id, 4, "aai-node-type", "l-interface"); + rules.addTreeEdge(g, v1, v2); + rules.addTreeEdge(g, v2, v3); + rules.addTreeEdge(g, v3, v4); + List expected = new ArrayList<>(); + expected.add(v4); + + GremlinTraversal qb = new GremlinTraversal<>(loader, g, v1); + QueryBuilder q = buildTestQuery(qb); + + List results = q.toList(); + + assertTrue("results match", expected.containsAll(results) && results.containsAll(expected)); + } + + @Test + public void traversalQueryUntilTest() throws AAIException { + Graph graph = TinkerGraph.open(); + EdgeRules rules = EdgeRules.getInstance(); + GraphTraversalSource g = graph.traversal(); + + Vertex v1 = graph.addVertex(T.id, 1, "aai-node-type", "cloud-region"); + Vertex v2 = graph.addVertex(T.id, 2, "aai-node-type", "tenant"); + Vertex v3 = graph.addVertex(T.id, 3, "aai-node-type", "vserver"); + Vertex v4 = graph.addVertex(T.id, 4, "aai-node-type", "l-interface"); + rules.addTreeEdge(g, v1, v2); + rules.addTreeEdge(g, v2, v3); + rules.addTreeEdge(g, v3, v4); + List expected = new ArrayList<>(); + expected.add(v4); + + TraversalQuery qb = new TraversalQuery<>(loader, g, v1); + QueryBuilder q = buildTestQuery(qb); + + List results = q.toList(); + + assertTrue("results match", expected.containsAll(results) && results.containsAll(expected)); + } + + + +} diff --git a/aai-core/src/test/java/org/onap/aai/serialization/db/DbAliasTest.java b/aai-core/src/test/java/org/onap/aai/serialization/db/DbAliasTest.java new file mode 100644 index 00000000..2137b3e9 --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/serialization/db/DbAliasTest.java @@ -0,0 +1,133 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.serialization.db; + +import com.thinkaurelius.titan.core.TitanFactory; +import com.thinkaurelius.titan.core.TitanGraph; +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; +import org.apache.tinkerpop.gremlin.structure.Graph; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.aai.AAISetup; +import org.onap.aai.dbmap.DBConnectionType; +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.*; +import org.onap.aai.parsers.query.QueryParser; +import org.onap.aai.schema.enums.PropertyMetadata; +import org.onap.aai.serialization.engines.QueryStyle; +import org.onap.aai.serialization.engines.TitanDBEngine; +import org.onap.aai.serialization.engines.TransactionalGraphEngine; + +import java.io.UnsupportedEncodingException; +import java.lang.reflect.InvocationTargetException; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Collections; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + +public class DbAliasTest extends AAISetup { + + private TitanGraph graph; + + private final Version version = Version.v9; + private final ModelType introspectorFactoryType = ModelType.MOXY; + private final QueryStyle queryStyle = QueryStyle.TRAVERSAL; + private final DBConnectionType type = DBConnectionType.REALTIME; + private Loader loader; + private TransactionalGraphEngine dbEngine; + + @Before + public void setup() throws Exception { + graph = TitanFactory.build().set("storage.backend","inmemory").open(); + loader = LoaderFactory.createLoaderForVersion(introspectorFactoryType, version); + dbEngine = new TitanDBEngine( + queryStyle, + type, + loader); + } + + @After + public void tearDown() { + graph.tx().rollback(); + graph.close(); + } + + @Test + public void checkOnWrite() throws AAIException, UnsupportedEncodingException, URISyntaxException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, NoSuchMethodException, InterruptedException { + final String property = "persona-model-customization-id"; + String dbPropertyName = property; + TransactionalGraphEngine spy = spy(this.dbEngine); + TransactionalGraphEngine.Admin adminSpy = spy(dbEngine.asAdmin()); + Graph g = graph.newTransaction(); + GraphTraversalSource traversal = g.traversal(); + when(spy.asAdmin()).thenReturn(adminSpy); + when(adminSpy.getTraversalSource()).thenReturn(traversal); + DBSerializer serializer = new DBSerializer(version, spy, introspectorFactoryType, "AAI_TEST"); + QueryParser uriQuery = spy.getQueryBuilder().createQueryFromURI(new URI("network/generic-vnfs/generic-vnf/key1")); + Introspector obj = loader.introspectorFromName("generic-vnf"); + Vertex v = g.addVertex(); + Object id = v.id(); + obj.setValue("vnf-id", "key1"); + obj.setValue(property, "hello"); + serializer.serializeToDb(obj, v, uriQuery, "", ""); + g.tx().commit(); + v = graph.traversal().V(id).next(); + Map map = obj.getPropertyMetadata(property); + if (map.containsKey(PropertyMetadata.DB_ALIAS)) { + dbPropertyName = map.get(PropertyMetadata.DB_ALIAS); + } + + assertEquals("dbAlias is ", "model-customization-id", dbPropertyName); + assertEquals("dbAlias property exists", "hello", v.property(dbPropertyName).orElse("")); + assertEquals("model property does not", "missing", v.property(property).orElse("missing")); + + } + + @Test + public void checkOnRead() throws AAIException, UnsupportedEncodingException, URISyntaxException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, NoSuchMethodException, InterruptedException, MalformedURLException { + final String property = "persona-model-customization-id"; + + TransactionalGraphEngine spy = spy(dbEngine); + TransactionalGraphEngine.Admin adminSpy = spy(dbEngine.asAdmin()); + Vertex v = graph.traversal().addV("vnf-id", "key1", "model-customization-id", "hello").next(); + graph.tx().commit(); + Graph g = graph.newTransaction(); + GraphTraversalSource traversal = g.traversal(); + when(spy.asAdmin()).thenReturn(adminSpy); + when(adminSpy.getTraversalSource()).thenReturn(traversal); + DBSerializer serializer = new DBSerializer(version, spy, introspectorFactoryType, "AAI_TEST"); + Introspector obj = loader.introspectorFromName("generic-vnf"); + serializer.dbToObject(Collections.singletonList(v), obj, 0, true, "false"); + + assertEquals("dbAlias property exists", "hello", obj.getValue(property)); + + } + + +} diff --git a/aai-core/src/test/java/org/onap/aai/serialization/db/DbSerializerTest.java b/aai-core/src/test/java/org/onap/aai/serialization/db/DbSerializerTest.java new file mode 100644 index 00000000..c89150b6 --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/serialization/db/DbSerializerTest.java @@ -0,0 +1,441 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.serialization.db; + +import com.thinkaurelius.titan.core.TitanFactory; +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; +import org.apache.tinkerpop.gremlin.structure.Edge; +import org.apache.tinkerpop.gremlin.structure.Graph; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph; +import org.junit.After; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.onap.aai.AAISetup; +import org.onap.aai.db.props.AAIProperties; +import org.onap.aai.dbmap.DBConnectionType; +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.Introspector; +import org.onap.aai.introspection.Loader; +import org.onap.aai.introspection.LoaderFactory; +import org.onap.aai.introspection.ModelType; +import org.onap.aai.introspection.Version; +import org.onap.aai.serialization.engines.QueryStyle; +import org.onap.aai.serialization.engines.TitanDBEngine; +import org.onap.aai.serialization.engines.TransactionalGraphEngine; + +import static org.junit.Assert.*; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class DbSerializerTest extends AAISetup { + + //to use, set thrown.expect to whatever your test needs + //this line establishes default of expecting no exception to be thrown + @Rule + public ExpectedException thrown = ExpectedException.none(); + + protected Graph graph; + protected final EdgeRules rules = EdgeRules.getInstance(); + + private final Version version = Version.getLatest(); + private final ModelType introspectorFactoryType = ModelType.MOXY; + private final QueryStyle queryStyle = QueryStyle.TRAVERSAL; + private final DBConnectionType type = DBConnectionType.REALTIME; + private Loader loader; + private TransactionalGraphEngine dbEngine; + private TransactionalGraphEngine engine; //for tests that aren't mocking the engine + private DBSerializer dbser; + TransactionalGraphEngine spy; + TransactionalGraphEngine.Admin adminSpy; + + @Before + public void setup() throws Exception { + graph = TitanFactory.build().set("storage.backend", "inmemory").open(); + loader = LoaderFactory.createLoaderForVersion(introspectorFactoryType, version); + dbEngine = new TitanDBEngine(queryStyle, type, loader); + spy = spy(dbEngine); + adminSpy = spy(dbEngine.asAdmin()); + + createGraph(); + + engine = new TitanDBEngine(queryStyle, type, loader); + dbser = new DBSerializer(Version.getLatest(), engine, introspectorFactoryType, "AAI-TEST"); + } + + public void createGraph() throws AAIException { + /* + * This setus up the test graph, For future junits , add more vertices + * and edges + */ + + Vertex l3interipv4addresslist_1 = graph.traversal().addV("aai-node-type", "l3-interface-ipv4-address-list", + "l3-interface-ipv4-address", "l3-interface-ipv4-address-1").next(); + Vertex subnet_2 = graph.traversal().addV("aai-node-type", "subnet", "subnet-id", "subnet-id-2").next(); + Vertex l3interipv6addresslist_3 = graph.traversal().addV("aai-node-type", "l3-interface-ipv6-address-list", + "l3-interface-ipv6-address", "l3-interface-ipv6-address-3").next(); + Vertex subnet_4 = graph.traversal().addV("aai-node-type", "subnet", "subnet-id", "subnet-id-4").next(); + Vertex subnet_5 = graph.traversal().addV("aai-node-type", "subnet", "subnet-id", "subnet-id-5").next(); + Vertex l3network_6 = graph.traversal() + .addV("aai-node-type", "l3-network", "network-id", "network-id-6", "network-name", "network-name-6") + .next(); + + GraphTraversalSource g = graph.traversal(); + rules.addEdge(g, l3interipv4addresslist_1, subnet_2); + rules.addEdge(g, l3interipv6addresslist_3, subnet_4); + rules.addTreeEdge(g, subnet_5, l3network_6); + + } + + @After + public void tearDown() throws Exception { + graph.close(); + } + + @Test + public void subnetDelwithInEdgesIpv4Test() throws AAIException { + String expected_message = "Object is being reference by additional objects preventing it from being deleted. Please clean up references from the following types [l3-interface-ipv4-address-list]"; + + /* + * This subnet has in-edges with l3-ipv4 and NOT ok to delete + */ + Vertex subnet = graph.traversal().V().has("aai-node-type", "subnet").has("subnet-id", "subnet-id-2").next(); + + String exceptionMessage = testDelete(subnet); + assertEquals(expected_message, exceptionMessage); + + } + + @Test + public void subnetDelwithInEdgesIpv6Test() throws AAIException { + String expected_message = "Object is being reference by additional objects preventing it from being deleted. Please clean up references from the following types [l3-interface-ipv6-address-list]"; + + /* + * This subnet has in-edges with l3-ipv6 and NOT ok to delete + */ + Vertex subnet = graph.traversal().V().has("aai-node-type", "subnet").has("subnet-id", "subnet-id-4").next(); + String exceptionMessage = testDelete(subnet); + assertEquals(expected_message, exceptionMessage); + + } + + @Test + public void subnetDelwithInEdgesL3network() throws AAIException { + String expected_message = ""; + + /* + * This subnet has in-edges with l3-network and ok to delete + */ + Vertex subnet = graph.traversal().V().has("aai-node-type", "subnet").has("subnet-id", "subnet-id-5").next(); + + String exceptionMessage = testDelete(subnet); + assertEquals(expected_message, exceptionMessage); + + } + + public String testDelete(Vertex v) throws AAIException { + + // Graph g_tx = graph.newTransaction(); + GraphTraversalSource traversal = graph.traversal(); + when(spy.asAdmin()).thenReturn(adminSpy); + when(adminSpy.getTraversalSource()).thenReturn(traversal); + when(adminSpy.getReadOnlyTraversalSource()).thenReturn(traversal); + + String exceptionMessage = ""; + DBSerializer serializer = new DBSerializer(version, spy, introspectorFactoryType, "AAI_TEST"); + try { + serializer.delete(v, "resourceVersion", false); + } catch (AAIException exception) { + exceptionMessage = exception.getMessage(); + + } + return exceptionMessage; + + } + + @Test + public void createNewVertexTest() throws AAIException { + engine.startTransaction(); + + Introspector testObj = loader.introspectorFromName("generic-vnf"); + + Vertex testVertex = dbser.createNewVertex(testObj); + Vertex fromGraph = engine.tx().traversal().V().has("aai-node-type","generic-vnf").toList().get(0); + assertEquals(testVertex.id(), fromGraph.id()); + assertEquals("AAI-TEST", fromGraph.property(AAIProperties.SOURCE_OF_TRUTH.toString()).value()); + engine.rollback(); + } + + @Test + public void touchStandardVertexPropertiesTest() throws AAIException, InterruptedException { + engine.startTransaction(); + DBSerializer dbser2 = new DBSerializer(Version.getLatest(), engine, introspectorFactoryType, "AAI-TEST-2"); + + Graph graph = TinkerGraph.open(); + Vertex vert = graph.addVertex("aai-node-type", "generic-vnf"); + + dbser.touchStandardVertexProperties(vert, true); + String resverStart = (String)vert.property(AAIProperties.RESOURCE_VERSION.toString()).value(); + String lastModTimeStart = (String)vert.property(AAIProperties.LAST_MOD_TS.toString()).value(); + + Thread.sleep(10); //bc the resource version is set based on current time in milliseconds, + //if this test runs through too fast the value may not change + //causing the test to fail. sleeping ensures a different value + + dbser2.touchStandardVertexProperties(vert, false); + assertFalse(resverStart.equals((String)vert.property(AAIProperties.RESOURCE_VERSION.toString()).value())); + assertFalse(lastModTimeStart.equals((String)vert.property(AAIProperties.LAST_MOD_TS.toString()).value())); + assertEquals("AAI-TEST-2", (String)vert.property(AAIProperties.LAST_MOD_SOURCE_OF_TRUTH.toString()).value()); + engine.rollback(); + } + + @Test + public void verifyResourceVersion_SunnyDayTest() throws AAIException { + engine.startTransaction(); + + assertTrue(dbser.verifyResourceVersion("delete", "vnfc", "abc", "abc", "vnfcs/vnfc/vnfcId")); + engine.rollback(); + } + + @Test + public void verifyResourceVersion_CreateWithRVTest() throws AAIException { + engine.startTransaction(); + + thrown.expect(AAIException.class); + thrown.expectMessage("resource-version passed for create of generic-vnfs/generic-vnf/myid"); + try { + dbser.verifyResourceVersion("create", "generic-vnf", null, "old-res-ver", "generic-vnfs/generic-vnf/myid"); + } finally { + engine.rollback(); + } + } + + @Test + public void verifyResourceVersion_MissingRVTest() throws AAIException { + engine.startTransaction(); + + thrown.expect(AAIException.class); + thrown.expectMessage("resource-version not passed for update of generic-vnfs/generic-vnf/myid"); + try { + dbser.verifyResourceVersion("update", "generic-vnf", "current-res-ver", null, "generic-vnfs/generic-vnf/myid"); + } finally { + engine.rollback(); + } + } + + @Test + public void verifyResourceVersion_MismatchRVTest() throws AAIException { + engine.startTransaction(); + + thrown.expect(AAIException.class); + thrown.expectMessage("resource-version MISMATCH for update of generic-vnfs/generic-vnf/myid"); + try { + dbser.verifyResourceVersion("update", "generic-vnf", "current-res-ver", "old-res-ver", "generic-vnfs/generic-vnf/myid"); + } finally { + engine.rollback(); + } + } + + @Test + public void trimClassNameTest() throws AAIException { + assertEquals("GenericVnf", dbser.trimClassName("GenericVnf")); + assertEquals("GenericVnf", dbser.trimClassName("org.onap.aai.GenericVnf")); + } + + @Test + public void getURIForVertexTest() throws AAIException, URISyntaxException, UnsupportedEncodingException { + engine.startTransaction(); + + Vertex cr = engine.tx().addVertex("aai-node-type", "cloud-region", "cloud-owner", "me", "cloud-region-id", "123"); + Vertex ten = engine.tx().addVertex("aai-node-type", "tenant", "tenant-id", "453"); + EdgeRules rules = EdgeRules.getInstance(); + rules.addTreeEdge(engine.tx().traversal(), cr, ten); + + URI compare = new URI("/cloud-infrastructure/cloud-regions/cloud-region/me/123/tenants/tenant/453"); + assertEquals(compare, dbser.getURIForVertex(ten)); + + cr.property("aai-node-type").remove(); + URI compareFailure = new URI("/unknown-uri"); + assertEquals(compareFailure, dbser.getURIForVertex(ten)); + engine.rollback(); + } + + @Test + public void getVertexPropertiesTest() throws AAIException, UnsupportedEncodingException { + engine.startTransaction(); + + Vertex cr = engine.tx().addVertex("aai-node-type", "cloud-region", "cloud-owner", "me", "cloud-region-id", "123"); + + Introspector crIntro = dbser.getVertexProperties(cr); + assertEquals("cloud-region", crIntro.getDbName()); + assertEquals("me", crIntro.getValue("cloud-owner")); + assertEquals("123", crIntro.getValue("cloud-region-id")); + engine.rollback(); + } + + @Test + public void setCachedURIsTest() throws AAIException, UnsupportedEncodingException, URISyntaxException { + engine.startTransaction(); + + Vertex cr = engine.tx().addVertex("aai-node-type", "cloud-region", "cloud-owner", "me", "cloud-region-id", "123"); + Vertex ten = engine.tx().addVertex("aai-node-type", "tenant", "tenant-id", "453"); + Vertex vs = engine.tx().addVertex("aai-node-type", "vserver", "vserver-id", "vs1", + AAIProperties.AAI_URI.toString(), + "/cloud-infrastructure/cloud-regions/cloud-region/me/123/tenants/tenant/453/vservers/vserver/vs1"); + EdgeRules rules = EdgeRules.getInstance(); + rules.addTreeEdge(engine.tx().traversal(), cr, ten); + rules.addTreeEdge(engine.tx().traversal(), ten, vs); + + List vertices = new ArrayList(Arrays.asList(cr, ten, vs)); + Introspector crIn = dbser.getVertexProperties(cr); + Introspector tenIn = dbser.getVertexProperties(ten); + Introspector vsIn = dbser.getVertexProperties(vs); + List intros = new ArrayList(Arrays.asList(crIn, tenIn, vsIn)); + + dbser.setCachedURIs(vertices, intros); + + assertEquals("/cloud-infrastructure/cloud-regions/cloud-region/me/123", + (String)cr.property(AAIProperties.AAI_URI.toString()).value()); + assertEquals("/cloud-infrastructure/cloud-regions/cloud-region/me/123/tenants/tenant/453", + (String)ten.property(AAIProperties.AAI_URI.toString()).value()); + assertEquals("/cloud-infrastructure/cloud-regions/cloud-region/me/123/tenants/tenant/453/vservers/vserver/vs1", + (String)vs.property(AAIProperties.AAI_URI.toString()).value()); + engine.rollback(); + } + + @Test + public void getEdgeBetweenTest() throws AAIException { + engine.startTransaction(); + + Vertex cr = engine.tx().addVertex("aai-node-type", "cloud-region", "cloud-owner", "me", "cloud-region-id", "123"); + Vertex ten = engine.tx().addVertex("aai-node-type", "tenant", "tenant-id", "453"); + EdgeRules rules = EdgeRules.getInstance(); + rules.addTreeEdge(engine.tx().traversal(), cr, ten); + + Edge e = dbser.getEdgeBetween(EdgeType.TREE, ten, cr); + assertEquals("has", e.label()); + engine.rollback(); + } + + @Test + public void deleteEdgeTest() throws AAIException, UnsupportedEncodingException { + engine.startTransaction(); + + Vertex gvnf = engine.tx().addVertex("aai-node-type","generic-vnf","vnf-id","myvnf"); + Vertex vnfc = engine.tx().addVertex("aai-node-type","vnfc","vnfc-name","a-name"); + EdgeRules rules = EdgeRules.getInstance(); + rules.addEdge(engine.tx().traversal(), gvnf, vnfc); + + Introspector relData = loader.introspectorFromName("relationship-data"); + relData.setValue("relationship-key", "vnfc.vnfc-name"); + relData.setValue("relationship-value", "a-name"); + Introspector relationship = loader.introspectorFromName("relationship"); + relationship.setValue("related-to", "vnfc"); + relationship.setValue("related-link", "/network/vnfcs/vnfc/a-name"); + relationship.setValue("relationship-data",relData); + + assertTrue(dbser.deleteEdge(relationship, gvnf)); + + assertFalse(engine.tx().traversal().V(gvnf).both("uses").hasNext()); + assertFalse(engine.tx().traversal().V(vnfc).both("uses").hasNext()); + engine.rollback(); + } + + @Test + public void createEdgeTest() throws AAIException, UnsupportedEncodingException { + engine.startTransaction(); + + Vertex gvnf = engine.tx().addVertex("aai-node-type","generic-vnf","vnf-id","myvnf"); + Vertex vnfc = engine.tx().addVertex("aai-node-type","vnfc","vnfc-name","a-name"); + + //sunny day case + Introspector relData = loader.introspectorFromName("relationship-data"); + relData.setValue("relationship-key", "vnfc.vnfc-name"); + relData.setValue("relationship-value", "a-name"); + Introspector relationship = loader.introspectorFromName("relationship"); + relationship.setValue("related-to", "vnfc"); + relationship.setValue("related-link", "/network/vnfcs/vnfc/a-name"); + relationship.setValue("relationship-data",relData); + + assertTrue(dbser.createEdge(relationship, gvnf)); + assertTrue(engine.tx().traversal().V(gvnf).both("uses").hasNext()); + assertTrue(engine.tx().traversal().V(vnfc).both("uses").hasNext()); + + //rainy day case, edge to nonexistant object + Introspector relData2 = loader.introspectorFromName("relationship-data"); + relData2.setValue("relationship-key", "vnfc.vnfc-name"); + relData2.setValue("relationship-value", "b-name"); + Introspector relationship2 = loader.introspectorFromName("relationship"); + relationship2.setValue("related-to", "vnfc"); + relationship2.setValue("related-link", "/network/vnfcs/vnfc/b-name"); + relationship2.setValue("relationship-data",relData2); + + thrown.expect(AAIException.class); + thrown.expectMessage("Node of type vnfc. Could not find object at: /network/vnfcs/vnfc/b-name"); + try { + dbser.createEdge(relationship2, gvnf); + } finally { + engine.rollback(); + } + } + + @Test + public void serializeSingleVertexTopLevelTest() throws AAIException, UnsupportedEncodingException { + engine.startTransaction(); + + Introspector gvnf = loader.introspectorFromName("generic-vnf"); + Vertex gvnfVert = dbser.createNewVertex(gvnf); + + gvnf.setValue("vnf-id", "myvnf"); + dbser.serializeSingleVertex(gvnfVert, gvnf, "test"); + assertTrue(engine.tx().traversal().V().has("aai-node-type","generic-vnf").has("vnf-id","myvnf").hasNext()); + engine.rollback(); + } + + @Test + public void serializeSingleVertexChildTest() throws AAIException, UnsupportedEncodingException { + engine.startTransaction(); + + Vertex cr = engine.tx().addVertex("aai-node-type", "cloud-region", "cloud-owner", "me", "cloud-region-id", "123"); + Introspector tenIn = loader.introspectorFromName("tenant"); + Vertex ten = dbser.createNewVertex(tenIn); + EdgeRules rules = EdgeRules.getInstance(); + rules.addTreeEdge(engine.tx().traversal(), cr, ten); + + tenIn.setValue("tenant-id", "453"); + tenIn.setValue("tenant-name", "mytenant"); + + dbser.serializeSingleVertex(ten, tenIn, "test"); + + assertTrue(engine.tx().traversal().V().has("aai-node-type","tenant").has("tenant-id","453").has("tenant-name","mytenant").hasNext()); + engine.rollback(); + } +} \ No newline at end of file diff --git a/aai-core/src/test/java/org/onap/aai/serialization/db/EdgePropertyMapTest.java b/aai-core/src/test/java/org/onap/aai/serialization/db/EdgePropertyMapTest.java new file mode 100644 index 00000000..8dbb8000 --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/serialization/db/EdgePropertyMapTest.java @@ -0,0 +1,44 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.serialization.db; + +import org.junit.Test; + +import java.util.Map; + +import static org.junit.Assert.assertEquals; + +public class EdgePropertyMapTest { + + @Test + public void run() { + Map map = new EdgePropertyMap<>(); + map.put("direction", "OUT"); + map.put("test", "hello"); + map.put("isParent", "${direction}"); + map.put("SVC-INFRA", "!${direction}"); + + assertEquals("normal retrieval", "hello", map.get("test")); + assertEquals("variable retrieval", "OUT", map.get("isParent")); + assertEquals("negate variable retrieval", "IN", map.get("SVC-INFRA")); + } +} diff --git a/aai-core/src/test/java/org/onap/aai/serialization/db/EdgeRulesTest.java b/aai-core/src/test/java/org/onap/aai/serialization/db/EdgeRulesTest.java new file mode 100644 index 00000000..4bf6a6c2 --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/serialization/db/EdgeRulesTest.java @@ -0,0 +1,238 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.serialization.db; + + +import org.apache.tinkerpop.gremlin.structure.Direction; +import org.junit.Test; +import org.onap.aai.AAISetup; +import static org.junit.Assert.assertEquals; + +import java.util.Map; +import java.util.Set; + +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; +import org.apache.tinkerpop.gremlin.structure.Graph; +import org.apache.tinkerpop.gremlin.structure.T; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph; +import org.junit.Rule; +import org.junit.rules.ExpectedException; + +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.Version; +import org.onap.aai.serialization.db.exceptions.EdgeMultiplicityException; +import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException; + +import com.google.common.collect.Multimap; + +public class EdgeRulesTest extends AAISetup { + + //set thrown.expect to whatever a specific test needs + //this establishes a default of expecting no exceptions to be thrown + @Rule + public ExpectedException thrown = ExpectedException.none(); + + @Test + public void verifyOutDirection() throws AAIException, NoEdgeRuleFoundException { + EdgeRules rules = EdgeRules.getInstance(); + EdgeRule rule = rules.getEdgeRule(EdgeType.TREE, "cloud-region", "flavor"); + + assertEquals("out direction", rule.getDirection(), Direction.OUT); + } + + @Test + public void verifyOutFlippedDirection() throws AAIException, NoEdgeRuleFoundException { + EdgeRules rules = EdgeRules.getInstance(); + EdgeRule rule = rules.getEdgeRule(EdgeType.TREE, "flavor", "cloud-region"); + + assertEquals("in direction", rule.getDirection(), Direction.IN); + } + + @Test + public void verifyInDirection() throws AAIException, NoEdgeRuleFoundException { + EdgeRules rules = EdgeRules.getInstance(); + EdgeRule rule = rules.getEdgeRule(EdgeType.COUSIN, "model-ver", "model-element"); + + assertEquals("in direction", rule.getDirection(), Direction.IN); + } + + @Test + public void verifyInFlippedDirection() throws AAIException, NoEdgeRuleFoundException { + EdgeRules rules = EdgeRules.getInstance(); + EdgeRule rule = rules.getEdgeRule(EdgeType.COUSIN, "model-element", "model-ver"); + + assertEquals("out direction", rule.getDirection(), Direction.OUT); + } + @Test + public void verifyMultipleGet() throws AAIException { + EdgeRules rules = EdgeRules.getInstance(); + Map ruleMap = rules.getEdgeRules("model-element", "model-ver"); + assertEquals("has isA rule", "isA", ruleMap.get("isA").getLabel()); + assertEquals("has startsWith rule", "startsWith", ruleMap.get("startsWith").getLabel()); + } + + @Test + public void verifyMultipleGetSingleRule() throws AAIException { + EdgeRules rules = EdgeRules.getInstance(); + Map ruleMap = rules.getEdgeRules("availability-zone", "complex"); + assertEquals("has groupsResourcesIn rule", "groupsResourcesIn", ruleMap.get("groupsResourcesIn").getLabel()); + } + + @Test + public void verifyOldEdgeRule() throws AAIException, ClassNotFoundException, IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { + assertEquals(true, EdgeRules.getInstance().hasEdgeRule("model-element", "model-ver")); + assertEquals(true, EdgeRules.getInstance(Version.v8).hasEdgeRule("pserver", "complex")); + assertEquals(false, EdgeRules.getInstance(Version.v8).hasEdgeRule("model-element", "model-ver")); + } + + @Test + public void hasEdgeRuleVertexTest() { + Graph graph = TinkerGraph.open(); + Vertex v1 = graph.addVertex("aai-node-type", "cloud-region"); + Vertex v2 = graph.addVertex("aai-node-type", "tenant"); + assertEquals(true, EdgeRules.getInstance().hasEdgeRule(v1, v2)); + } + + @Test + public void getEdgeRuleByTypeAndVertices() throws AAIException { + Graph graph = TinkerGraph.open(); + Vertex v1 = graph.addVertex("aai-node-type", "cloud-region"); + Vertex v2 = graph.addVertex("aai-node-type", "tenant"); + EdgeRules rules = EdgeRules.getInstance(); + EdgeRule rule = rules.getEdgeRule(EdgeType.TREE, v1, v2); + assertEquals(true, "OUT".equalsIgnoreCase(rule.getContains())); + assertEquals(true, "NONE".equalsIgnoreCase(rule.getDeleteOtherV())); + assertEquals(true, MultiplicityRule.ONE2MANY.equals(rule.getMultiplicityRule())); + assertEquals(true, "IN".equalsIgnoreCase(rule.getServiceInfrastructure())); + assertEquals(true, "OUT".equalsIgnoreCase(rule.getPreventDelete())); + } + + @Test + public void addTreeEdgeTest() throws AAIException { + Graph graph = TinkerGraph.open(); + Vertex v1 = graph.addVertex(T.id, "1", "aai-node-type", "cloud-region"); + Vertex v2 = graph.addVertex(T.id, "10", "aai-node-type", "tenant"); + EdgeRules rules = EdgeRules.getInstance(); + GraphTraversalSource g = graph.traversal(); + rules.addTreeEdge(g, v1, v2); + assertEquals(true, g.V(v1).out("has").has("aai-node-type", "tenant").hasNext()); + + Vertex v3 = graph.addVertex(T.id, "2", "aai-node-type", "cloud-region"); + assertEquals(null, rules.addTreeEdgeIfPossible(g, v3, v2)); + } + + @Test + public void addCousinEdgeTest() throws AAIException { + Graph graph = TinkerGraph.open(); + Vertex v1 = graph.addVertex(T.id, "1", "aai-node-type", "flavor"); + Vertex v2 = graph.addVertex(T.id, "10", "aai-node-type", "vserver"); + EdgeRules rules = EdgeRules.getInstance(Version.getLatest()); + GraphTraversalSource g = graph.traversal(); + rules.addEdge(g, v1, v2); + assertEquals(true, g.V(v2).out("hasFlavor").has("aai-node-type", "flavor").hasNext()); + + Vertex v3 = graph.addVertex(T.id, "2", "aai-node-type", "flavor"); + assertEquals(null, rules.addEdgeIfPossible(g, v3, v2)); + } + + @Test + public void multiplicityViolationTest() throws AAIException { + thrown.expect(EdgeMultiplicityException.class); + thrown.expectMessage("multiplicity rule violated: only one edge can exist with label: uses between vf-module and volume-group"); + + Graph graph = TinkerGraph.open(); + Vertex v1 = graph.addVertex(T.id, "1", "aai-node-type", "vf-module"); + Vertex v2 = graph.addVertex(T.id, "10", "aai-node-type", "volume-group"); + EdgeRules rules = EdgeRules.getInstance(Version.getLatest()); + GraphTraversalSource g = graph.traversal(); + + rules.addEdge(g, v2, v1); + Vertex v3 = graph.addVertex(T.id, "3", "aai-node-type", "vf-module"); + rules.addEdge(g, v2, v3); + } + + @Test + public void getChildrenTest() { + EdgeRules rules = EdgeRules.getInstance("/dbedgerules/DbEdgeRules_test.json"); + Set children = rules.getChildren("foo"); + assertEquals(2, children.size()); + boolean sawBazRule = false; + boolean sawQuuxRule = false; + for (EdgeRule r : children) { + if ("isVeryHappyAbout".equals(r.getLabel())) { + sawBazRule = true; + } else if ("dancesWith".equals(r.getLabel())) { + sawQuuxRule = true; + } + } + assertEquals(true, sawBazRule && sawQuuxRule); + } + + @Test + public void getAllRulesTest() { + EdgeRules rules = EdgeRules.getInstance("/dbedgerules/DbEdgeRules_test.json"); + Multimap allRules = rules.getAllRules(); + assertEquals(3, allRules.size()); + assertEquals(true, allRules.containsKey("foo|bar")); + assertEquals(true, allRules.containsKey("foo|bar")); + assertEquals(true, allRules.containsKey("quux|foo")); + } + + @Test + public void getAllRulesMissingPropertyTest() { + EdgeRules rules = EdgeRules.getInstance("/dbedgerules/DbEdgeRules_test_broken.json"); + + thrown.expect(RuntimeException.class); + thrown.expectMessage("org.onap.aai.exceptions.AAIException: Rule between foo and bar is missing property delete-other-v."); + rules.getAllRules(); + } + + @Test + public void getChildrenMissingPropertyTest() { + EdgeRules rules = EdgeRules.getInstance("/dbedgerules/DbEdgeRules_test_broken.json"); + + thrown.expect(RuntimeException.class); + thrown.expectMessage("org.onap.aai.exceptions.AAIException: Rule between quux and foo is missing property SVC-INFRA."); + rules.getChildren("foo"); + } + + @Test + public void getEdgeRuleMissingPropertyTest() throws AAIException { + EdgeRules rules = EdgeRules.getInstance("/dbedgerules/DbEdgeRules_test_broken.json"); + + thrown.expect(RuntimeException.class); + thrown.expectMessage("org.onap.aai.exceptions.AAIException: Rule between quux and foo is missing property SVC-INFRA."); + rules.getEdgeRules("foo", "quux"); + } + + @Test + public void verifyAllRules() { + // This will cause every rule in the real json files to be verified + // so if any required properties are missing, the verification builds + // will catch it and incorrect rules can't get merged in. + for (Version v : Version.values()) { + EdgeRules rules = EdgeRules.getInstance(v); + rules.getAllRules(); + } + } +} diff --git a/aai-core/src/test/java/org/onap/aai/serialization/queryformats/QueryFormatTestHelper.java b/aai-core/src/test/java/org/onap/aai/serialization/queryformats/QueryFormatTestHelper.java new file mode 100644 index 00000000..53d1d293 --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/serialization/queryformats/QueryFormatTestHelper.java @@ -0,0 +1,76 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.serialization.queryformats; + +import org.apache.tinkerpop.gremlin.structure.Graph; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.apache.tinkerpop.gremlin.structure.io.IoCore; +import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; +import org.onap.aai.db.props.AAIProperties; +import org.onap.aai.serialization.queryformats.exceptions.AAIFormatVertexException; +import org.onap.aai.serialization.queryformats.utils.UrlBuilder; + +import java.io.IOException; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; + +import static org.mockito.Matchers.isA; +import static org.mockito.Mockito.when; + +public class QueryFormatTestHelper { + + + public static final String testResources = "src/test/resources/org.onap.aai/serialization/queryformats/"; + public static final String graphsonResources = "src/test/resources/org.onap.aai/serialization/queryformats/graphson/"; + + + public static void mockPathed(UrlBuilder mock) throws AAIFormatVertexException { + Answer answer = new Answer() { + public String answer(InvocationOnMock invocation) throws Throwable { + Vertex v = invocation.getArgumentAt(0, Vertex.class); + + return v.property(AAIProperties.AAI_URI).orElse("urimissing"); + } + }; + when(mock.pathed(isA(Vertex.class))).thenAnswer(answer); + + } + + public static Graph loadGraphson(String fileName) throws IOException { + final Graph graph = TinkerGraph.open(); + graph.io(IoCore.graphson()).readGraph(QueryFormatTestHelper.graphsonResources + fileName); + + return graph; + } + + public static void setFinalStatic(Field field, Object newValue) throws Exception { + field.setAccessible(true); + // remove final modifier from field + Field modifiersField = Field.class.getDeclaredField("modifiers"); + modifiersField.setAccessible(true); + modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); + field.set(null, newValue); + } + +} diff --git a/aai-core/src/test/java/org/onap/aai/serialization/queryformats/SimpleFormatTest.java b/aai-core/src/test/java/org/onap/aai/serialization/queryformats/SimpleFormatTest.java new file mode 100644 index 00000000..5e400116 --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/serialization/queryformats/SimpleFormatTest.java @@ -0,0 +1,164 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.serialization.queryformats; + +import com.google.gson.JsonObject; +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; +import org.apache.tinkerpop.gremlin.process.traversal.strategy.verification.ReadOnlyStrategy; +import org.apache.tinkerpop.gremlin.structure.Graph; +import org.apache.tinkerpop.gremlin.structure.T; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.aai.dbmap.DBConnectionType; +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.Loader; +import org.onap.aai.introspection.LoaderFactory; +import org.onap.aai.introspection.ModelType; +import org.onap.aai.introspection.Version; +import org.onap.aai.introspection.exceptions.AAIUnknownObjectException; +import org.onap.aai.serialization.db.DBSerializer; +import org.onap.aai.serialization.engines.QueryStyle; +import org.onap.aai.serialization.engines.TitanDBEngine; +import org.onap.aai.serialization.engines.TransactionalGraphEngine; +import org.onap.aai.serialization.queryformats.exceptions.AAIFormatVertexException; +import org.onap.aai.serialization.queryformats.utils.UrlBuilder; + +import java.io.UnsupportedEncodingException; + +import static org.junit.Assert.*; +import static org.mockito.Matchers.anyBoolean; +import static org.mockito.Matchers.anyInt; +import static org.mockito.Matchers.anyObject; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.*; + +public class SimpleFormatTest { + + @Mock + private UrlBuilder urlBuilder; + + private Graph graph; + private TransactionalGraphEngine dbEngine; + private Loader loader; + private DBSerializer serializer; + private RawFormat simpleFormat; + private Vertex vfModule; + private final ModelType factoryType = ModelType.MOXY; + + @Before + public void setUp() throws Exception { + + MockitoAnnotations.initMocks(this); + + graph = TinkerGraph.open(); + + vfModule = graph.addVertex( + T.label, "vf-module", + T.id, "5", + "aai-node-type", "vf-module", + "vf-module-id", "vf-module-id-val-68205", + "vf-module-name", "example-vf-module-name-val-68205", + "heat-stack-id", "example-heat-stack-id-val-68205", + "orchestration-status", "example-orchestration-status-val-68205", + "is-base-vf-module", "true", + "resource-version", "1498166571906", + "model-invariant-id", "fe8aac07-ce6c-4f9f-aa0d-b561c77da9e8", + "model-invariant-id-local", "fe8aac07-ce6c-4f9f-aa0d-b561c77da9e8", + "model-version-id", "0d23052d-8ffe-433e-a25d-da5da027bb7c", + "model-version-id-local", "0d23052d-8ffe-433e-a25d-da5da027bb7c", + "widget-model-id", "example-widget-model-id-val-68205", + "widget-model-version", "example-widget--model-version-val-68205", + "contrail-service-instance-fqdn", "example-contrail-service-instance-fqdn-val-68205" + ); + } + + @Test + public void testCreatePropertiesObjectReturnsProperProperties() throws AAIFormatVertexException, AAIException { + + createLoaderEngineSetup(); + serializer = new DBSerializer(Version.v10, dbEngine, factoryType, "Junit"); + simpleFormat = new RawFormat.Builder(loader, serializer, urlBuilder).nodesOnly(true).depth(0).modelDriven().build(); + + assertNotNull(dbEngine.tx()); + assertNotNull(dbEngine.asAdmin()); + + JsonObject json = simpleFormat.createPropertiesObject(vfModule); + + assertTrue(json.has("model-invariant-id")); + assertTrue(json.has("model-version-id")); + + assertFalse(json.has("model-invariant-id-local")); + assertFalse(json.has("model-version-id-local")); + + } + + @Ignore + @Test(expected = AAIFormatVertexException.class) + public void testCreatePropertiesObjectThrowsExceptionIfSerializationFails() throws AAIFormatVertexException, AAIException, UnsupportedEncodingException { + + serializer = mock(DBSerializer.class); + loader = mock(Loader.class); + + simpleFormat = new RawFormat.Builder(loader, serializer, urlBuilder).nodesOnly(true).depth(0).build(); + + when(serializer.dbToObject(anyObject(), anyObject(), anyInt(), anyBoolean(), anyString())) + .thenThrow(new AAIException("Test Exception")); + + simpleFormat.createPropertiesObject(vfModule); + } + + @Ignore + @Test(expected = AAIFormatVertexException.class) + public void testCreatePropertiesObjectThrowsExceptionIfUnknownObject() throws AAIFormatVertexException, AAIException, UnsupportedEncodingException { + + loader = mock(Loader.class); + serializer = mock(DBSerializer.class); + + simpleFormat = new RawFormat.Builder(loader, serializer, urlBuilder).nodesOnly(true).depth(0).build(); + + when(loader.introspectorFromName(anyString())) + .thenThrow(new AAIUnknownObjectException("Test Exception")); + + simpleFormat.createPropertiesObject(vfModule); + } + + public void createLoaderEngineSetup(){ + + if(loader == null){ + loader = LoaderFactory.createLoaderForVersion(factoryType, Version.v10); + dbEngine = spy(new TitanDBEngine(QueryStyle.TRAVERSAL, DBConnectionType.CACHED, loader)); + + TransactionalGraphEngine.Admin spyAdmin = spy(dbEngine.asAdmin()); + + when(dbEngine.tx()).thenReturn(graph); + when(dbEngine.asAdmin()).thenReturn(spyAdmin); + + when(spyAdmin.getReadOnlyTraversalSource()).thenReturn(graph.traversal(GraphTraversalSource.build().with(ReadOnlyStrategy.instance()))); + when(spyAdmin.getTraversalSource()).thenReturn(graph.traversal()); + } + } +} diff --git a/aai-core/src/test/java/org/onap/aai/serialization/queryformats/utils/QueryParamInjectorTest.java b/aai-core/src/test/java/org/onap/aai/serialization/queryformats/utils/QueryParamInjectorTest.java new file mode 100644 index 00000000..3c1b033c --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/serialization/queryformats/utils/QueryParamInjectorTest.java @@ -0,0 +1,60 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.serialization.queryformats.utils; + +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.Loader; +import org.onap.aai.serialization.db.DBSerializer; +import org.onap.aai.serialization.queryformats.Resource; +import org.onap.aai.serialization.queryformats.Resource.Builder; + +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; + +import static org.junit.Assert.assertEquals; + +public class QueryParamInjectorTest { + + + @Mock private Loader loader; + @Mock private DBSerializer serializer; + @Mock private UrlBuilder urlBuilder; + + @Test + public void test() throws AAIException { + MockitoAnnotations.initMocks(this); + QueryParamInjector injector = QueryParamInjector.getInstance(); + + Builder b = new Resource.Builder(loader, serializer, urlBuilder); + MultivaluedMap params = new MultivaluedHashMap<>(); + params.putSingle("nodesOnly", "true"); + params.putSingle("depth", "10"); + params.putSingle("invalid", "1000"); + injector.injectParams(b, params); + + assertEquals("is nodes only", true, b.isNodesOnly()); + assertEquals("is depth 10", 10, b.getDepth()); + } +} diff --git a/aai-core/src/test/java/org/onap/aai/serialization/queryformats/utils/UrlBuilderTest.java b/aai-core/src/test/java/org/onap/aai/serialization/queryformats/utils/UrlBuilderTest.java new file mode 100644 index 00000000..80ae7066 --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/serialization/queryformats/utils/UrlBuilderTest.java @@ -0,0 +1,101 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.serialization.queryformats.utils; + +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.aai.AAISetup; +import org.onap.aai.introspection.Version; +import org.onap.aai.serialization.db.DBSerializer; +import org.onap.aai.serialization.queryformats.exceptions.AAIFormatVertexException; +import org.onap.aai.util.AAIConstants; + +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.net.URISyntaxException; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.when; + +public class UrlBuilderTest extends AAISetup { + + @Mock + private DBSerializer serializer; + @Mock + private Vertex v; + + private static final String uri = "/test/uri"; + private static final Object vId = new Long(123); + private static final String protocolAndHost = "http://localhost/aai/"; + + @Before + public void before() throws UnsupportedEncodingException, URISyntaxException { + MockitoAnnotations.initMocks(this); + when(serializer.getURIForVertex(any(Vertex.class))).thenReturn(new URI(uri)); + when(v.id()).thenReturn(vId); + } + + @Test + public void v11Pathed() throws UnsupportedEncodingException, URISyntaxException, AAIFormatVertexException { + Version version = Version.v11; + UrlBuilder builder = new UrlBuilder(version, serializer, protocolAndHost); + String result = builder.pathed(v); + + assertEquals("has no protocol and host", AAIConstants.AAI_APP_ROOT + version + uri, result); + + } + + @Test + public void v11Id() throws UnsupportedEncodingException, URISyntaxException, AAIFormatVertexException { + Version version = Version.v11; + UrlBuilder builder = new UrlBuilder(version, serializer, protocolAndHost); + String result = builder.id(v); + + assertEquals("has no protocol and host", AAIConstants.AAI_APP_ROOT + version + "/resources/id/" + vId, result); + + } + + @Test + public void beforeV11Pathed() throws UnsupportedEncodingException, URISyntaxException, AAIFormatVertexException { + Version version = Version.v10; + UrlBuilder builder = new UrlBuilder(version, serializer, protocolAndHost); + String result = builder.pathed(v); + + assertEquals("has protocol and host", protocolAndHost + version + uri, result); + + } + + @Test + public void beforeV11Id() throws UnsupportedEncodingException, URISyntaxException, AAIFormatVertexException { + Version version = Version.v10; + UrlBuilder builder = new UrlBuilder(version, serializer, protocolAndHost); + String result = builder.id(v); + + assertEquals("has protocol and host", protocolAndHost + version + "/resources/id/" + vId, result); + + } + +} diff --git a/aai-core/src/test/java/org/onap/aai/serialization/tinkerpop/TreeBackedVertexTest.java b/aai-core/src/test/java/org/onap/aai/serialization/tinkerpop/TreeBackedVertexTest.java new file mode 100644 index 00000000..9c1e922b --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/serialization/tinkerpop/TreeBackedVertexTest.java @@ -0,0 +1,153 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.serialization.tinkerpop; + +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.*; +import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.onap.aai.serialization.db.EdgeProperty; +import org.onap.aai.serialization.engines.query.GraphTraversalQueryEngine; + +import static org.junit.Assert.assertEquals; + +@Ignore +public class TreeBackedVertexTest { + + private Graph graph = TinkerGraph.open(); + private Object startKey = null; + private Tree tree = null; + private Tree treeDepth1 = null; + private Tree treeDepth0NodeOnly = null; + + @Before + public void configure() { + GraphTraversalSource g = graph.traversal(); + + startKey = g.addV(T.label, "vserver").as("v1").property("test", "hello") + .addV(T.label, "vserver").as("v2") + .addV(T.label, "interface").property("name", "interface 1").as("v7").addInE("hasChild", "v2").property(EdgeProperty.CONTAINS.toString(), true) + .addV(T.label, "pserver").property("name", "pserver 1").as("v4").addOutE("runsOn", "v1").property(EdgeProperty.CONTAINS.toString(), false) + .addV(T.label, "interface").property("name", "interface 2").as("v3").addInE("hasChild", "v1").property(EdgeProperty.CONTAINS.toString(), true) + .addV(T.label, "address").property("name", "address 1").addInE("hasChild", "v3").property(EdgeProperty.CONTAINS.toString(), true) + .addV(T.label, "address").property("name", "address 2").addInE("hasChild", "v3").property(EdgeProperty.CONTAINS.toString(), true) + .addV(T.label, "complex").property("name", "complex 1").addInE("locatedIn", "v4").property(EdgeProperty.CONTAINS.toString(), false) + .addV(T.label, "interface").property("name", "interface 3").addInE("hasChild", "v4").property(EdgeProperty.CONTAINS.toString(), true) + .addV(T.label, "subnet").property("name", "subnet 1").as("v5").addInE("in", "v3").property(EdgeProperty.CONTAINS.toString(), false) + .addV(T.label, "address").property("name", "address 3").as("v6").addInE("hasChild", "v5").property(EdgeProperty.CONTAINS.toString(), true) + .select("v1").next(); + + tree = new GraphTraversalQueryEngine(g).findSubGraph((Vertex)startKey); + treeDepth1 = new GraphTraversalQueryEngine(g).findSubGraph((Vertex)startKey, 1, false); + treeDepth0NodeOnly = new GraphTraversalQueryEngine(g).findSubGraph((Vertex)startKey, 0, true); + } + + @Ignore + @Test + public void oneHopViaEdges() { + + //BulkSet set = (BulkSet)result; + TreeBackedVertex v = new TreeBackedVertex((Vertex)tree.getObjectsAtDepth(1).iterator().next(), tree); + + + assertEquals("locate child", v.edges(Direction.OUT).next().inVertex().property("name").orElse(""), "interface 2"); + assertEquals("locate cousin", v.edges(Direction.IN).next().outVertex().property("name").orElse(""), "pserver 1"); + + + } + + @Ignore + @Test + public void oneHopViaVertices() { + + //BulkSet set = (BulkSet)result; + TreeBackedVertex v = new TreeBackedVertex((Vertex)tree.getObjectsAtDepth(1).iterator().next(), tree); + + + assertEquals("locate child", "interface 2", v.vertices(Direction.OUT).next().property("name").orElse("")); + assertEquals("locate cousin", "pserver 1", v.vertices(Direction.IN).next().property("name").orElse("")); + + } + + @Ignore + @Test + public void twoHopCousinViaVertices() { + + //BulkSet set = (BulkSet)result; + TreeBackedVertex v = new TreeBackedVertex((Vertex)tree.getObjectsAtDepth(1).iterator().next(), tree); + + + assertEquals("locate child", "subnet 1", v.vertices(Direction.OUT).next().vertices(Direction.OUT, "in").next().property("name").orElse("")); + + } + + @Test + public void walkVerticesRestrictedDepth() { + + //BulkSet set = (BulkSet)result; + TreeBackedVertex v = new TreeBackedVertex((Vertex)treeDepth1.getObjectsAtDepth(1).iterator().next(), treeDepth1); + + + assertEquals("nothing returned", false, v.vertices(Direction.OUT).next() + .vertices(Direction.OUT, "hasChild").hasNext()); + + } + + @Test + public void walkVertices() { + TreeBackedVertex v = new TreeBackedVertex((Vertex)tree.getObjectsAtDepth(1).iterator().next(), tree); + assertEquals("locate child", "address 2", v.vertices(Direction.OUT).next() + .vertices(Direction.OUT, "hasChild").next().property("name").orElse("")); + } + + @Test + public void walkEdges() { + TreeBackedVertex v = new TreeBackedVertex((Vertex)tree.getObjectsAtDepth(1).iterator().next(), tree); + + assertEquals("locate child", "address 2", v.edges(Direction.OUT).next().inVertex() + .edges(Direction.OUT, "hasChild").next().inVertex().property("name").orElse("")); + } + + @Test + public void noEdgesFoudWithLabelVertices() { + TreeBackedVertex v = new TreeBackedVertex((Vertex)tree.getObjectsAtDepth(1).iterator().next(), tree); + + assertEquals("missing hello label", false , v.vertices(Direction.OUT, "hello").hasNext()); + } + + @Test + public void noEdgesFoudWithLabelEdges() { + TreeBackedVertex v = new TreeBackedVertex((Vertex)tree.getObjectsAtDepth(1).iterator().next(), tree); + + assertEquals("missing hello label", false , v.edges(Direction.OUT, "hello").hasNext()); + } + + @Test + public void depthZeroNodeOnly() { + TreeBackedVertex v = new TreeBackedVertex((Vertex)treeDepth0NodeOnly.getObjectsAtDepth(1).iterator().next(), treeDepth0NodeOnly); + assertEquals("no edges returned", false, v.edges(Direction.BOTH).hasNext()); + } + +} diff --git a/aai-core/src/test/java/org/onap/aai/util/GenerateXsdTest.java b/aai-core/src/test/java/org/onap/aai/util/GenerateXsdTest.java new file mode 100644 index 00000000..9a36680b --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/util/GenerateXsdTest.java @@ -0,0 +1,55 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.util; + +import org.junit.Test; +import org.onap.aai.introspection.Version; + +public class GenerateXsdTest { + + @Test + public void testGenerationOfXsdAndYaml() throws Exception { + + GenerateXsd generateXsd = new GenerateXsd(); + System.setProperty("gen_version", Version.getLatest().toString()); + System.setProperty("gen_type", "XSD"); + System.setProperty("yamlresponses_url", ""); + System.setProperty("yamlresponses_label", ""); + + generateXsd.main(new String[]{}); + + System.setProperty("gen_version", Version.getLatest().toString()); + System.setProperty("gen_type", "YAML"); + + String wikiLink = System.getProperty("aai.wiki.link"); + + if(wikiLink == null){ + wikiLink = "https://wiki.onap.org/"; + } + + System.setProperty("yamlresponses_url", wikiLink); + System.setProperty("yamlresponses_label", "Response codes found in [response codes]"); + + generateXsd.main(new String[]{}); + } + +} diff --git a/aai-core/src/test/java/org/onap/aai/workarounds/RemoveDME2QueryParamsTest.java b/aai-core/src/test/java/org/onap/aai/workarounds/RemoveDME2QueryParamsTest.java new file mode 100644 index 00000000..a5c7055d --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/workarounds/RemoveDME2QueryParamsTest.java @@ -0,0 +1,92 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.workarounds; + +import org.junit.Before; +import org.junit.Test; + +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; + +import static org.junit.Assert.assertEquals; + +public class RemoveDME2QueryParamsTest { + + private MultivaluedMap hasParams; + private MultivaluedMap doesNotHaveParams; + private RemoveDME2QueryParams removeParams = new RemoveDME2QueryParams(); + + /** + * Setup. + */ + @Before + public void setup() { + hasParams = new MultivaluedHashMap<>(); + doesNotHaveParams = new MultivaluedHashMap<>(); + + hasParams.add("version", "1"); + hasParams.add("envContext", "DEV"); + hasParams.add("routeOffer", "INT1"); + hasParams.add("test1", "peppermints"); + hasParams.add("test2", "amber"); + + doesNotHaveParams.add("version", "1"); + doesNotHaveParams.add("envContext", "DEV"); + doesNotHaveParams.add("test1", "peppermints"); + doesNotHaveParams.add("test2", "amber"); + + } + + /** + * Test removal. + */ + @Test + public void testRemoval() { + + if (removeParams.shouldRemoveQueryParams(hasParams)) { + removeParams.removeQueryParams(hasParams); + } + + assertEquals("no version", false, hasParams.containsKey("version")); + assertEquals("no envContext", false, hasParams.containsKey("envContext")); + assertEquals("no routeOffer", false, hasParams.containsKey("routeOffer")); + assertEquals("has test1", true, hasParams.containsKey("test1")); + assertEquals("has test2", true, hasParams.containsKey("test2")); + + } + + /** + * Should not remove. + */ + @Test + public void shouldNotRemove() { + + if (removeParams.shouldRemoveQueryParams(doesNotHaveParams)) { + removeParams.removeQueryParams(doesNotHaveParams); + } + + assertEquals("no version", true, doesNotHaveParams.containsKey("version")); + assertEquals("no envContext", true, doesNotHaveParams.containsKey("envContext")); + assertEquals("has test1", true, doesNotHaveParams.containsKey("test1")); + assertEquals("has test2", true, doesNotHaveParams.containsKey("test2")); + } +} diff --git a/aai-core/src/test/java/org/openecomp/aai/AAISetup.java b/aai-core/src/test/java/org/openecomp/aai/AAISetup.java deleted file mode 100644 index b0fce58d..00000000 --- a/aai-core/src/test/java/org/openecomp/aai/AAISetup.java +++ /dev/null @@ -1,34 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -package org.openecomp.aai; - -import org.junit.BeforeClass; -import org.openecomp.aai.serialization.queryformats.QueryFormatTestHelper; -import org.openecomp.aai.util.AAIConstants; - -public abstract class AAISetup { - - @BeforeClass - public static void setupBundleconfig() throws Exception { - System.setProperty("AJSC_HOME", "."); - System.setProperty("BUNDLECONFIG_DIR", "src/test/resources/bundleconfig-local"); - QueryFormatTestHelper.setFinalStatic(AAIConstants.class.getField("AAI_HOME_ETC_OXM"), "src/test/resources/bundleconfig-local/etc/oxm/"); - } -} diff --git a/aai-core/src/test/java/org/openecomp/aai/exceptions/AAIExceptionTest.java b/aai-core/src/test/java/org/openecomp/aai/exceptions/AAIExceptionTest.java deleted file mode 100644 index 554b6418..00000000 --- a/aai-core/src/test/java/org/openecomp/aai/exceptions/AAIExceptionTest.java +++ /dev/null @@ -1,113 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.exceptions; - -import org.junit.Test; -import org.openecomp.aai.AAISetup; - -import static org.junit.Assert.assertEquals; - -public class AAIExceptionTest extends AAISetup { - - private static final String code = "4004"; - private static final String details = "This is a detailed description of the exception."; - private static final Throwable cause = new RuntimeException("This is a runtime exception."); - private static final Throwable noMessage = new RuntimeException(); - - /** - * Test constructor with 0 params. - * - * @throws Exception the exception - */ - @Test - public void testConstructorWith0Params() throws Exception { - AAIException exception = new AAIException(); - assertEquals(exception, exception); - } - - /** - * Test constructor with 1 params. - * - * @throws Exception the exception - */ - @Test - public void testConstructorWith1Params() throws Exception { - AAIException exception = new AAIException(code); - assertEquals(exception, exception); - } - - /** - * Test constructor with 2 params details. - * - * @throws Exception the exception - */ - @Test - public void testConstructorWith2ParamsDetails() throws Exception { - AAIException exception = new AAIException(code, details); - assertEquals(details, exception.getMessage()); - } - - /** - * Test constructor with 2 params cause. - * - * @throws Exception the exception - */ - @Test - public void testConstructorWith2ParamsCause() throws Exception { - AAIException exception = new AAIException(code, cause); - assertEquals("java.lang.RuntimeException: This is a runtime exception.", exception.getMessage()); - } - - /** - * Test constructor with 2 params null message. - * - * @throws Exception the exception - */ - @Test - public void testConstructorWith2ParamsNullMessage() throws Exception { - AAIException exception = new AAIException(code, noMessage); - assertEquals(noMessage.toString(), exception.getMessage()); - } - - /** - * Test constructor with 3 params. - * - * @throws Exception the exception - */ - @Test - public void testConstructorWith3Params() throws Exception { - AAIException exception = new AAIException(code, cause, details); - String details = "This is a detailed description of the exception."; - assertEquals(details, exception.getMessage()); - } - - /** - * Test constructor with 3 params null message. - * - * @throws Exception the exception - */ - @Test - public void testConstructorWith3ParamsNullMessage() throws Exception { - AAIException exception = new AAIException(code, noMessage, details); - String detailString = new String(details); - assertEquals(detailString, exception.getMessage()); - } -} diff --git a/aai-core/src/test/java/org/openecomp/aai/exceptions/AAIExceptionWithInfoTest.java b/aai-core/src/test/java/org/openecomp/aai/exceptions/AAIExceptionWithInfoTest.java deleted file mode 100644 index 41841ac7..00000000 --- a/aai-core/src/test/java/org/openecomp/aai/exceptions/AAIExceptionWithInfoTest.java +++ /dev/null @@ -1,147 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.exceptions; - -import org.junit.Test; -import org.openecomp.aai.AAISetup; - -import java.util.HashMap; - -import static org.junit.Assert.assertEquals; - -public class AAIExceptionWithInfoTest extends AAISetup { - - - private static final HashMap map = new HashMap(); - - { - map.put("itemInteger", 1); - map.put("itemString", "Two"); - map.put("itemThree", Boolean.TRUE); - } - - private static final String info = "An error has occurred."; - private static final String code = "AAI_4004"; - private static final String details = "This is a detailed description of the exception."; - private static final Throwable cause = new RuntimeException("This is a runtime exception."); - - /** - * Test constructor with 2 params. - * - * @throws Exception the exception - */ - @Test - public void testConstructorWith2Params() throws Exception { - AAIExceptionWithInfo exception = new AAIExceptionWithInfo(map, info); - - assertEquals(map, exception.getInfoHash()); - assertEquals(info, exception.getInfo()); - } - - /** - * Test constructor with 3 params. - * - * @throws Exception the exception - */ - @Test - public void testConstructorWith3Params() throws Exception { - AAIExceptionWithInfo exception = new AAIExceptionWithInfo(code, map, info); - - assertEquals("4004", exception.getErrorObject().getErrorCode()); - assertEquals(map, exception.getInfoHash()); - assertEquals(info, exception.getInfo()); - } - - /** - * Test constructor with 4 params I. - * - * @throws Exception the exception - */ - @Test - public void testConstructorWith4ParamsI() throws Exception { - AAIExceptionWithInfo exception = new AAIExceptionWithInfo(code, details, map, info); - - assertEquals("4004", exception.getErrorObject().getErrorCode()); - assertEquals(details, exception.getMessage()); - assertEquals(map, exception.getInfoHash()); - assertEquals(info, exception.getInfo()); - } - - /** - * Test constructor with 4 params II. - * - * @throws Exception the exception - */ - @Test - public void testConstructorWith4ParamsII() throws Exception { - AAIExceptionWithInfo exception = new AAIExceptionWithInfo(code, cause, map, info); - - assertEquals("4004", exception.getErrorObject().getErrorCode()); - assertEquals(cause.toString(), exception.getMessage()); - assertEquals(map, exception.getInfoHash()); - assertEquals(info, exception.getInfo()); - } - - /** - * Test constructor with 5 params. - * - * @throws Exception the exception - */ - @Test - public void testConstructorWith5Params() throws Exception { - AAIExceptionWithInfo exception = new AAIExceptionWithInfo(code, cause, details, map, info); - - assertEquals("4004", exception.getErrorObject().getErrorCode()); - assertEquals(details, exception.getMessage()); - assertEquals(map, exception.getInfoHash()); - assertEquals(info, exception.getInfo()); - } - - /** - * Test set info hash. - */ - @Test - public void testSetInfoHash() { - AAIExceptionWithInfo exception = new AAIExceptionWithInfo(map, info); - - HashMap newMap = new HashMap(); - newMap.put("itemInteger", 2); - exception.setInfoHash(newMap); - - assertEquals(newMap, exception.getInfoHash()); - assertEquals(info, exception.getInfo()); - } - - /** - * Test set info. - */ - @Test - public void testSetInfo() { - AAIExceptionWithInfo exception = new AAIExceptionWithInfo(map, info); - - String newInfo = "This is updated info."; - exception.setInfo(newInfo); - - assertEquals(map, exception.getInfoHash()); - assertEquals(newInfo, exception.getInfo()); - } - -} diff --git a/aai-core/src/test/java/org/openecomp/aai/introspection/IntrospectorTestSpec.java b/aai-core/src/test/java/org/openecomp/aai/introspection/IntrospectorTestSpec.java deleted file mode 100644 index 1ecc6923..00000000 --- a/aai-core/src/test/java/org/openecomp/aai/introspection/IntrospectorTestSpec.java +++ /dev/null @@ -1,58 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.introspection; - -import org.openecomp.aai.AAISetup; -import org.openecomp.aai.introspection.exceptions.AAIUnknownObjectException; - -import static org.junit.Assert.assertEquals; - -public class IntrospectorTestSpec extends AAISetup { - - - - /** - * Container test set. - * - * @param wrappedPortGroups the wrapped port groups - * @throws AAIUnknownObjectException - */ - protected void containerTestSet(Introspector wrappedPortGroups) throws AAIUnknownObjectException { - - assertEquals( - "isContainer", - true, - wrappedPortGroups.isContainer()); - - assertEquals( - "newInstanceOfNestedProperty", - "PortGroup", - wrappedPortGroups.newInstanceOfNestedProperty("port-group").getClass().getSimpleName()); - - assertEquals( - "isComplexGenericType", - true, - wrappedPortGroups.isComplexGenericType("port-group")); - - - } - -} diff --git a/aai-core/src/test/java/org/openecomp/aai/introspection/MoxyEngineTest.java b/aai-core/src/test/java/org/openecomp/aai/introspection/MoxyEngineTest.java deleted file mode 100644 index 0f67ddfc..00000000 --- a/aai-core/src/test/java/org/openecomp/aai/introspection/MoxyEngineTest.java +++ /dev/null @@ -1,45 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.introspection; - -import org.junit.Test; -import org.openecomp.aai.introspection.exceptions.AAIUnknownObjectException; - -public class MoxyEngineTest extends IntrospectorTestSpec { - - /** - * Container object. - * @throws AAIUnknownObjectException - */ - @Test - public void containerObject() throws AAIUnknownObjectException { - - Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v9); - - Introspector obj = loader.introspectorFromName("port-groups"); - - this.containerTestSet(obj); - - } - - - -} diff --git a/aai-core/src/test/java/org/openecomp/aai/introspection/PojoInjestorTest.java b/aai-core/src/test/java/org/openecomp/aai/introspection/PojoInjestorTest.java deleted file mode 100644 index b820cfef..00000000 --- a/aai-core/src/test/java/org/openecomp/aai/introspection/PojoInjestorTest.java +++ /dev/null @@ -1,59 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.introspection; - -import org.junit.Test; -import org.openecomp.aai.db.props.AAIProperties; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Marshaller; - -import static org.junit.Assert.*; - -public class PojoInjestorTest { - - @Test - public void getVersionTest() { - String latestVersion = "org.openecomp.aai.yang.VnfImage"; - PojoInjestor testPI = new PojoInjestor(); - assertEquals("", AAIProperties.LATEST, testPI.getVersion(latestVersion)); - - String oldVersion = "org.openecomp.aai.yang.v8.VnfImage"; - assertEquals("", Version.v8, testPI.getVersion(oldVersion)); - } - - @Test - public void getContextForVersionTest() { - PojoInjestor testPI = new PojoInjestor(); - JAXBContext context = testPI.getContextForVersion(Version.v9); - try { - Marshaller marshaller = context.createMarshaller(); - //this will fail if the context wasn't initialized successfully (I think) - marshaller.setProperty(org.eclipse.persistence.jaxb.MarshallerProperties.MEDIA_TYPE, "application/json"); - } catch (JAXBException e) { - e.printStackTrace(); - fail("failed on setting marshaller property"); - } - //if we get to here that means everything went ok - assertTrue(true); - } -} diff --git a/aai-core/src/test/java/org/openecomp/aai/introspection/PojoLoaderTest.java b/aai-core/src/test/java/org/openecomp/aai/introspection/PojoLoaderTest.java deleted file mode 100644 index e4e58b60..00000000 --- a/aai-core/src/test/java/org/openecomp/aai/introspection/PojoLoaderTest.java +++ /dev/null @@ -1,52 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.introspection; - -import org.junit.Test; -import org.openecomp.aai.AAISetup; -import org.openecomp.aai.domain.yang.v9.VnfImage; -import org.openecomp.aai.introspection.exceptions.AAIUnmarshallingException; -import org.openecomp.aai.restcore.MediaType; - -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -public class PojoLoaderTest extends AAISetup { - - - @Test - public void test() { - Loader pojoLoader = LoaderFactory.createLoaderForVersion(ModelType.POJO, Version.v9); - String payload = "{\"vnf-image-uuid\":\"myuuid\",\"application\":\"testApp\",\"application-vendor\":\"testVendor\",\"application-version\":\"versionTest\"}"; - try { - Introspector intro = pojoLoader.unmarshal("vnf-image", payload, MediaType.APPLICATION_JSON_TYPE); - VnfImage myVnfImage = (VnfImage) intro.getUnderlyingObject(); - assertTrue("myuuid".equals(myVnfImage.getVnfImageUuid())); - assertTrue("testApp".equals(myVnfImage.getApplication())); - assertTrue("testVendor".equals(myVnfImage.getApplicationVendor())); - assertTrue("versionTest".equals(myVnfImage.getApplicationVersion())); - } catch (AAIUnmarshallingException e) { - e.printStackTrace(); - fail("AAIUnmarshallingException thrown"); - } - } - -} diff --git a/aai-core/src/test/java/org/openecomp/aai/introspection/PojoStrategyTest.java b/aai-core/src/test/java/org/openecomp/aai/introspection/PojoStrategyTest.java deleted file mode 100644 index 0bd61178..00000000 --- a/aai-core/src/test/java/org/openecomp/aai/introspection/PojoStrategyTest.java +++ /dev/null @@ -1,43 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.introspection; - -import org.junit.Test; -import org.openecomp.aai.domain.yang.CloudRegion; -import org.openecomp.aai.domain.yang.VolumeGroup; -import org.openecomp.aai.schema.enums.ObjectMetadata; - -import static org.junit.Assert.assertEquals; - -public class PojoStrategyTest { - - @Test - public void getMetadataTest() { - Introspector cloudregion = IntrospectorFactory.newInstance(ModelType.POJO, new CloudRegion()); - assertEquals("cloud-infrastructure", cloudregion.getMetadata(ObjectMetadata.NAMESPACE)); - assertEquals("cloud-regions", cloudregion.getMetadata(ObjectMetadata.CONTAINER)); - - Introspector volumegroup = IntrospectorFactory.newInstance(ModelType.POJO, new VolumeGroup()); - assertEquals("cloud-region", volumegroup.getMetadata(ObjectMetadata.DEPENDENT_ON)); - assertEquals("", volumegroup.getMetadata(ObjectMetadata.NAMESPACE)); - } - -} diff --git a/aai-core/src/test/java/org/openecomp/aai/introspection/PropertyPredicatesTest.java b/aai-core/src/test/java/org/openecomp/aai/introspection/PropertyPredicatesTest.java deleted file mode 100644 index 50aea8fe..00000000 --- a/aai-core/src/test/java/org/openecomp/aai/introspection/PropertyPredicatesTest.java +++ /dev/null @@ -1,74 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.introspection; - -import org.junit.Before; -import org.junit.Test; -import org.openecomp.aai.AAISetup; -import org.openecomp.aai.introspection.exceptions.AAIUnknownObjectException; - -import java.util.Set; - -import static org.hamcrest.Matchers.hasItems; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertThat; - -public class PropertyPredicatesTest extends AAISetup { - - private final Version version = Version.getLatest(); - - private Loader loader; - private ModelType introspectorFactoryType = ModelType.MOXY; - private Introspector obj; - - @Before - public void setup() throws Exception { - loader = LoaderFactory.createLoaderForVersion(introspectorFactoryType, version); - obj = loader.introspectorFromName("test-object"); - } - - @Test - public void includeInTestGeneration() throws AAIUnknownObjectException { - - Set props = obj.getProperties(PropertyPredicates.includeInTestGeneration()); - - assertThat("props not found", props, - not(hasItems("persona-model-ver", "not-visible-test-element", "model-invariant-id", "model-version-id"))); - } - - @Test - public void isVisible() throws AAIUnknownObjectException { - - Set props = obj.getProperties(PropertyPredicates.isVisible()); - - assertThat("props not found", props, not(hasItems("persona-model-ver"))); - } - - @Test - public void all() throws AAIUnknownObjectException { - - Set props = obj.getProperties(); - - assertThat("all found", props, hasItems("persona-model-ver", "not-visible-test-element")); - } - - -} diff --git a/aai-core/src/test/java/org/openecomp/aai/introspection/ReflectionEngineTest.java b/aai-core/src/test/java/org/openecomp/aai/introspection/ReflectionEngineTest.java deleted file mode 100644 index d7cd7b18..00000000 --- a/aai-core/src/test/java/org/openecomp/aai/introspection/ReflectionEngineTest.java +++ /dev/null @@ -1,46 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.introspection; - -import org.junit.Test; -import org.openecomp.aai.introspection.exceptions.AAIUnknownObjectException; - -public class ReflectionEngineTest extends IntrospectorTestSpec { - - /** - * Container object. - * - * @throws InstantiationException the instantiation exception - * @throws IllegalAccessException the illegal access exception - * @throws ClassNotFoundException the class not found exception - * @throws AAIUnknownObjectException - */ - @Test - public void containerObject() throws InstantiationException, IllegalAccessException, ClassNotFoundException, AAIUnknownObjectException { - Object javaObj = null; - String className = "org.openecomp.aai.domain.yang.PortGroups"; - javaObj = Class.forName(className).newInstance(); - - Introspector obj = IntrospectorFactory.newInstance(ModelType.POJO, javaObj); - -// this.containerTestSet(obj); - } -} diff --git a/aai-core/src/test/java/org/openecomp/aai/introspection/sideeffect/DataCopyTest.java b/aai-core/src/test/java/org/openecomp/aai/introspection/sideeffect/DataCopyTest.java deleted file mode 100644 index 8e37fe05..00000000 --- a/aai-core/src/test/java/org/openecomp/aai/introspection/sideeffect/DataCopyTest.java +++ /dev/null @@ -1,267 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.introspection.sideeffect; - -import com.thinkaurelius.titan.core.TitanFactory; -import com.thinkaurelius.titan.core.TitanGraph; -import org.apache.commons.io.IOUtils; -import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; -import org.apache.tinkerpop.gremlin.structure.Graph; -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.apache.tinkerpop.gremlin.structure.VertexProperty; -import org.junit.*; -import org.junit.rules.ExpectedException; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.openecomp.aai.db.props.AAIProperties; -import org.openecomp.aai.dbmap.DBConnectionType; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.*; -import org.openecomp.aai.introspection.sideeffect.exceptions.AAIMissingRequiredPropertyException; -import org.openecomp.aai.parsers.query.QueryParser; -import org.openecomp.aai.serialization.db.DBSerializer; -import org.openecomp.aai.serialization.db.EdgeProperty; -import org.openecomp.aai.serialization.engines.QueryStyle; -import org.openecomp.aai.serialization.engines.TitanDBEngine; -import org.openecomp.aai.serialization.engines.TransactionalGraphEngine; - -import java.io.FileInputStream; -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.lang.reflect.InvocationTargetException; -import java.net.MalformedURLException; -import java.net.URISyntaxException; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.when; - -public class DataCopyTest { - - private static TitanGraph graph; - private final static Version version = Version.getLatest(); - private final static ModelType introspectorFactoryType = ModelType.MOXY; - private final static QueryStyle queryStyle = QueryStyle.TRAVERSAL; - private final static DBConnectionType type = DBConnectionType.REALTIME; - private static Loader loader; - private static TransactionalGraphEngine dbEngine; - @Mock private Vertex self; - @Mock private VertexProperty prop; - @Mock private QueryParser uriQuery; - @Rule - public ExpectedException thrown = ExpectedException.none(); - - - @BeforeClass - public static void setup() throws NoSuchFieldException, SecurityException, Exception { - graph = TitanFactory.build().set("storage.backend","inmemory").open(); - System.setProperty("AJSC_HOME", "."); - System.setProperty("BUNDLECONFIG_DIR", "src/test/resources/bundleconfig-local"); - loader = LoaderFactory.createLoaderForVersion(introspectorFactoryType, version); - dbEngine = new TitanDBEngine( - queryStyle, - type, - loader); - - graph.traversal().addV("aai-node-type", "model", "model-invariant-id", "key1").as("v1") - .addV("aai-node-type", "model-ver", "model-ver", "myValue", "model-version-id", "key2", "model-version", "testValue").addInE("has", "v1", EdgeProperty.CONTAINS.toString(), true) - .addV("aai-node-type", "model", "model-invariant-id", "key3").as("v2") - .addV("aai-node-type", "model-ver", "model-ver", "myValue", "model-version-id", "key4").addInE("has", "v2", EdgeProperty.CONTAINS.toString(), true) - .next(); - graph.tx().commit(); - } - - @AfterClass - public static void tearDown() { - graph.tx().rollback(); - graph.close(); - } - - @Before - public void initMock() { - MockitoAnnotations.initMocks(this); - } - - @Test - public void runPopulatePersonaModelVer() throws URISyntaxException, AAIException, UnsupportedEncodingException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException, InstantiationException, NoSuchMethodException, MalformedURLException { - - final Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.getLatest()); - final Introspector obj = loader.introspectorFromName("test-object"); - obj.setValue("vnf-id", "myId"); - obj.setValue("model-invariant-id", "key1"); - obj.setValue("model-version-id", "key2"); - TransactionalGraphEngine spy = spy(dbEngine); - TransactionalGraphEngine.Admin adminSpy = spy(dbEngine.asAdmin()); - Graph g = graph.newTransaction(); - GraphTraversalSource traversal = g.traversal(); - when(spy.asAdmin()).thenReturn(adminSpy); - when(adminSpy.getTraversalSource()).thenReturn(traversal); - when(self.property(AAIProperties.AAI_URI)).thenReturn(prop); - when(prop.orElse(null)).thenReturn(obj.getURI()); - DBSerializer serializer = new DBSerializer(version, spy, introspectorFactoryType, "AAI_TEST"); - SideEffectRunner runner = new SideEffectRunner - .Builder(spy, serializer).addSideEffect(DataCopy.class).build(); - - runner.execute(obj, self); - - assertEquals("value populated", "testValue", obj.getValue("persona-model-ver")); - - g.tx().rollback(); - - - } - - @Test - public void runPopulateModelVersionId() throws URISyntaxException, AAIException, UnsupportedEncodingException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException, InstantiationException, NoSuchMethodException, MalformedURLException { - - final Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v9); - final Introspector obj = loader.introspectorFromName("test-object"); - obj.setValue("vnf-id", "myId"); - obj.setValue("persona-model-id", "key1"); - obj.setValue("persona-model-version", "testValue"); - TransactionalGraphEngine spy = spy(dbEngine); - TransactionalGraphEngine.Admin adminSpy = spy(dbEngine.asAdmin()); - Graph g = graph.newTransaction(); - GraphTraversalSource traversal = g.traversal(); - when(spy.asAdmin()).thenReturn(adminSpy); - when(adminSpy.getTraversalSource()).thenReturn(traversal); - when(self.property(AAIProperties.AAI_URI)).thenReturn(prop); - when(prop.orElse(null)).thenReturn(obj.getURI()); - DBSerializer serializer = new DBSerializer(version, spy, introspectorFactoryType, "AAI_TEST"); - SideEffectRunner runner = new SideEffectRunner - .Builder(spy, serializer).addSideEffect(DataCopy.class).build(); - - runner.execute(obj, self); - - assertEquals("value populated", "key2", obj.getValue("model-version-id")); - - g.tx().rollback(); - } - - @Test - public void verifyNestedSideEffect() throws URISyntaxException, AAIException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException, InstantiationException, NoSuchMethodException, IOException { - - final Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.getLatest()); - final Introspector obj = loader.unmarshal("customer", this.getJsonString("nested-case.json")); - System.out.println(obj.marshal(true)); - TransactionalGraphEngine spy = spy(dbEngine); - TransactionalGraphEngine.Admin adminSpy = spy(dbEngine.asAdmin()); - Graph g = graph.newTransaction(); - GraphTraversalSource traversal = g.traversal(); - when(spy.tx()).thenReturn(g); - when(spy.asAdmin()).thenReturn(adminSpy); - when(adminSpy.getTraversalSource()).thenReturn(traversal); - when(self.property(AAIProperties.AAI_URI)).thenReturn(prop); - when(prop.orElse(null)).thenReturn(obj.getURI()); - when(uriQuery.isDependent()).thenReturn(false); - DBSerializer serializer = new DBSerializer(version, spy, introspectorFactoryType, "AAI_TEST"); - Vertex v= serializer.createNewVertex(obj); - serializer.serializeToDb(obj, v, uriQuery, obj.getURI(), "test"); - - assertEquals("nested value populated", "testValue", g.traversal().V().has("service-instance-id", "nested-instance-key").next().property("persona-model-version").orElse("")); - - g.tx().rollback(); - - } - - @Test - public void expectedMissingPropertyExceptionInURI() throws AAIException, UnsupportedEncodingException { - - final Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.getLatest()); - final Introspector obj = loader.introspectorFromName("test-object"); - obj.setValue("vnf-id", "myId"); - obj.setValue("model-invariant-id", "key1"); - - TransactionalGraphEngine spy = spy(dbEngine); - TransactionalGraphEngine.Admin adminSpy = spy(dbEngine.asAdmin()); - Graph g = graph.newTransaction(); - GraphTraversalSource traversal = g.traversal(); - when(spy.asAdmin()).thenReturn(adminSpy); - when(adminSpy.getTraversalSource()).thenReturn(traversal); - when(self.property(AAIProperties.AAI_URI)).thenReturn(prop); - when(prop.orElse(null)).thenReturn(obj.getURI()); - DBSerializer serializer = new DBSerializer(version, spy, introspectorFactoryType, "AAI_TEST"); - SideEffectRunner runner = new SideEffectRunner - .Builder(spy, serializer).addSideEffect(DataCopy.class).build(); - - thrown.expect(AAIMissingRequiredPropertyException.class); - runner.execute(obj, self); - } - - @Test - public void expectedMissingPropertyExceptionForResultingObject() throws AAIException, UnsupportedEncodingException { - final Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.getLatest()); - final Introspector obj = loader.introspectorFromName("test-object"); - obj.setValue("vnf-id", "myId"); - obj.setValue("model-invariant-id", "key3"); - obj.setValue("model-version-id", "key4"); - - TransactionalGraphEngine spy = spy(dbEngine); - TransactionalGraphEngine.Admin adminSpy = spy(dbEngine.asAdmin()); - Graph g = graph.newTransaction(); - GraphTraversalSource traversal = g.traversal(); - when(spy.asAdmin()).thenReturn(adminSpy); - when(adminSpy.getTraversalSource()).thenReturn(traversal); - when(self.property(AAIProperties.AAI_URI)).thenReturn(prop); - when(prop.orElse(null)).thenReturn(obj.getURI()); - DBSerializer serializer = new DBSerializer(version, spy, introspectorFactoryType, "AAI_TEST"); - SideEffectRunner runner = new SideEffectRunner - .Builder(spy, serializer).addSideEffect(DataCopy.class).build(); - - thrown.expect(AAIMissingRequiredPropertyException.class); - runner.execute(obj, self); - } - - @Test - public void expectNoProcessingWithNoProperties() throws AAIException, UnsupportedEncodingException { - final Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.getLatest()); - final Introspector obj = loader.introspectorFromName("test-object"); - obj.setValue("vnf-id", "myId"); - - TransactionalGraphEngine spy = spy(dbEngine); - TransactionalGraphEngine.Admin adminSpy = spy(dbEngine.asAdmin()); - Graph g = graph.newTransaction(); - GraphTraversalSource traversal = g.traversal(); - when(spy.asAdmin()).thenReturn(adminSpy); - when(adminSpy.getTraversalSource()).thenReturn(traversal); - when(self.property(AAIProperties.AAI_URI)).thenReturn(prop); - when(prop.orElse(null)).thenReturn(obj.getURI()); - DBSerializer serializer = new DBSerializer(version, spy, introspectorFactoryType, "AAI_TEST"); - SideEffectRunner runner = new SideEffectRunner - .Builder(spy, serializer).addSideEffect(DataCopy.class).build(); - - runner.execute(obj, self); - - assertEquals("no model-version-id", true, obj.getValue("model-version-id") == null); - assertEquals("no model-invariant-id", true, obj.getValue("model-invariant-id") == null); - - } - - private String getJsonString(String filename) throws IOException { - - - FileInputStream is = new FileInputStream("src/test/resources/bundleconfig-local/etc/oxm/sideeffect/" + filename); - String s = IOUtils.toString(is, "UTF-8"); - IOUtils.closeQuietly(is); - - return s; - } -} diff --git a/aai-core/src/test/java/org/openecomp/aai/introspection/sideeffect/DataLinkTest.java b/aai-core/src/test/java/org/openecomp/aai/introspection/sideeffect/DataLinkTest.java deleted file mode 100644 index 8220b86c..00000000 --- a/aai-core/src/test/java/org/openecomp/aai/introspection/sideeffect/DataLinkTest.java +++ /dev/null @@ -1,258 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.introspection.sideeffect; - -import com.thinkaurelius.titan.core.TitanFactory; -import com.thinkaurelius.titan.core.TitanGraph; -import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; -import org.apache.tinkerpop.gremlin.structure.Graph; -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.apache.tinkerpop.gremlin.structure.VertexProperty; -import org.junit.*; -import org.junit.rules.ExpectedException; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.openecomp.aai.db.props.AAIProperties; -import org.openecomp.aai.dbmap.DBConnectionType; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.*; -import org.openecomp.aai.parsers.query.QueryParser; -import org.openecomp.aai.serialization.db.DBSerializer; -import org.openecomp.aai.serialization.db.EdgeProperty; -import org.openecomp.aai.serialization.engines.QueryStyle; -import org.openecomp.aai.serialization.engines.TitanDBEngine; -import org.openecomp.aai.serialization.engines.TransactionalGraphEngine; - -import java.io.UnsupportedEncodingException; -import java.lang.reflect.InvocationTargetException; -import java.net.MalformedURLException; -import java.net.URISyntaxException; -import java.util.List; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.when; - -public class DataLinkTest { - - private static TitanGraph graph; - private final static Version version = Version.getLatest(); - private final static ModelType introspectorFactoryType = ModelType.MOXY; - private final static QueryStyle queryStyle = QueryStyle.TRAVERSAL; - private final static DBConnectionType type = DBConnectionType.REALTIME; - private static Loader loader; - private static TransactionalGraphEngine dbEngine; - @Mock private QueryParser parser; - @Mock private Vertex self; - @Mock private VertexProperty prop; - @Rule - public ExpectedException thrown = ExpectedException.none(); - - - @BeforeClass - public static void setup() throws NoSuchFieldException, SecurityException, Exception { - graph = TitanFactory.build().set("storage.backend","inmemory").open(); - System.setProperty("AJSC_HOME", "."); - System.setProperty("BUNDLECONFIG_DIR", "src/test/resources/bundleconfig-local"); - loader = LoaderFactory.createLoaderForVersion(introspectorFactoryType, version); - dbEngine = new TitanDBEngine( - queryStyle, - type, - loader); - - graph.traversal().addV("aai-node-type", "vpn-binding", "vpn-id", "addKey").as("v1") - .addV("aai-node-type", "vpn-binding", "vpn-id", "modifyKey").as("v2") - .addV("aai-node-type", "route-target", "global-route-target", "modifyTargetKey", "route-target-role", "modifyRoleKey", "linked", true).addInE("has", "v2", EdgeProperty.CONTAINS.toString(), true) - .addV("aai-node-type", "vpn-binding", "vpn-id", "deleteKey").as("v3") - .addV("aai-node-type", "route-target", "global-route-target", "deleteTargetKey", "route-target-role", "deleteRoleKey", "linked", true).addInE("has", "v3", EdgeProperty.CONTAINS.toString(), true) - .addV("aai-node-type", "vpn-binding", "vpn-id", "getKey").as("v4") - .addV("aai-node-type", "route-target", "global-route-target", "getTargetKey", "route-target-role", "getRoleKey", "linked", true).addInE("has", "v4", EdgeProperty.CONTAINS.toString(), true) - .addV("aai-node-type", "vpn-binding", "vpn-id", "getKeyNoLink").as("v5") - .addV("aai-node-type", "route-target", "global-route-target", "getTargetKeyNoLink", "route-target-role", "getRoleKeyNoLink").addInE("has", "v5", EdgeProperty.CONTAINS.toString(), true) - .next(); - graph.tx().commit(); - } - - @AfterClass - public static void tearDown() { - graph.tx().rollback(); - graph.close(); - } - - @Before - public void initMock() { - MockitoAnnotations.initMocks(this); - } - - @Test - public void verifyCreationOfVertex() throws URISyntaxException, AAIException, UnsupportedEncodingException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException, InstantiationException, NoSuchMethodException, MalformedURLException { - - final Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v9); - final Introspector obj = loader.introspectorFromName("vpn-binding"); - obj.setValue("vpn-id", "addKey"); - obj.setValue("global-route-target", "key1"); - obj.setValue("route-target-role", "key2"); - TransactionalGraphEngine spy = spy(dbEngine); - TransactionalGraphEngine.Admin adminSpy = spy(dbEngine.asAdmin()); - Graph g = graph.newTransaction(); - GraphTraversalSource traversal = g.traversal(); - when(spy.asAdmin()).thenReturn(adminSpy); - when(adminSpy.getTraversalSource()).thenReturn(traversal); - when(spy.tx()).thenReturn(g); - when(self.property(AAIProperties.AAI_URI)).thenReturn(prop); - when(prop.orElse(null)).thenReturn(obj.getURI()); - DBSerializer serializer = new DBSerializer(version, spy, introspectorFactoryType, "AAI_TEST"); - SideEffectRunner runner = new SideEffectRunner - .Builder(spy, serializer).addSideEffect(DataLinkWriter.class).build(); - - runner.execute(obj, self); - - assertEquals("route-target vertex found", true, traversal.V() - .has(AAIProperties.NODE_TYPE, "route-target").has("global-route-target", "key1").has("route-target-role", "key2").has("linked", true).hasNext()); - - g.tx().rollback(); - - } - - @Test - public void verifyModificationOfVertex() throws URISyntaxException, AAIException, UnsupportedEncodingException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException, InstantiationException, NoSuchMethodException, MalformedURLException { - - final Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v9); - final Introspector obj = loader.introspectorFromName("vpn-binding"); - obj.setValue("vpn-id", "modifyKey"); - obj.setValue("global-route-target", "modifyTargetKey2"); - obj.setValue("route-target-role", "modifyRoleKey2"); - TransactionalGraphEngine spy = spy(dbEngine); - TransactionalGraphEngine.Admin adminSpy = spy(dbEngine.asAdmin()); - Graph g = graph.newTransaction(); - GraphTraversalSource traversal = g.traversal(); - when(spy.asAdmin()).thenReturn(adminSpy); - when(adminSpy.getTraversalSource()).thenReturn(traversal); - when(spy.tx()).thenReturn(g); - when(self.property(AAIProperties.AAI_URI)).thenReturn(prop); - when(prop.orElse(null)).thenReturn(obj.getURI()); - DBSerializer serializer = new DBSerializer(version, spy, introspectorFactoryType, "AAI_TEST"); - SideEffectRunner runner = new SideEffectRunner - .Builder(spy, serializer).addSideEffect(DataLinkWriter.class).build(); - - runner.execute(obj, self); - - assertEquals("route-target vertex found", true, traversal.V() - .has(AAIProperties.NODE_TYPE, "route-target").has("global-route-target", "modifyTargetKey2").has("route-target-role", "modifyRoleKey2").has("linked", true).hasNext()); - assertEquals("previous link removed", true, traversal.V() - .has(AAIProperties.NODE_TYPE, "route-target").has("global-route-target", "modifyTargetKey").has("route-target-role", "modifyRoleKey").hasNot("linked").hasNext()); - g.tx().rollback(); - - } - - @Test - public void verifyDeleteOfVertex() throws URISyntaxException, AAIException, UnsupportedEncodingException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException, InstantiationException, NoSuchMethodException, MalformedURLException { - - final Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v9); - final Introspector obj = loader.introspectorFromName("vpn-binding"); - obj.setValue("vpn-id", "deleteKey"); - TransactionalGraphEngine spy = spy(dbEngine); - TransactionalGraphEngine.Admin adminSpy = spy(dbEngine.asAdmin()); - Graph g = graph.newTransaction(); - GraphTraversalSource traversal = g.traversal(); - when(spy.asAdmin()).thenReturn(adminSpy); - when(adminSpy.getTraversalSource()).thenReturn(traversal); - when(adminSpy.getReadOnlyTraversalSource()).thenReturn(traversal); - when(spy.tx()).thenReturn(g); - when(self.property(AAIProperties.AAI_URI)).thenReturn(prop); - when(prop.orElse(null)).thenReturn(obj.getURI()); - DBSerializer serializer = new DBSerializer(version, spy, introspectorFactoryType, "AAI_TEST"); - SideEffectRunner runner = new SideEffectRunner - .Builder(spy, serializer).addSideEffect(DataLinkWriter.class).build(); - - runner.execute(obj, self); - - assertEquals("route-target vertex not found", false, traversal.V() - .has(AAIProperties.NODE_TYPE, "route-target").has("global-route-target", "deleteTargetKey").has("route-target-role", "deleteRoleKey").has("linked", true).hasNext()); - g.tx().rollback(); - - } - - @Test - public void verifyPropertyPopulation() throws URISyntaxException, AAIException, UnsupportedEncodingException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException, InstantiationException, NoSuchMethodException, MalformedURLException { - - final Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v9); - final Introspector obj = loader.introspectorFromName("vpn-binding"); - obj.setValue("vpn-id", "getKey"); - TransactionalGraphEngine spy = spy(dbEngine); - TransactionalGraphEngine.Admin adminSpy = spy(dbEngine.asAdmin()); - Graph g = graph.newTransaction(); - GraphTraversalSource traversal = g.traversal(); - when(spy.asAdmin()).thenReturn(adminSpy); - when(adminSpy.getTraversalSource()).thenReturn(traversal); - when(spy.tx()).thenReturn(g); - when(self.property(AAIProperties.AAI_URI)).thenReturn(prop); - when(prop.orElse(null)).thenReturn(obj.getURI()); - DBSerializer serializer = new DBSerializer(version, spy, introspectorFactoryType, "AAI_TEST"); - SideEffectRunner runner = new SideEffectRunner - .Builder(spy, serializer).addSideEffect(DataLinkReader.class).build(); - - runner.execute(obj, self); - - assertEquals("both properties have been populated in target object", true, obj.getValue("global-route-target").equals("getTargetKey") && obj.getValue("route-target-role").equals("getRoleKey")); - g.tx().rollback(); - - } - - @Test - public void verifyPropertyPopulationWithV10OnlyPut() throws URISyntaxException, AAIException, UnsupportedEncodingException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException, InstantiationException, NoSuchMethodException, MalformedURLException { - final Introspector obj = loader.introspectorFromName("vpn-binding"); - obj.setValue("vpn-id", "getKeyNoLink"); - final Introspector routeTargets = loader.introspectorFromName("route-targets"); - obj.setValue("route-targets", routeTargets.getUnderlyingObject()); - List targets = routeTargets.getValue("route-target"); - final Introspector routeTargetOne = loader.introspectorFromName("route-target"); - routeTargetOne.setValue("global-route-target", "getTargetKeyNoLink"); - routeTargetOne.setValue("route-target-role", "getRoleKeyNoLink"); - targets.add(routeTargetOne.getUnderlyingObject()); - final Introspector routeTargetTwo = loader.introspectorFromName("route-target"); - routeTargetTwo.setValue("global-route-target", "getTargetKeyNoLink2"); - routeTargetTwo.setValue("route-target-role", "getRoleKeyNoLink2"); - targets.add(routeTargetTwo.getUnderlyingObject()); - TransactionalGraphEngine spy = spy(dbEngine); - TransactionalGraphEngine.Admin adminSpy = spy(dbEngine.asAdmin()); - Graph g = graph.newTransaction(); - GraphTraversalSource traversal = g.traversal(); - when(spy.tx()).thenReturn(g); - when(spy.asAdmin()).thenReturn(adminSpy); - when(adminSpy.getTraversalSource()).thenReturn(traversal); - when(spy.tx()).thenReturn(g); - when(parser.isDependent()).thenReturn(false); - when(self.property(AAIProperties.AAI_URI)).thenReturn(prop); - when(prop.orElse(null)).thenReturn(obj.getURI()); - DBSerializer serializer = new DBSerializer(version, spy, introspectorFactoryType, "AAI_TEST"); - Vertex v = serializer.createNewVertex(obj); - serializer.serializeToDb(obj, v, parser, obj.getURI(), "testing"); - Vertex routeTargetOneV = traversal.V().has("global-route-target", "getTargetKeyNoLink").next(); - Vertex routeTargetTwoV = traversal.V().has("global-route-target", "getTargetKeyNoLink2").next(); - - assertEquals("first route target put has linked", true, routeTargetOneV.property(AAIProperties.LINKED).orElse(false)); - assertEquals("second route target put does not have linked", false, routeTargetTwoV.property(AAIProperties.LINKED).orElse(false)); - - g.tx().rollback(); - - } -} diff --git a/aai-core/src/test/java/org/openecomp/aai/introspection/validation/IntrospectorValidationTest.java b/aai-core/src/test/java/org/openecomp/aai/introspection/validation/IntrospectorValidationTest.java deleted file mode 100644 index 8b76967a..00000000 --- a/aai-core/src/test/java/org/openecomp/aai/introspection/validation/IntrospectorValidationTest.java +++ /dev/null @@ -1,95 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.introspection.validation; - -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.*; -import org.openecomp.aai.introspection.tools.IntrospectorValidator; -import org.openecomp.aai.introspection.tools.Issue; -import org.openecomp.aai.introspection.tools.IssueType; -import org.openecomp.aai.serialization.queryformats.QueryFormatTestHelper; -import org.openecomp.aai.util.AAIConstants; - -import java.util.List; - -import static org.junit.Assert.assertEquals; - -public class IntrospectorValidationTest { - - - private final static Version version = Version.v10; - private final static ModelType introspectorFactoryType = ModelType.MOXY; - private static Loader loader; - private IntrospectorValidator validator; - @BeforeClass - public static void setUp() throws NoSuchFieldException, SecurityException, Exception { - System.setProperty("AJSC_HOME", "."); - System.setProperty("BUNDLECONFIG_DIR", "bundleconfig-local"); - QueryFormatTestHelper.setFinalStatic(AAIConstants.class.getField("AAI_HOME_ETC_OXM"), "src/test/resources/org/openecomp/aai/introspection/"); - - loader = LoaderFactory.createLoaderForVersion(introspectorFactoryType, version); - - } - @Before - public void createValidator() { - validator = new IntrospectorValidator.Builder() - .validateRequired(false) - .restrictDepth(10000) - .build(); - } - @Ignore - @Test - public void verifySuccessWhenEmpty() throws AAIException { - Introspector obj = loader.introspectorFromName("test-object"); - obj.setValue("vnf-id", "key1"); - validator.validate(obj); - List issues = validator.getIssues(); - assertEquals("no issues found", true, issues.isEmpty()); - } - - @Ignore - @Test - public void verifyRequiresSingleFieldFailure() throws AAIException { - Introspector obj = loader.introspectorFromName("test-object"); - obj.setValue("vnf-id", "key1"); - obj.setValue("model-invariant-id", "id1"); - validator.validate(obj); - List issues = validator.getIssues(); - assertEquals("issues found", true, issues.size() == 1); - Issue issue = issues.get(0); - assertEquals("found expected issue", IssueType.DEPENDENT_PROP_NOT_FOUND, issue.getType()); - } - @Ignore - @Test - public void verifyRequiresSuccess() throws AAIException { - Introspector obj = loader.introspectorFromName("test-object"); - obj.setValue("vnf-id", "key1"); - obj.setValue("model-invariant-id", "id1"); - obj.setValue("model-version-id", "version-id1"); - validator.validate(obj); - List issues = validator.getIssues(); - assertEquals("no issues found", true, issues.isEmpty()); - } -} diff --git a/aai-core/src/test/java/org/openecomp/aai/logging/CNNameTest.java b/aai-core/src/test/java/org/openecomp/aai/logging/CNNameTest.java deleted file mode 100644 index b4705030..00000000 --- a/aai-core/src/test/java/org/openecomp/aai/logging/CNNameTest.java +++ /dev/null @@ -1,137 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.logging; - -import ch.qos.logback.access.spi.IAccessEvent; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mockito; -import org.openecomp.aai.logging.CNName; -import org.openecomp.aai.serialization.queryformats.QueryFormatTestHelper; -import org.openecomp.aai.util.AAIConstants; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.agent.PowerMockAgent; - -import javax.security.auth.x500.X500Principal; -import javax.servlet.http.HttpServletRequest; -import java.security.cert.X509Certificate; - -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - -@PowerMockIgnore("javax.security.auth.x500.X500Principal") -@PrepareForTest({IAccessEvent.class, HttpServletRequest.class, X509Certificate.class}) -public class CNNameTest { - - static { - PowerMockAgent.initializeIfNeeded(); - } - - - IAccessEvent mockAccEvent; - HttpServletRequest mockHttpServletRequest; - CNName cnname; - X509Certificate cert; - - /** - * Initialize. - */ - @Before - public void initialize() throws Exception { - System.setProperty("AJSC_HOME", "."); - System.setProperty("BUNDLECONFIG_DIR", "src/test/resources/bundleconfig-local"); - QueryFormatTestHelper.setFinalStatic(AAIConstants.class.getField("AAI_HOME_ETC_OXM"), "src/test/resources/bundleconfig-local/etc/oxm/"); - mockAccEvent = Mockito.mock(IAccessEvent.class); - mockHttpServletRequest = Mockito.mock(HttpServletRequest.class); - cert = Mockito.mock(X509Certificate.class); - } - - - /** - * Test 'convert' when there is no AccessConverter. - */ - @Test - public void testConvert_withoutAccessConverter(){ - cnname = getTestObj(false); - assertTrue("Conversion failed with no AccessConverter", "INACTIVE_HEADER_CONV".equals(cnname.convert(mockAccEvent))); - } - - /** - * Test 'convert' with no CipherSuite. - */ - @Test - public void testConvert_withNullCipherSuite(){ - setupForCipherSuite(null); - assertTrue("Conversion failed for a null CipherSuite", "-".equals(cnname.convert(mockAccEvent))); - } - - - /** - * Test 'convert' with a non-null CipherSuite. - */ - @Test - public void testConvert_withNotNullCipherSuite(){ - - setupForCipherSuite("StrRepOfAValidSuite"); - - final X500Principal principal = new X500Principal("CN=AAI, OU=DOX, O=BWS, C=CA"); - - Mockito.when(cert.getSubjectX500Principal()).thenReturn(principal); - - final X509Certificate[] certChain = {cert}; - - when(mockHttpServletRequest.getAttribute("javax.servlet.request.X509Certificate")).thenReturn(certChain); - - assertTrue("Conversion failed for a valid CipherSuite", principal.toString().equals(cnname.convert(mockAccEvent))); - } - - - /** - * Helper method to mock IAccessEvent and HttpServletRequest. - * - * @param suite CipherSuite to be used in current test - */ - private void setupForCipherSuite(String suite){ - cnname = getTestObj(true); - when(mockAccEvent.getRequest()).thenReturn(mockHttpServletRequest); - when(mockHttpServletRequest.getAttribute("javax.servlet.request.cipher_suite")).thenReturn(suite); - } - - - /** - * Helper method to create a CNName object with overridden 'start status' . - * - * @param instanceStarted Start status to be used - * @return CNName object to test - */ - private CNName getTestObj(final boolean instanceStarted){ - return new CNName(){ - @Override - public boolean isStarted(){ - return instanceStarted; - } - }; - } -} - - - diff --git a/aai-core/src/test/java/org/openecomp/aai/logging/CustomLogPatternLayoutTest.java b/aai-core/src/test/java/org/openecomp/aai/logging/CustomLogPatternLayoutTest.java deleted file mode 100644 index 3e79646b..00000000 --- a/aai-core/src/test/java/org/openecomp/aai/logging/CustomLogPatternLayoutTest.java +++ /dev/null @@ -1,51 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.logging; - -import org.junit.Test; -import org.openecomp.aai.logging.CNName; -import org.openecomp.aai.logging.CustomLogPatternLayout; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -public class CustomLogPatternLayoutTest { - - /** - * Test null when defaultConverterMap doesn't have corresponding entry. - */ - @Test - public void testNull(){ - String s = CustomLogPatternLayout.defaultConverterMap.get("z"); - assertFalse("Entry not found for key 'z'", CNName.class.getName().equals(s)); - } - - /** - * Test defaultConverterMap when valid entry exists. - */ - @Test - public void testEntryFor_Z(){ - CustomLogPatternLayout layout = new CustomLogPatternLayout(); - String s = CustomLogPatternLayout.defaultConverterMap.get("z"); - assertTrue("Entry not found for key 'z'", CNName.class.getName().equals(s)); - } - -} diff --git a/aai-core/src/test/java/org/openecomp/aai/logging/DME2RestFlagTest.java b/aai-core/src/test/java/org/openecomp/aai/logging/DME2RestFlagTest.java deleted file mode 100644 index 1ac17dad..00000000 --- a/aai-core/src/test/java/org/openecomp/aai/logging/DME2RestFlagTest.java +++ /dev/null @@ -1,82 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.logging; -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; -import ch.qos.logback.access.spi.IAccessEvent; -import org.junit.*; - - -public class DME2RestFlagTest { - - IAccessEvent mockAccEvent; - DME2RestFlag _DME2RestFlag; - - String[] temp = new String[4]; - - - @Before - public void setUp() throws Exception { - - mockAccEvent = mock(IAccessEvent.class); - _DME2RestFlag= spy(DME2RestFlag.class); - - } - private DME2RestFlag getTestObj(final boolean instanceStarted){ - return new DME2RestFlag(){ - @Override - public - boolean isStarted(){ - return instanceStarted; - } - }; - } - - @Test - public void convertTestAllValid(){ - temp[0]= "temp1"; - temp[1] = "-"; - when(mockAccEvent.getRequestParameter("envContext")).thenReturn(temp); - when(mockAccEvent.getRequestParameter("routeOffer")).thenReturn(temp); - when(mockAccEvent.getRequestParameter("version")).thenReturn(temp); - _DME2RestFlag = getTestObj(true); - assertEquals(_DME2RestFlag.convert(mockAccEvent),"DME2"); - } - - @Test - public void convertMissingRouteTest(){ - temp[0]= ""; - temp[1] = "-"; - when(mockAccEvent.getRequestParameter("envContext")).thenReturn(temp); - when(mockAccEvent.getRequestParameter("routeOffer")).thenReturn(temp); - when(mockAccEvent.getRequestParameter("version")).thenReturn(temp); - _DME2RestFlag = getTestObj(true); - assertEquals(_DME2RestFlag.convert(mockAccEvent),"REST"); - } - - @Test - public void convertIsStartedFalseTest(){ - _DME2RestFlag = getTestObj(false); - assertEquals(_DME2RestFlag.convert(mockAccEvent),"INACTIVE_HEADER_CONV"); - } - - -} diff --git a/aai-core/src/test/java/org/openecomp/aai/logging/EelfClassOfCallerTest.java b/aai-core/src/test/java/org/openecomp/aai/logging/EelfClassOfCallerTest.java deleted file mode 100644 index 63ac5683..00000000 --- a/aai-core/src/test/java/org/openecomp/aai/logging/EelfClassOfCallerTest.java +++ /dev/null @@ -1,70 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.logging; - -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; -import ch.qos.logback.classic.spi.ILoggingEvent; -import org.junit.*; - -public class EelfClassOfCallerTest { - - EelfClassOfCaller _eelfClassOfCaller; - ILoggingEvent mockEvent; - StackTraceElement[] cdafive = new StackTraceElement[5]; - StackTraceElement[] cdaone = new StackTraceElement[1]; - StackTraceElement[] cdazero = new StackTraceElement[0]; - - - @Before - public void setUp() throws Exception { - - mockEvent = mock(ILoggingEvent.class); - _eelfClassOfCaller= spy(EelfClassOfCaller.class); - - } - - - @Test - public void getFullyQualifiedNameCDALENFiveTest(){ - StackTraceElement temp = new StackTraceElement("classname_five","methodname","filename", 4); - cdafive[2]=temp; - when(mockEvent.getCallerData()).thenReturn(cdafive); - assertEquals(_eelfClassOfCaller.getFullyQualifiedName(mockEvent),"classname_five"); - - } - @Test - public void getFullyQualifiedNameCDALenOneTest(){ - StackTraceElement temp = new StackTraceElement("classname_one","methodname","filename", 4); - cdaone[0]=temp; - when(mockEvent.getCallerData()).thenReturn(cdaone); - assertEquals(_eelfClassOfCaller.getFullyQualifiedName(mockEvent),"classname_one"); - - } - - @Test - public void getFullyQualifiedNameCDALenZeroTest(){ - when(mockEvent.getCallerData()).thenReturn(cdazero); - assertEquals(_eelfClassOfCaller.getFullyQualifiedName(mockEvent),"?"); - - } - -} diff --git a/aai-core/src/test/java/org/openecomp/aai/logging/ErrorObjectTest.java b/aai-core/src/test/java/org/openecomp/aai/logging/ErrorObjectTest.java deleted file mode 100644 index 6a5bb843..00000000 --- a/aai-core/src/test/java/org/openecomp/aai/logging/ErrorObjectTest.java +++ /dev/null @@ -1,162 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.logging; - -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.Status; -import static org.junit.Assert.*; - -import org.junit.*; - -public class ErrorObjectTest { - - ErrorObject newErrorObject = new ErrorObject("disposition","category","severity", 200, "restErrorCode","errorCode","errorText"); - - //Constructor Tests - @Test - public void createObjectTest1(){ - //No HTTP Status argument - ErrorObject errorObject = new ErrorObject("severity","errorcode","errortext","disposition","category"); - assertNotNull(errorObject); - } - @Test - public void createObjectTest2(){ - //HTTP Status code as integer - ErrorObject errorObject = new ErrorObject("severity",200,"errorcode","errortext","disposition","category"); - assertNotNull(errorObject); - } - @Test - public void createObjectTest3(){ - //HTTP Status code as Status - ErrorObject errorObject = new ErrorObject("severity",Status.OK,"errorcode","errortext","disposition","category"); - assertNotNull(errorObject); - } - //Disposition Tests - @Test - public void getDispositionTest() { - assertEquals(newErrorObject.getDisposition(), "disposition"); - } - @Test - public void setDispositionTest() { - newErrorObject.setDisposition("newDisposition"); - assertEquals(newErrorObject.getDisposition(), "newDisposition"); - } - - //Category Tests - @Test - public void getCategoryTest(){ - assertEquals(newErrorObject.getCategory(), "category"); - } - @Test - public void setCategoryTest(){ - newErrorObject.setCategory("newCategory"); - assertEquals(newErrorObject.getCategory(), "newCategory"); - } - - //Severity Tests - @Test - public void getSeverityTest(){ - assertEquals(newErrorObject.getSeverity(), "severity"); - } - @Test - public void setSeverityTest(){ - newErrorObject.setSeverity("newSeverity"); - assertEquals(newErrorObject.getSeverity(), "newSeverity"); - } - - //Error Code Tests - @Test - public void getErrorCodeTest(){ - assertEquals(newErrorObject.getErrorCode(), "errorCode"); - } - @Test - public void SetErrorCodeTest(){ - newErrorObject.setErrorCode("newErrorCode"); - assertEquals(newErrorObject.getErrorCode(), "newErrorCode"); - } - - //HTTP Response Code Tests - @Test - public void getHTTPCodeTest(){ - assertEquals(newErrorObject.getHTTPResponseCode(), Status.OK); - } - @Test - public void setHTTPCodeTest(){ - newErrorObject.setHTTPResponseCode(201); - assertEquals(newErrorObject.getHTTPResponseCode(), Status.CREATED); - } - @Test(expected=IllegalArgumentException.class) - public void invalidHttpCodeTest(){ - newErrorObject.setHTTPResponseCode(6281723); - } - @Test(expected=IllegalArgumentException.class) - public void invalidHttpCodeTest2(){ - newErrorObject.setHTTPResponseCode("82901"); - } - - //Rest Error Code Tests - @Test - public void getRestErrorCodeTest(){ - assertEquals(newErrorObject.getRESTErrorCode(), "restErrorCode"); - } - @Test - public void setRestErrorCodeTest(){ - newErrorObject.setRESTErrorCode("newRestErrorCode"); - assertEquals(newErrorObject.getRESTErrorCode(), "newRestErrorCode"); - } - - //Error Text Tests - @Test - public void getErrorTextTest(){ - assertEquals(newErrorObject.getErrorText(), "errorText"); - } - @Test - public void setErrorTextTest(){ - newErrorObject.setErrorText("newErrorText"); - assertEquals(newErrorObject.getErrorText(), "newErrorText"); - } - @Test - public void getErrorCodeStringTest(){ - assertEquals(newErrorObject.getErrorCodeString(), "disposition.category.errorCode"); - } - @Test - public void getErrorCodeStringDisposition5Test(){ - //get Error Code String while Disposition = 5 - newErrorObject.setDisposition("5"); - assertEquals(newErrorObject.getErrorCodeString(), "ERR.5.category.errorCode"); - } - @Test - public void getSeverityCodeTest(){ - newErrorObject.setSeverity("WARN"); - assertEquals(newErrorObject.getSeverityCode(newErrorObject.getSeverity()), "1"); - - newErrorObject.setSeverity("ERROR"); - assertEquals(newErrorObject.getSeverityCode(newErrorObject.getSeverity()), "2"); - - newErrorObject.setSeverity("FATAL"); - assertEquals(newErrorObject.getSeverityCode(newErrorObject.getSeverity()), "3"); - } - //To String Test - @Test - public void toStringTest(){ - assertEquals(newErrorObject.toString(), "ErrorObject [errorCode=errorCode, errorText=errorText, restErrorCode=restErrorCode, httpResponseCode=OK, severity=severity, disposition=disposition, category=category]"); - } -} diff --git a/aai-core/src/test/java/org/openecomp/aai/logging/LoggingContextTest.java b/aai-core/src/test/java/org/openecomp/aai/logging/LoggingContextTest.java deleted file mode 100644 index 9cc522eb..00000000 --- a/aai-core/src/test/java/org/openecomp/aai/logging/LoggingContextTest.java +++ /dev/null @@ -1,107 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.logging; - -import org.junit.Test; - -import java.util.*; - -import static org.junit.Assert.*; - -public class LoggingContextTest { - - private static final int MAX_STORED_CONTEXTS = 100; - - @Test - public void testStopWatch() { - try { - LoggingContext.stopWatchStop(); - throw new AssertionError("No exception thrown when LoggingContext.stopWatchStop() called without a prior LoggingContext.stopWatchStart()"); - } catch (StopWatchNotStartedException e) { - //Expected - } - - LoggingContext.stopWatchStart(); - - assertTrue(LoggingContext.stopWatchStop() >= 0); - - try { - LoggingContext.stopWatchStop(); - throw new AssertionError("No exception thrown when LoggingContext.stopWatchStop() twice in succession"); - } catch (StopWatchNotStartedException e) { - //Expected - } - } - - @Test - public void testRequestId() { //AKA Transaction ID - final String sUuid = "57d51eaa-edc6-4f50-a69d-f2d4d2445120"; - - LoggingContext.requestId(sUuid); - - assertEquals(LoggingContext.requestId(), UUID.fromString(sUuid)); - - final UUID uuid = UUID.randomUUID(); - - LoggingContext.requestId(uuid); - - assertEquals(LoggingContext.requestId(), uuid); - - LoggingContext.requestId("foo"); //Illegal - this will result in a new, randomly - //generated UUID as per the logging spec - - assertNotNull(LoggingContext.requestId()); //Make sure ANY UUID was assigned - assertNotEquals(LoggingContext.requestId(), uuid); //Make sure it actually changed from the last - //known valid UUID - } - - @Test - public void testClear() { - LoggingContext.init(); - LoggingContext.clear(); - - assertEquals(Collections.emptyMap(), LoggingContext.getCopy()); - } - - @Test - public void testSaveRestore() { - - final Deque> contexts = new LinkedList> (); - - LoggingContext.init(); - - for (int i = 0; i < MAX_STORED_CONTEXTS; i++) { - LoggingContext.customField1(String.valueOf(i)); - - assertEquals(LoggingContext.customField1(), String.valueOf(i)); - - LoggingContext.save(); - - contexts.push(LoggingContext.getCopy()); - } - - while (contexts.peek() != null) { - LoggingContext.restore(); - - assertEquals(LoggingContext.getCopy(), contexts.pop()); - } - } -} diff --git a/aai-core/src/test/java/org/openecomp/aai/parsers/query/GraphTraversalTest.java b/aai-core/src/test/java/org/openecomp/aai/parsers/query/GraphTraversalTest.java deleted file mode 100644 index a4070b02..00000000 --- a/aai-core/src/test/java/org/openecomp/aai/parsers/query/GraphTraversalTest.java +++ /dev/null @@ -1,814 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.parsers.query; - -import org.apache.tinkerpop.gremlin.process.traversal.P; -import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; -import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__; -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.openecomp.aai.AAISetup; -import org.openecomp.aai.db.props.AAIProperties; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.LoaderFactory; -import org.openecomp.aai.introspection.ModelType; -import org.openecomp.aai.introspection.Version; -import org.openecomp.aai.rest.RestTokens; -import org.openecomp.aai.serialization.engines.QueryStyle; -import org.openecomp.aai.serialization.engines.TitanDBEngine; -import org.openecomp.aai.serialization.engines.TransactionalGraphEngine; - -import javax.ws.rs.core.MultivaluedHashMap; -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.UriBuilder; -import java.io.UnsupportedEncodingException; -import java.net.URI; -import java.util.ArrayList; -import java.util.List; - -import static org.hamcrest.CoreMatchers.containsString; -import static org.hamcrest.Matchers.hasProperty; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; - -public class GraphTraversalTest extends AAISetup { - - private TransactionalGraphEngine dbEngine; - private TransactionalGraphEngine dbEnginev9; - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - /** - * Configure. - * @throws Exception - * @throws SecurityException - * @throws NoSuchFieldException - */ - @Before - public void configure() throws Exception { - dbEngine = - new TitanDBEngine(QueryStyle.TRAVERSAL, - LoaderFactory.createLoaderForVersion(ModelType.MOXY, AAIProperties.LATEST), - false); - - dbEnginev9 = - new TitanDBEngine(QueryStyle.TRAVERSAL, - LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v9), - false); - } - - /** - * Parent query. - * - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - */ - @Test - public void parentQuery() throws UnsupportedEncodingException, AAIException { - URI uri = UriBuilder.fromPath("cloud-infrastructure/complexes/complex/key1").build(); - - QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); - - GraphTraversal expected = __.start().has("physical-location-id", "key1").has("aai-node-type", "complex"); - assertEquals( - "gremlin query should be " + expected.toString(), - expected.toString(), - query.getQueryBuilder().getQuery().toString()); - assertEquals( - "parent gremlin query should be equal to normal query", - expected.toString(), - query.getQueryBuilder().getParentQuery().getQuery().toString()); - assertEquals( - "result type should be complex", - "complex", - query.getResultType()); - assertEquals( - "result type should be empty", - "", - query.getParentResultType()); - assertEquals("dependent",false, query.isDependent()); - - - } - - /** - * Child query. - * - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - */ - @Test - public void childQuery() throws UnsupportedEncodingException, AAIException { - URI uri = UriBuilder.fromPath("cloud-infrastructure/complexes/complex/key1/ctag-pools/ctag-pool/key2/key3").build(); - QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); - GraphTraversal expected = __.start() - .has("physical-location-id", "key1").has("aai-node-type", "complex") - .out("hasCtagPool") - .has("aai-node-type", "ctag-pool") - .has("target-pe", "key2").has("availability-zone-name", "key3"); - GraphTraversal expectedParent = __.start() - .has("physical-location-id", "key1").has("aai-node-type", "complex"); - assertEquals( - "gremlin query should be " + expected.toString(), - expected.toString(), - query.getQueryBuilder().getQuery().toString()); - assertEquals( - "parent gremlin query should be equal the query for complex", - expectedParent.toString(), - query.getQueryBuilder().getParentQuery().getQuery().toString()); - assertEquals( - "result type should be complex", - "complex", - query.getParentResultType()); - assertEquals( - "result type should be ctag-pool", - "ctag-pool", - query.getResultType()); - assertEquals("dependent",true, query.isDependent()); - - - } - - /** - * Naming exceptions. - * - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - */ - @Test - public void namingExceptions() throws UnsupportedEncodingException, AAIException { - URI uri = UriBuilder.fromPath("network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags/cvlan-tag/655").build(); - QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); - GraphTraversal expected = __.start() - .has("vnf-id", "key1").has("aai-node-type", "vce") - .out("hasPortGroup") - .has("aai-node-type", "port-group") - .has("interface-id", "key2").out("hasCTag") - .has("aai-node-type", "cvlan-tag") - .has("cvlan-tag", 655); - GraphTraversal expectedParent = __.start() - .has("vnf-id", "key1").has("aai-node-type", "vce") - .out("hasPortGroup") - .has("aai-node-type", "port-group") - .has("interface-id", "key2"); - assertEquals( - "gremlin query should be " + expected.toString(), - expected.toString(), - query.getQueryBuilder().getQuery().toString()); - assertEquals( - "parent gremlin query should be equal the query for port group", - expectedParent.toString(), - query.getQueryBuilder().getParentQuery().getQuery().toString()); - assertEquals( - "result type should be cvlan-tag", - "cvlan-tag", - query.getResultType()); - assertEquals( - "result type should be port-group", - "port-group", - query.getParentResultType()); - assertEquals( - "contaner type should be empty", - "", - query.getContainerType()); - assertEquals("dependent",true, query.isDependent()); - - - } - - /** - * Gets the all. - * - * @return the all - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - */ - @Test - public void getAll() throws UnsupportedEncodingException, AAIException { - URI uri = UriBuilder.fromPath("network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags").build(); - QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); - GraphTraversal expected = __.start() - .has("vnf-id", "key1").has("aai-node-type", "vce") - .out("hasPortGroup") - .has("aai-node-type", "port-group") - .has("interface-id", "key2").out("hasCTag") - .has("aai-node-type", "cvlan-tag"); - GraphTraversal expectedParent = __.start() - .has("vnf-id", "key1").has("aai-node-type", "vce") - .out("hasPortGroup") - .has("aai-node-type", "port-group") - .has("interface-id", "key2"); - assertEquals( - "gremlin query should be " + expected.toString(), - expected.toString(), - query.getQueryBuilder().getQuery().toString()); - assertEquals( - "parent gremlin query should be equal the query for port group", - expectedParent.toString(), - query.getQueryBuilder().getParentQuery().getQuery().toString()); - assertEquals( - "result type should be port-group", - "port-group", - query.getParentResultType()); - assertEquals( - "result type should be cvlan-tag", - "cvlan-tag", - query.getResultType()); - assertEquals( - "container type should be cvlan-tags", - "cvlan-tags", - query.getContainerType()); - assertEquals("dependent",true, query.isDependent()); - - - } - - @Test - public void getAllParent() throws UnsupportedEncodingException, AAIException { - URI uri = UriBuilder.fromPath("cloud-infrastructure/pservers").build(); - QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); - GraphTraversal expected = __.start() - .has("aai-node-type", "pserver"); - GraphTraversal expectedParent = __.start() - .has("aai-node-type", "pserver"); - assertEquals( - "gremlin query should be " + expected.toString(), - expected.toString(), - query.getQueryBuilder().getQuery().toString()); - assertEquals( - "parent gremlin query should be equal the query for pserver", - expectedParent.toString(), - query.getQueryBuilder().getParentQuery().getQuery().toString()); - assertEquals( - "parent result type should be empty", - "", - query.getParentResultType()); - assertEquals( - "result type should be pserver", - "pserver", - query.getResultType()); - assertEquals( - "container type should be pservers", - "pservers", - query.getContainerType()); - assertEquals("dependent",false, query.isDependent()); - - - } - - - /** - * Gets the via query param. - * - * @return the via query param - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - */ - @Test - public void getViaQueryParam() throws UnsupportedEncodingException, AAIException { - URI uri = UriBuilder.fromPath("cloud-infrastructure/cloud-regions/cloud-region/mycloudowner/mycloudregionid/tenants/tenant").build(); - MultivaluedMap map = new MultivaluedHashMap<>(); - map.putSingle("tenant-name", "Tenant1"); - QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri, map); - GraphTraversal expected = __.start() - .has("cloud-owner", "mycloudowner").has("cloud-region-id", "mycloudregionid") - .has("aai-node-type", "cloud-region") - .out("has") - .has("aai-node-type", "tenant") - .has("tenant-name", "Tenant1"); - - GraphTraversal expectedParent = __.start() - .has("cloud-owner", "mycloudowner").has("cloud-region-id", "mycloudregionid") - .has("aai-node-type", "cloud-region"); - - assertEquals( - "gremlin query should be " + expected.toString(), - expected.toString(), - query.getQueryBuilder().getQuery().toString()); - assertEquals( - "parent gremlin query should be equal the query for cloud-region", - expectedParent.toString(), - query.getQueryBuilder().getParentQuery().getQuery().toString()); - assertEquals( - "result type should be cloud-region", - "cloud-region", - query.getParentResultType()); - assertEquals( - "result type should be tenant", - "tenant", - query.getResultType()); - assertEquals( - "container type should be empty", - "", - query.getContainerType()); - assertEquals("dependent",true, query.isDependent()); - - } - - @Test - public void getViaDuplicateQueryParam() throws UnsupportedEncodingException, AAIException { - URI uri = UriBuilder.fromPath("cloud-infrastructure/cloud-regions/cloud-region/mycloudowner/mycloudregionid/tenants/tenant").build(); - MultivaluedMap map = new MultivaluedHashMap<>(); - List values = new ArrayList<>(); - values.add("Tenant1"); - values.add("Tenant2"); - map.put("tenant-name", values); - QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri, map); - GraphTraversal expected = __.start() - .has("cloud-owner", "mycloudowner").has("cloud-region-id", "mycloudregionid") - .has("aai-node-type", "cloud-region") - .out("has") - .has("aai-node-type", "tenant") - .has("tenant-name", P.within(values)); - - GraphTraversal expectedParent = __.start() - .has("cloud-owner", "mycloudowner").has("cloud-region-id", "mycloudregionid") - .has("aai-node-type", "cloud-region"); - - assertEquals( - "gremlin query should be " + expected.toString(), - expected.toString(), - query.getQueryBuilder().getQuery().toString()); - assertEquals( - "parent gremlin query should be equal the query for cloud-region", - expectedParent.toString(), - query.getQueryBuilder().getParentQuery().getQuery().toString()); - assertEquals( - "result type should be cloud-region", - "cloud-region", - query.getParentResultType()); - assertEquals( - "result type should be tenant", - "tenant", - query.getResultType()); - assertEquals( - "container type should be empty", - "", - query.getContainerType()); - assertEquals("dependent",true, query.isDependent()); - - } - - /** - * Gets the plural via query param. - * - * @return the plural via query param - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - */ - @Test - public void getPluralViaQueryParam() throws UnsupportedEncodingException, AAIException { - URI uri = UriBuilder.fromPath("network/vnfcs").build(); - MultivaluedMap map = new MultivaluedHashMap<>(); - map.putSingle("prov-status", "up"); - QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri, map); - GraphTraversal expected = __.start() - .has("aai-node-type", "vnfc") - .has("prov-status", "up"); - - GraphTraversal expectedParent = __.start() - .has("aai-node-type", "vnfc"); - - assertEquals( - "gremlin query should be " + expected.toString(), - expected.toString(), - query.getQueryBuilder().getQuery().toString()); - assertEquals( - "parent", - expectedParent.toString(), - query.getQueryBuilder().getParentQuery().getQuery().toString()); - assertEquals( - "parent result type should be empty", - "", - query.getParentResultType()); - assertEquals( - "result type should be vnfc", - "vnfc", - query.getResultType()); - assertEquals( - "container type should be empty", - "vnfcs", - query.getContainerType()); - assertEquals("dependent",true, query.isDependent()); - - } - - /** - * Gets the all query param naming exception. - * - * @return the all query param naming exception - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - */ - @Test - public void getAllQueryParamNamingException() throws UnsupportedEncodingException, AAIException { - URI uri = UriBuilder.fromPath("network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags").build(); - MultivaluedMap map = new MultivaluedHashMap<>(); - map.putSingle("cvlan-tag", "333"); - QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri, map); - - GraphTraversal expected = __.start() - .has("vnf-id", "key1").has("aai-node-type", "vce") - .out("hasPortGroup") - .has("aai-node-type", "port-group") - .has("interface-id", "key2").out("hasCTag") - .has("aai-node-type", "cvlan-tag") - .has("cvlan-tag", 333); - GraphTraversal expectedParent = __.start() - .has("vnf-id", "key1").has("aai-node-type", "vce") - .out("hasPortGroup") - .has("aai-node-type", "port-group") - .has("interface-id", "key2"); - assertEquals( - "gremlin query should be " + expected.toString(), - expected.toString(), - query.getQueryBuilder().getQuery().toString()); - assertEquals( - "parent gremlin query should be equal the query for port group", - expectedParent.toString(), - query.getQueryBuilder().getParentQuery().getQuery().toString()); - assertEquals( - "result type should be port-group", - "port-group", - query.getParentResultType()); - assertEquals( - "result type should be cvlan-tag", - "cvlan-tag", - query.getResultType()); - assertEquals( - "container type should be cvlan-tags", - "cvlan-tags", - query.getContainerType()); - assertEquals("dependent",true, query.isDependent()); - - - } - - /** - * Abstract type. - * - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - */ - @Test - public void abstractType() throws UnsupportedEncodingException, AAIException { - URI uri = UriBuilder.fromPath("vnf/key1").build(); - - QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); - - GraphTraversal expected = __.start() - .has("vnf-id", "key1").has(AAIProperties.NODE_TYPE, P.within("vce", "generic-vnf")); - - GraphTraversal expectedParent = expected; - assertEquals( - "gremlin query should be " + expected.toString(), - expected.toString(), - query.getQueryBuilder().getQuery().toString()); - assertEquals( - "parent gremlin query should be equal the query for port group", - expectedParent.toString(), - query.getQueryBuilder().getParentQuery().getQuery().toString()); - assertEquals( - "result type should be empty", - "", - query.getParentResultType()); - assertEquals( - "result type should be vnf", - "vnf", - query.getResultType()); - - assertEquals("dependent",false, query.isDependent()); - - - } - - /** - * Non parent abstract type. - * - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - */ - @Test - public void nonParentAbstractType() throws UnsupportedEncodingException, AAIException { - URI uri = UriBuilder.fromPath("cloud-infrastructure/pservers/pserver/key2/vnf/key1").build(); - thrown.expect(AAIException.class); - thrown.expectMessage(containsString("not a valid path")); - dbEngine.getQueryBuilder().createQueryFromURI(uri); - } - - @Test - public void parentAbstractTypeWithNesting() throws UnsupportedEncodingException, AAIException { - URI uri = UriBuilder.fromPath("vnf/key1/vf-modules/vf-module/key2").build(); - - QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); - - GraphTraversal expected = __.start() - .has("vnf-id", "key1").has(AAIProperties.NODE_TYPE, P.within("vce", "generic-vnf")) - .union(__.out("has").has(AAIProperties.NODE_TYPE, "vf-module")).has("vf-module-id", "key2"); - - GraphTraversal expectedParent = __.start() - .has("vnf-id", "key1").has(AAIProperties.NODE_TYPE, P.within("vce", "generic-vnf")); - assertEquals( - "gremlin query should be " + expected.toString(), - expected.toString(), - query.getQueryBuilder().getQuery().toString()); - assertEquals( - "parent gremlin query should be equal the query for ", - expectedParent.toString(), - query.getQueryBuilder().getParentQuery().getQuery().toString()); - assertEquals( - "result type should be vnf", - "vnf", - query.getParentResultType()); - assertEquals( - "result type should be vf-module", - "vf-module", - query.getResultType()); - - assertEquals("dependent",true, query.isDependent()); - - } - - @Test - public void getViaBadQueryParam() throws UnsupportedEncodingException, AAIException { - URI uri = UriBuilder.fromPath("cloud-infrastructure/cloud-regions/cloud-region/a/b/tenants/tenant").build(); - MultivaluedMap map = new MultivaluedHashMap<>(); - map.putSingle("tenant-n231ame", "Tenant1"); - thrown.expect(AAIException.class); - thrown.expect(hasProperty("code", is("AAI_3000"))); - - QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri, map); - - } - - @Test - public void getPluralViaBadQueryParam() throws UnsupportedEncodingException, AAIException { - URI uri = UriBuilder.fromPath("cloud-infrastructure/cloud-regions/cloud-region/a/b/tenants").build(); - MultivaluedMap map = new MultivaluedHashMap<>(); - map.putSingle("tenant-n231ame", "Tenant1"); - thrown.expect(AAIException.class); - thrown.expect(hasProperty("code", is("AAI_3000"))); - - QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri, map); - - } - - @Test - public void getPluralViaDuplicateQueryParam() throws UnsupportedEncodingException, AAIException { - URI uri = UriBuilder.fromPath("network/vnfcs").build(); - MultivaluedMap map = new MultivaluedHashMap<>(); - List values = new ArrayList<>(); - values.add("up"); - values.add("down"); - values.add("left"); - values.add("right"); - values.add("start"); - map.put("prov-status", values); - QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri, map); - GraphTraversal expected = __.start() - .has("aai-node-type", "vnfc") - .has("prov-status", P.within(values)); - - GraphTraversal expectedParent = __.start() - .has("aai-node-type", "vnfc"); - - assertEquals( - "gremlin query should be " + expected.toString(), - expected.toString(), - query.getQueryBuilder().getQuery().toString()); - assertEquals( - "parent", - expectedParent.toString(), - query.getQueryBuilder().getParentQuery().getQuery().toString()); - assertEquals( - "parent result type should be empty", - "", - query.getParentResultType()); - assertEquals( - "result type should be vnfc", - "vnfc", - query.getResultType()); - assertEquals( - "container type should be empty", - "vnfcs", - query.getContainerType()); - assertEquals("dependent",true, query.isDependent()); - - } - - @Test - public void dbAliasedSearch() throws UnsupportedEncodingException, AAIException { - URI uri = UriBuilder.fromPath("network/test-objects").build(); - MultivaluedMap map = new MultivaluedHashMap<>(); - map.putSingle("persona-model-customization-id", "key2"); - QueryParser query = dbEnginev9.getQueryBuilder().createQueryFromURI(uri, map); - GraphTraversal expected = __.start() - .has("aai-node-type", "test-object") - .has("model-customization-id", "key2"); - GraphTraversal expectedParent = __.start() - .has("aai-node-type", "test-object"); - - assertEquals( - "gremlin query should be " + expected.toString(), - expected.toString(), - query.getQueryBuilder().getQuery().toString()); - assertEquals( - "parent", - expectedParent.toString(), - query.getQueryBuilder().getParentQuery().getQuery().toString()); - - assertEquals( - "result type should be", - "test-object", - query.getResultType()); - assertEquals( - "result type should be empty", - "", - query.getParentResultType()); - assertEquals("dependent",true, query.isDependent()); - - - } - - @Test - public void dataLinkedSearch() throws UnsupportedEncodingException, AAIException { - URI uri = UriBuilder.fromPath("network/vpn-bindings").build(); - MultivaluedMap map = new MultivaluedHashMap<>(); - map.putSingle("global-route-target", "key2"); - QueryParser query = dbEnginev9.getQueryBuilder().createQueryFromURI(uri, map); - GraphTraversal expected = __.start() - .has("aai-node-type", "vpn-binding") - .where(__.out("has").has(AAIProperties.NODE_TYPE, "route-target").has("global-route-target", "key2")); - GraphTraversal expectedParent = __.start() - .has("aai-node-type", "vpn-binding"); - - assertEquals( - "gremlin query should be " + expected.toString(), - expected.toString(), - query.getQueryBuilder().getQuery().toString()); - assertEquals( - "parent", - expectedParent.toString(), - query.getQueryBuilder().getParentQuery().getQuery().toString()); - - assertEquals( - "result type should be", - "vpn-binding", - query.getResultType()); - assertEquals( - "result type should be empty", - "", - query.getParentResultType()); - assertEquals("dependent",true, query.isDependent()); - } - - @Test - public void pluralCousin() throws UnsupportedEncodingException, AAIException { - URI uri = UriBuilder.fromPath("cloud-infrastructure/complexes/complex/key1/related-to/pservers").build(); - - QueryParser query = dbEnginev9.getQueryBuilder().createQueryFromURI(uri); - GraphTraversal expected = __.start() - .has("physical-location-id", "key1") - .has("aai-node-type", "complex") - .in("locatedIn").has("aai-node-type", "pserver"); - GraphTraversal expectedParent = __.start() - .has("physical-location-id", "key1") - .has("aai-node-type", "complex"); - - assertEquals( - "gremlin query should be " + expected.toString(), - expected.toString(), - query.getQueryBuilder().getQuery().toString()); - assertEquals( - "parent", - expectedParent.toString(), - query.getQueryBuilder().getParentQuery().getQuery().toString()); - - assertEquals( - "result type should be", - "pserver", - query.getResultType()); - assertEquals( - "result type should be", - "complex", - query.getParentResultType()); - //this is controversial but we're not allowing writes on this currently - assertEquals("dependent",true, query.isDependent()); - } - - @Test - public void specificCousin() throws UnsupportedEncodingException, AAIException { - URI uri = UriBuilder.fromPath("cloud-infrastructure/complexes/complex/key1/related-to/pservers/pserver/key2").build(); - - QueryParser query = dbEnginev9.getQueryBuilder().createQueryFromURI(uri); - GraphTraversal expected = __.start() - .has("physical-location-id", "key1") - .has("aai-node-type", "complex") - .in("locatedIn").has("aai-node-type", "pserver") - .has("hostname", "key2"); - GraphTraversal expectedParent = __.start() - .has("physical-location-id", "key1") - .has("aai-node-type", "complex"); - - assertEquals( - "gremlin query should be " + expected.toString(), - expected.toString(), - query.getQueryBuilder().getQuery().toString()); - assertEquals( - "parent", - expectedParent.toString(), - query.getQueryBuilder().getParentQuery().getQuery().toString()); - - assertEquals( - "result type should be", - "pserver", - query.getResultType()); - assertEquals( - "result type should be", - "complex", - query.getParentResultType()); - //this is controversial but we're not allowing writes on this currently - assertEquals("dependent",true, query.isDependent()); - } - - @Test - public void doubleSpecificCousin() throws UnsupportedEncodingException, AAIException { - URI uri = UriBuilder.fromPath("cloud-infrastructure/complexes/complex/key1/related-to/pservers/pserver/key2/related-to/vservers/vserver/key3").build(); - - QueryParser query = dbEnginev9.getQueryBuilder().createQueryFromURI(uri); - GraphTraversal expected = __.start() - .has("physical-location-id", "key1") - .has("aai-node-type", "complex") - .in("locatedIn").has("aai-node-type", "pserver") - .has("hostname", "key2") - .in("runsOnPserver").has("aai-node-type", "vserver") - .has("vserver-id", "key3"); - GraphTraversal expectedParent = __.start() - .has("physical-location-id", "key1") - .has("aai-node-type", "complex") - .in("locatedIn").has("aai-node-type", "pserver") - .has("hostname", "key2"); - - assertEquals( - "gremlin query should be " + expected.toString(), - expected.toString(), - query.getQueryBuilder().getQuery().toString()); - assertEquals( - "parent", - expectedParent.toString(), - query.getQueryBuilder().getParentQuery().getQuery().toString()); - - assertEquals( - "result type should be", - "vserver", - query.getResultType()); - assertEquals( - "result type should be", - "pserver", - query.getParentResultType()); - //this is controversial but we're not allowing writes on this currently - assertEquals("dependent",true, query.isDependent()); - } - - @Test - public void traversalEndsInRelatedTo() throws UnsupportedEncodingException, AAIException { - URI uri = UriBuilder.fromPath("cloud-infrastructure/complexes/complex/key1/related-to").build(); - - thrown.expect(AAIException.class); - thrown.expectMessage(containsString(RestTokens.COUSIN.toString())); - QueryParser query = dbEnginev9.getQueryBuilder().createQueryFromURI(uri); - - } - - @Test - public void pluralCousinToPluralCousin() throws UnsupportedEncodingException, AAIException { - URI uri = UriBuilder.fromPath("cloud-infrastructure/complexes/related-to/pservers").build(); - - thrown.expect(AAIException.class); - thrown.expectMessage(containsString("chain plurals")); - QueryParser query = dbEnginev9.getQueryBuilder().createQueryFromURI(uri); - - } -} diff --git a/aai-core/src/test/java/org/openecomp/aai/parsers/query/LegacyQueryTest.java b/aai-core/src/test/java/org/openecomp/aai/parsers/query/LegacyQueryTest.java deleted file mode 100644 index baaad6c9..00000000 --- a/aai-core/src/test/java/org/openecomp/aai/parsers/query/LegacyQueryTest.java +++ /dev/null @@ -1,157 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.parsers.query; - -import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext; -import org.junit.Ignore; -import org.junit.Test; -import org.openecomp.aai.AAISetup; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.LoaderFactory; -import org.openecomp.aai.introspection.ModelInjestor; -import org.openecomp.aai.introspection.ModelType; -import org.openecomp.aai.introspection.Version; -import org.openecomp.aai.serialization.engines.QueryStyle; -import org.openecomp.aai.serialization.engines.TitanDBEngine; -import org.openecomp.aai.serialization.engines.TransactionalGraphEngine; - -import javax.ws.rs.core.UriBuilder; -import javax.xml.bind.JAXBException; -import java.io.UnsupportedEncodingException; -import java.net.URI; - -import static org.junit.Assert.assertEquals; - - -@Ignore -public class LegacyQueryTest extends AAISetup { - - private ModelInjestor injestor = ModelInjestor.getInstance(); - - private TransactionalGraphEngine dbEngine = - new TitanDBEngine(QueryStyle.GREMLIN_TRAVERSAL, - LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v8), - false); - private final Version version = Version.v8; - private DynamicJAXBContext context = injestor.getContextForVersion(version); - - - /** - * Parent query. - * - * @throws JAXBException the JAXB exception - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - */ - @Test - public void parentQuery() throws JAXBException, UnsupportedEncodingException, AAIException { - - URI uri = UriBuilder.fromPath("cloud-infrastructure/pservers/pserver/key1").build(); - - QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); - - String expected = - ".has('hostname', 'key1').has('aai-node-type', 'pserver')"; - assertEquals( - "gremlin query should be " + expected, - expected, - query.getQueryBuilder().getQuery()); - assertEquals( - "parent gremlin query should be equal to normal query", - expected, - query.getQueryBuilder().getParentQuery().getQuery()); - assertEquals( - "result type should be pserver", - "pserver", - query.getResultType()); - - } - - /** - * Child query. - * - * @throws JAXBException the JAXB exception - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - */ - @Test - public void childQuery() throws JAXBException, UnsupportedEncodingException, AAIException { - URI uri = UriBuilder.fromPath("cloud-infrastructure/pservers/pserver/key1/lag-interfaces/lag-interface/key2").build(); - QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); - - String expected = - ".has('hostname', 'key1').has('aai-node-type', 'pserver')" - + ".out('hasLAGInterface').has('aai-node-type', 'lag-interface')" - + ".has('interface-name', 'key2')"; - String parentExpected = - ".has('hostname', 'key1').has('aai-node-type', 'pserver')"; - assertEquals( - "gremlin query should be for node", - expected, - query.getQueryBuilder().getQuery()); - assertEquals( - "parent gremlin query should be for parent", - parentExpected, - query.getQueryBuilder().getParentQuery().getQuery()); - assertEquals( - "result type should be lag-interface", - "lag-interface", - query.getResultType()); - } - - /** - * Naming exceptions. - * - * @throws JAXBException the JAXB exception - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - */ - @Test - public void namingExceptions() throws JAXBException, UnsupportedEncodingException, AAIException { - URI uri = UriBuilder.fromPath("network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags/cvlan-tag/655").build(); - - QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); - String expected = - ".has('vnf-id', 'key1').has('aai-node-type', 'vce')" - + ".in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'port-group')" - + ".has('interface-id', 'key2')" - + ".in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'cvlan-tag')" - + ".has('cvlan-tag', 655)"; - String expectedParent = - ".has('vnf-id', 'key1').has('aai-node-type', 'vce')" - + ".in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'port-group')" - + ".has('interface-id', 'key2')"; - assertEquals( - "gremlin query should be " + expected, - expected, - query.getQueryBuilder().getQuery()); - assertEquals( - "parent gremlin query should be equal the query for port group", - expectedParent, - query.getQueryBuilder().getParentQuery().getQuery()); - assertEquals( - "result type should be cvlan-tag", - "cvlan-tag", - query.getResultType()); - - } - -} diff --git a/aai-core/src/test/java/org/openecomp/aai/parsers/query/RelationshipGremlinQueryTest.java b/aai-core/src/test/java/org/openecomp/aai/parsers/query/RelationshipGremlinQueryTest.java deleted file mode 100644 index 0aad09c4..00000000 --- a/aai-core/src/test/java/org/openecomp/aai/parsers/query/RelationshipGremlinQueryTest.java +++ /dev/null @@ -1,662 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.parsers.query; - -import org.eclipse.persistence.dynamic.DynamicEntity; -import org.eclipse.persistence.jaxb.UnmarshallerProperties; -import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext; -import org.junit.Ignore; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.openecomp.aai.AAISetup; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.*; -import org.openecomp.aai.serialization.engines.QueryStyle; -import org.openecomp.aai.serialization.engines.TitanDBEngine; -import org.openecomp.aai.serialization.engines.TransactionalGraphEngine; - -import javax.xml.bind.JAXBException; -import javax.xml.bind.Unmarshaller; -import javax.xml.transform.stream.StreamSource; -import java.io.StringReader; -import java.io.UnsupportedEncodingException; - -import static org.hamcrest.CoreMatchers.containsString; -import static org.junit.Assert.assertEquals; - -@Ignore -public class RelationshipGremlinQueryTest extends AAISetup { - - private ModelInjestor injestor = ModelInjestor.getInstance(); - private TransactionalGraphEngine dbEngine = - new TitanDBEngine(QueryStyle.GREMLIN_TRAVERSAL, - LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v8), - false); - private final Version version = Version.v8; - private DynamicJAXBContext context = injestor.getContextForVersion(version); - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - /** - * Parent query. - * - * @throws JAXBException the JAXB exception - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - */ - @Test - public void parentQuery() throws JAXBException, UnsupportedEncodingException, AAIException { - - String content = - "{" - + "\"related-to\" : \"pserver\"," - + "\"relationship-data\" : [{" - + "\"relationship-key\" : \"pserver.hostname\"," - + "\"relationship-value\" : \"key1\"" - + "}]" - + "}"; - - Unmarshaller unmarshaller = context.createUnmarshaller(); - unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); - unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); - unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); - Object obj = context.newDynamicEntity("Relationship"); - - DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); - - Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity); - QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); - - String expected = - ".has('hostname', 'key1').has('aai-node-type', 'pserver')"; - assertEquals( - "gremlin query should be " + expected, - expected, - query.getQueryBuilder().getQuery()); - assertEquals( - "parent gremlin query should be equal to normal query", - expected, - query.getQueryBuilder().getParentQuery().getQuery()); - assertEquals( - "result type should be pserver", - "pserver", - query.getResultType()); - - } - - /** - * Child query. - * - * @throws JAXBException the JAXB exception - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - */ - @Test - public void childQuery() throws JAXBException, UnsupportedEncodingException, AAIException { - String content = - "{" - + "\"related-to\" : \"lag-interface\"," - + "\"relationship-data\" : [{" - + "\"relationship-key\" : \"pserver.hostname\"," - + "\"relationship-value\" : \"key1\"" - + "}, {" - + "\"relationship-key\" : \"lag-interface.interface-name\"," - + "\"relationship-value\" : \"key2\"" - + "}]" - + "}"; - - Unmarshaller unmarshaller = context.createUnmarshaller(); - unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); - unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); - unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); - Object obj = context.newDynamicEntity("Relationship"); - - DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); - - Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity); - QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); - - String expected = ".has('hostname', 'key1').has('aai-node-type', 'pserver').in('tosca.relationships.BindsTo').has('aai-node-type', 'lag-interface')" - + ".has('interface-name', 'key2')"; - String parentExpected = - ".has('hostname', 'key1').has('aai-node-type', 'pserver')"; - assertEquals( - "gremlin query should be for node", - expected, - query.getQueryBuilder().getQuery()); - assertEquals( - "parent gremlin query should be for parent", - parentExpected, - query.getQueryBuilder().getParentQuery().getQuery()); - assertEquals( - "result type should be lag-interface", - "lag-interface", - query.getResultType()); - } - - /** - * Naming exceptions. - * - * @throws JAXBException the JAXB exception - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - */ - @Test - public void namingExceptions() throws JAXBException, UnsupportedEncodingException, AAIException { - String content = - "{" - + "\"related-to\" : \"cvlan-tag\"," - + "\"relationship-data\" : [{" - + "\"relationship-key\" : \"vce.vnf-id\"," - + "\"relationship-value\" : \"key1\"" - + "}, {" - + "\"relationship-key\" : \"port-group.interface-id\"," - + "\"relationship-value\" : \"key2\"" - + "},{" - + "\"relationship-key\" : \"cvlan-tag.cvlan-tag\"," - + "\"relationship-value\" : \"655\"" - + "}]" - + "}"; - - Unmarshaller unmarshaller = context.createUnmarshaller(); - unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); - unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); - unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); - Object obj = context.newDynamicEntity("Relationship"); - - DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); - - Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity); - QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); - String expected = - ".has('vnf-id', 'key1').has('aai-node-type', 'vce')" - + ".in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'port-group')" - + ".has('interface-id', 'key2').in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'cvlan-tag')" - + ".has('cvlan-tag', 655)"; - String expectedParent = - ".has('vnf-id', 'key1').has('aai-node-type', 'vce')" - + ".in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'port-group')" - + ".has('interface-id', 'key2')"; - assertEquals( - "gremlin query should be " + expected, - expected, - query.getQueryBuilder().getQuery()); - assertEquals( - "parent gremlin query should be equal the query for port group", - expectedParent, - query.getQueryBuilder().getParentQuery().getQuery()); - assertEquals( - "result type should be cvlan-tag", - "cvlan-tag", - query.getResultType()); - - } - - /** - * Scrambled relationship. - * - * @throws JAXBException the JAXB exception - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - */ - @Test - public void scrambledRelationship() throws JAXBException, UnsupportedEncodingException, AAIException { - String content = - "{" - + "\"related-to\" : \"l3-interface-ipv4-address-list\"," - + "\"relationship-data\" : [{" - + "\"relationship-key\" : \"l3-interface-ipv4-address-list.l3-interface-ipv4-address\"," - + "\"relationship-value\" : \"key5\"" - + "},{" - + "\"relationship-key\" : \"lag-interface.interface-name\"," - + "\"relationship-value\" : \"key2\"" - + "},{" - + "\"relationship-key\" : \"l-interface.interface-name\"," - + "\"relationship-value\" : \"key3\"" - + "},{" - + "\"relationship-key\" : \"vlan.vlan-interface\"," - + "\"relationship-value\" : \"key4\"" - + "},{" - + "\"relationship-key\" : \"generic-vnf.vnf-id\"," - + "\"relationship-value\" : \"key1\"" - + "}]" - + "}"; - scrambledRelationshipSpec(content); - } - - /** - * Reversed relationship. - * - * @throws JAXBException the JAXB exception - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - */ - @Test - public void reversedRelationship() throws JAXBException, UnsupportedEncodingException, AAIException { - String content = - "{" - + "\"related-to\" : \"l3-interface-ipv4-address-list\"," - + "\"relationship-data\" : [{" - + "\"relationship-key\" : \"l3-interface-ipv4-address-list.l3-interface-ipv4-address\"," - + "\"relationship-value\" : \"key5\"" - + "},{" - + "\"relationship-key\" : \"vlan.vlan-interface\"," - + "\"relationship-value\" : \"key4\"" - + "},{" - + "\"relationship-key\" : \"l-interface.interface-name\"," - + "\"relationship-value\" : \"key3\"" - + "},{" - + "\"relationship-key\" : \"lag-interface.interface-name\"," - + "\"relationship-value\" : \"key2\"" - + "},{" - + "\"relationship-key\" : \"generic-vnf.vnf-id\"," - + "\"relationship-value\" : \"key1\"" - + "}]" - + "}"; - scrambledRelationshipSpec(content); - } - - /** - * Ordered ambiguous relationship. - * - * @throws JAXBException the JAXB exception - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - */ - @Test - public void orderedAmbiguousRelationship() throws JAXBException, UnsupportedEncodingException, AAIException { - String content = - "{" - + "\"related-to\" : \"l3-interface-ipv4-address-list\"," - + "\"relationship-data\" : [{" - + "\"relationship-key\" : \"generic-vnf.vnf-id\"," - + "\"relationship-value\" : \"key1\"" - + "},{" - + "\"relationship-key\" : \"lag-interface.interface-name\"," - + "\"relationship-value\" : \"key2\"" - + "},{" - + "\"relationship-key\" : \"l-interface.interface-name\"," - + "\"relationship-value\" : \"key3\"" - + "},{" - + "\"relationship-key\" : \"vlan.vlan-interface\"," - + "\"relationship-value\" : \"key4\"" - + "},{" - + "\"relationship-key\" : \"l3-interface-ipv4-address-list.l3-interface-ipv4-address\"," - + "\"relationship-value\" : \"key5\"" - + "}]" - + "}"; - scrambledRelationshipSpec(content); - } - - /** - * Scrambled relationship spec. - * - * @param content the content - * @throws JAXBException the JAXB exception - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - */ - public void scrambledRelationshipSpec(String content) throws JAXBException, UnsupportedEncodingException, AAIException { - - - Unmarshaller unmarshaller = context.createUnmarshaller(); - unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); - unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); - unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); - Object obj = context.newDynamicEntity("Relationship"); - - DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); - - Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity); - QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); - String expected = - ".has('vnf-id', 'key1').has('aai-node-type', 'generic-vnf')" - + ".in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'lag-interface')" - + ".has('interface-name', 'key2').in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'l-interface')" - + ".has('interface-name', 'key3').out('tosca.relationships.LinksTo').has('aai-node-type', 'vlan')" - + ".has('vlan-interface', 'key4').in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'l3-interface-ipv4-address-list')" - + ".has('l3-interface-ipv4-address', 'key5')"; - String expectedParent = - ".has('vnf-id', 'key1').has('aai-node-type', 'generic-vnf')" - + ".in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'lag-interface')" - + ".has('interface-name', 'key2').in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'l-interface')" - + ".has('interface-name', 'key3').out('tosca.relationships.LinksTo').has('aai-node-type', 'vlan')" - + ".has('vlan-interface', 'key4')"; - assertEquals( - "gremlin query should be " + expected, - expected, - query.getQueryBuilder().getQuery()); - assertEquals( - "parent gremlin query should be equal the query for vlan", - expectedParent, - query.getQueryBuilder().getParentQuery().getQuery()); - assertEquals( - "result type should be l3-interface-ipv4-address-list", - "l3-interface-ipv4-address-list", - query.getResultType()); - - } - - /** - * Short circuit. - * - * @throws JAXBException the JAXB exception - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - */ - @Test - public void shortCircuit() throws JAXBException, UnsupportedEncodingException, AAIException { - String content = - "{" - + "\"related-to\" : \"cvlan-tag\"," - + "\"related-link\" : \"http://mock-system-name.com:8443/aai/v6/network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags/cvlan-tag/655\"," - + "\"relationship-data\" : [{" - + "\"relationship-key\" : \"vce.vnf-id\"," - + "\"relationship-value\" : \"key1\"" - + "}, {" - + "\"relationship-key\" : \"port-group.interface-id\"," - + "\"relationship-value\" : \"key2\"" - + "},{" - + "\"relationship-key\" : \"cvlan-tag.cvlan-tag\"," - + "\"relationship-value\" : \"655\"" - + "}]" - + "}"; - - Unmarshaller unmarshaller = context.createUnmarshaller(); - unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); - unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); - unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); - Object obj = context.newDynamicEntity("Relationship"); - - DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); - - Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity); - QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); - String expected = - ".has('vnf-id', 'key1').has('aai-node-type', 'vce')" - + ".in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'port-group')" - + ".has('interface-id', 'key2').in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'cvlan-tag')" - + ".has('cvlan-tag', 655)"; - String expectedParent = - ".has('vnf-id', 'key1').has('aai-node-type', 'vce')" - + ".in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'port-group')" - + ".has('interface-id', 'key2')"; - assertEquals( - "gremlin query should be " + expected, - expected, - query.getQueryBuilder().getQuery()); - assertEquals( - "parent gremlin query should be equal the query for port group", - expectedParent, - query.getQueryBuilder().getParentQuery().getQuery()); - assertEquals( - "result type should be cvlan-tag", - "cvlan-tag", - query.getResultType()); - - } - - @Test - public void shorterCircuit() throws JAXBException, UnsupportedEncodingException, AAIException { - String content = - "{" - + "\"related-to\" : \"cvlan-tag\"," - + "\"related-link\" : \"file:///network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags/cvlan-tag/655\"" - + "}"; - - Unmarshaller unmarshaller = context.createUnmarshaller(); - unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); - unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); - unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); - Object obj = context.newDynamicEntity("Relationship"); - - DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); - - Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity); - QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); - String expected = - ".has('vnf-id', 'key1').has('aai-node-type', 'vce')" - + ".in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'port-group')" - + ".has('interface-id', 'key2').in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'cvlan-tag')" - + ".has('cvlan-tag', 655)"; - String expectedParent = - ".has('vnf-id', 'key1').has('aai-node-type', 'vce')" - + ".in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'port-group')" - + ".has('interface-id', 'key2')"; - assertEquals( - "gremlin query should be " + expected, - expected, - query.getQueryBuilder().getQuery()); - assertEquals( - "parent gremlin query should be equal the query for port group", - expectedParent, - query.getQueryBuilder().getParentQuery().getQuery()); - assertEquals( - "result type should be cvlan-tag", - "cvlan-tag", - query.getResultType()); - - } - - /** - * Double key. - * - * @throws JAXBException the JAXB exception - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - */ - @Test - public void doubleKey() throws JAXBException, UnsupportedEncodingException, AAIException { - String content = - "{" - + "\"related-to\" : \"ctag-pool\"," - + "\"relationship-data\" : [{" - + "\"relationship-key\" : \"complex.physical-location-id\"," - + "\"relationship-value\" : \"key1\"" - + " }, { " - + "\"relationship-key\" : \"ctag-pool.target-pe\"," - + " \"relationship-value\" : \"key2\"" - + " },{" - + "\"relationship-key\" : \"ctag-pool.availability-zone-name\"," - + "\"relationship-value\" : \"key3\"" - + "}]" - + "}"; - - - Unmarshaller unmarshaller = context.createUnmarshaller(); - unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); - unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); - unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); - Object obj = context.newDynamicEntity("Relationship"); - - DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); - - Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity); - QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); - - String expected = - ".has('physical-location-id', 'key1').has('aai-node-type', 'complex')" - + ".in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'ctag-pool')" - + ".has('target-pe', 'key2')" - + ".has('availability-zone-name', 'key3')"; - String expectedParent = - ".has('physical-location-id', 'key1').has('aai-node-type', 'complex')"; - - assertEquals( - "gremlin query should be " + expected, - expected, - query.getQueryBuilder().getQuery()); - assertEquals( - "parent gremlin query should be equal the query for port group", - expectedParent, - query.getQueryBuilder().getParentQuery().getQuery()); - assertEquals( - "result type should be ctag-pool", - "ctag-pool", - query.getResultType()); - - } - - /** - * Abstract type. - * - * @throws JAXBException the JAXB exception - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - */ - @Test - public void abstractType() throws JAXBException, UnsupportedEncodingException, AAIException { - String content = - "{" - + "\"related-to\" : \"vnf\"," - + "\"relationship-data\" : [{" - + "\"relationship-key\" : \"vnf.vnf-id\"," - + "\"relationship-value\" : \"key1\"" - + " }]" - + "}"; - - - Unmarshaller unmarshaller = context.createUnmarshaller(); - unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); - unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); - unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); - Object obj = context.newDynamicEntity("Relationship"); - - DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); - - Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity); - QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); - - String expected = - ".has('vnf-id', 'key1')" - + ".has('aai-node-type', P.within('vce','generic-vnf'))"; - - String expectedParent = - ".has('vnf-id', 'key1')" - + ".has('aai-node-type', P.within('vce','generic-vnf'))"; - - assertEquals( - "gremlin query should be " + expected, - expected, - query.getQueryBuilder().getQuery()); - assertEquals( - "parent gremlin query should be equal the query for port group", - expectedParent, - query.getQueryBuilder().getParentQuery().getQuery()); - assertEquals( - "result type should be vnf", - "vnf", - query.getResultType()); - - } - - /** - * Invalid node name. - * - * @throws JAXBException the JAXB exception - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - */ - @Test - public void invalidNodeName() throws JAXBException, UnsupportedEncodingException, AAIException { - String content = - "{" - + "\"related-to\" : \"l3-interface-ipv4-address-list\"," - + "\"relationship-data\" : [{" - + "\"relationship-key\" : \"generic-vnf.vnf-id\"," - + "\"relationship-value\" : \"key1\"" - + "},{" - + "\"relationship-key\" : \"lag-interface.interface-name\"," - + "\"relationship-value\" : \"key2\"" - + "},{" - + "\"relationship-key\" : \"l-infeaterface.interface-name\"," - + "\"relationship-value\" : \"key3\"" - + "},{" - + "\"relationship-key\" : \"vlan.vlan-interface\"," - + "\"relationship-value\" : \"key4\"" - + "},{" - + "\"relationship-key\" : \"l3-interface-ipv4-address-list.l3-interface-ipv4-address\"," - + "\"relationship-value\" : \"key5\"" - + "}]" - + "}"; - thrown.expect(AAIException.class); - thrown.expectMessage(containsString("invalid object name")); - - Unmarshaller unmarshaller = context.createUnmarshaller(); - unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); - unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); - unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); - Object obj = context.newDynamicEntity("Relationship"); - - DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); - - Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity); - dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); - - } - - /** - * Invalid property name. - * - * @throws JAXBException the JAXB exception - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - */ - @Test - public void invalidPropertyName() throws JAXBException, UnsupportedEncodingException, AAIException { - String content = - "{" - + "\"related-to\" : \"l3-interface-ipv4-address-list\"," - + "\"relationship-data\" : [{" - + "\"relationship-key\" : \"generic-vnf.vnf-id\"," - + "\"relationship-value\" : \"key1\"" - + "},{" - + "\"relationship-key\" : \"lag-interface.intfdaferface-name\"," - + "\"relationship-value\" : \"key2\"" - + "},{" - + "\"relationship-key\" : \"l-interface.interface-name\"," - + "\"relationship-value\" : \"key3\"" - + "},{" - + "\"relationship-key\" : \"vlan.vlan-interface\"," - + "\"relationship-value\" : \"key4\"" - + "},{" - + "\"relationship-key\" : \"l3-interface-ipv4-address-list.l3-interface-ipv4-address\"," - + "\"relationship-value\" : \"key5\"" - + "}]" - + "}"; - thrown.expect(AAIException.class); - thrown.expectMessage(containsString("invalid property name")); - - Unmarshaller unmarshaller = context.createUnmarshaller(); - unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); - unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); - unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); - Object obj = context.newDynamicEntity("Relationship"); - - DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); - - Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity); - dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); - - } -} diff --git a/aai-core/src/test/java/org/openecomp/aai/parsers/query/RelationshipQueryTest.java b/aai-core/src/test/java/org/openecomp/aai/parsers/query/RelationshipQueryTest.java deleted file mode 100644 index 94fe0c59..00000000 --- a/aai-core/src/test/java/org/openecomp/aai/parsers/query/RelationshipQueryTest.java +++ /dev/null @@ -1,271 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.parsers.query; - -import org.eclipse.persistence.dynamic.DynamicEntity; -import org.eclipse.persistence.jaxb.UnmarshallerProperties; -import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext; -import org.junit.Ignore; -import org.junit.Test; -import org.openecomp.aai.AAISetup; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.*; -import org.openecomp.aai.serialization.engines.QueryStyle; -import org.openecomp.aai.serialization.engines.TitanDBEngine; -import org.openecomp.aai.serialization.engines.TransactionalGraphEngine; - -import javax.xml.bind.JAXBException; -import javax.xml.bind.Unmarshaller; -import javax.xml.transform.stream.StreamSource; -import java.io.StringReader; -import java.io.UnsupportedEncodingException; - -import static org.junit.Assert.assertEquals; - -@Ignore -public class RelationshipQueryTest extends AAISetup { - - private ModelInjestor injestor = ModelInjestor.getInstance(); - - private TransactionalGraphEngine dbEngine = - new TitanDBEngine(QueryStyle.GREMLIN_TRAVERSAL, - LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v8), - false); - private final Version version = Version.v8; - private DynamicJAXBContext context = injestor.getContextForVersion(version); - - /** - * Parent query. - * - * @throws JAXBException the JAXB exception - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - */ - @Test - public void parentQuery() throws JAXBException, UnsupportedEncodingException, AAIException { - - String content = - "{" - + "\"related-to\" : \"pserver\"," - + "\"relationship-data\" : [{" - + "\"relationship-key\" : \"pserver.hostname\"," - + "\"relationship-value\" : \"key1\"" - + "}]" - + "}"; - - Unmarshaller unmarshaller = context.createUnmarshaller(); - unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); - unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); - unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); - Object obj = context.newDynamicEntity("Relationship"); - - DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); - - Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity); - QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); - - String expected = - ".has('hostname', 'key1').has('aai-node-type', 'pserver')"; - assertEquals( - "gremlin query should be " + expected, - expected, - query.getQueryBuilder().getQuery()); - assertEquals( - "parent gremlin query should be equal to normal query", - expected, - query.getQueryBuilder().getParentQuery().getQuery()); - assertEquals( - "result type should be pserver", - "pserver", - query.getResultType()); - - } - - /** - * Child query. - * - * @throws JAXBException the JAXB exception - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - */ - @Ignore - @Test - public void childQuery() throws JAXBException, UnsupportedEncodingException, AAIException { - String content = - "{" - + "\"related-to\" : \"lag-interface\"," - + "\"relationship-data\" : [{" - + "\"relationship-key\" : \"pserver.hostname\"," - + "\"relationship-value\" : \"key1\"" - + "}, {" - + "\"relationship-key\" : \"lag-interface.interface-name\"," - + "\"relationship-value\" : \"key2\"" - + "}]" - + "}"; - - Unmarshaller unmarshaller = context.createUnmarshaller(); - unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); - unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); - unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); - Object obj = context.newDynamicEntity("Relationship"); - - DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); - - Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity); - QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); - String expected = - ".has('hostname', 'key1').has('aai-node-type', 'pserver').out('hasLAGInterface').has('aai-node-type', 'lag-interface')" - + ".has('interface-name', 'key2')"; - String parentExpected = - ".has('hostname', 'key1').has('aai-node-type', 'pserver')"; - assertEquals( - "gremlin query should be for node", - expected, - query.getQueryBuilder().getQuery()); - assertEquals( - "parent gremlin query should be for parent", - parentExpected, - query.getQueryBuilder().getParentQuery().getQuery()); - assertEquals( - "result type should be lag-interface", - "lag-interface", - query.getResultType()); - } - - /** - * Naming exceptions. - * - * @throws JAXBException the JAXB exception - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - */ - @Ignore - @Test - public void namingExceptions() throws JAXBException, UnsupportedEncodingException, AAIException { - String content = - "{" - + "\"related-to\" : \"cvlan-tag\"," - + "\"relationship-data\" : [{" - + "\"relationship-key\" : \"vce.vnf-id\"," - + "\"relationship-value\" : \"key1\"" - + "}, {" - + "\"relationship-key\" : \"port-group.interface-id\"," - + "\"relationship-value\" : \"key2\"" - + "},{" - + "\"relationship-key\" : \"cvlan-tag.cvlan-tag\"," - + "\"relationship-value\" : \"655\"" - + "}]" - + "}"; - - Unmarshaller unmarshaller = context.createUnmarshaller(); - unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); - unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); - unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); - Object obj = context.newDynamicEntity("Relationship"); - - DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); - - Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity); - QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); - String expected = - ".has('vnf-id', 'key1').has('aai-node-type', 'vce').in('org.onap.relationships.inventory.BelongsTo')" - + ".has('aai-node-type', 'port-group').has('interface-id', 'key2').in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'cvlan-tag')" - + ".has('cvlan-tag', 655)"; - String expectedParent = - ".has('vnf-id', 'key1').has('aai-node-type', 'vce').in('org.onap.relationships.inventory.BelongsTo')" - + ".has('aai-node-type', 'port-group').has('interface-id', 'key2')"; - - assertEquals( - "gremlin query should be " + expected, - expected, - query.getQueryBuilder().getQuery()); - assertEquals( - "parent gremlin query should be equal the query for port group", - expectedParent, - query.getQueryBuilder().getParentQuery().getQuery()); - assertEquals( - "result type should be cvlan-tag", - "cvlan-tag", - query.getResultType()); - - } - - /** - * Double key. - * - * @throws JAXBException the JAXB exception - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - */ - @Ignore - @Test - public void doubleKey() throws JAXBException, UnsupportedEncodingException, AAIException { - String content = - "{" - + "\"related-to\" : \"ctag-pool\"," - + "\"relationship-data\" : [{" - + "\"relationship-key\" : \"complex.physical-location-id\"," - + "\"relationship-value\" : \"key1\"" - + " }, { " - + "\"relationship-key\" : \"ctag-pool.target-pe\"," - + " \"relationship-value\" : \"key2\"" - + " },{" - + "\"relationship-key\" : \"ctag-pool.availability-zone-name\"," - + "\"relationship-value\" : \"key3\"" - + "}]" - + "}"; - - - Unmarshaller unmarshaller = context.createUnmarshaller(); - unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); - unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); - unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); - Object obj = context.newDynamicEntity("Relationship"); - - DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); - - Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity); - QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); - - String expected = - ".has('physical-location-id', 'key1').has('aai-node-type', 'complex')" - + ".in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'ctag-pool')" - + ".has('target-pe', 'key2')" - + ".has('availability-zone-name', 'key3')"; - String expectedParent = - ".has('physical-location-id', 'key1').has('aai-node-type', 'complex')"; - - assertEquals( - "gremlin query should be " + expected, - expected, - query.getQueryBuilder().getQuery()); - assertEquals( - "parent gremlin query should be equal the query for port group", - expectedParent, - query.getQueryBuilder().getParentQuery().getQuery()); - assertEquals( - "result type should be ctag-pool", - "ctag-pool", - query.getResultType()); - - } - -} diff --git a/aai-core/src/test/java/org/openecomp/aai/parsers/query/UniqueRelationshipQueryTest.java b/aai-core/src/test/java/org/openecomp/aai/parsers/query/UniqueRelationshipQueryTest.java deleted file mode 100644 index 870bbd36..00000000 --- a/aai-core/src/test/java/org/openecomp/aai/parsers/query/UniqueRelationshipQueryTest.java +++ /dev/null @@ -1,296 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.parsers.query; - -import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; -import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__; -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.eclipse.persistence.dynamic.DynamicEntity; -import org.eclipse.persistence.jaxb.UnmarshallerProperties; -import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.openecomp.aai.AAISetup; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.*; -import org.openecomp.aai.serialization.engines.QueryStyle; -import org.openecomp.aai.serialization.engines.TitanDBEngine; -import org.openecomp.aai.serialization.engines.TransactionalGraphEngine; - -import javax.xml.bind.JAXBException; -import javax.xml.bind.Unmarshaller; -import javax.xml.transform.stream.StreamSource; -import java.io.StringReader; -import java.io.UnsupportedEncodingException; - -import static org.junit.Assert.assertEquals; - -@Ignore -public class UniqueRelationshipQueryTest extends AAISetup { - - private ModelInjestor injestor = ModelInjestor.getInstance(); - private TransactionalGraphEngine dbEngine = - new TitanDBEngine(QueryStyle.GREMLIN_UNIQUE, - LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v8), - false); - private final Version version = Version.v8; - private DynamicJAXBContext context = injestor.getContextForVersion(version); - private Unmarshaller unmarshaller = null; - - /** - * Setup. - * - * @throws JAXBException the JAXB exception - */ - @Before - public void setup() throws JAXBException { - unmarshaller = context.createUnmarshaller(); - unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); - unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); - unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); - } - - /** - * Parent query. - * - * @throws JAXBException the JAXB exception - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - */ - @Test - public void parentQuery() throws JAXBException, UnsupportedEncodingException, AAIException { - - String content = - "{" - + "\"related-to\" : \"pserver\"," - + "\"relationship-data\" : [{" - + "\"relationship-key\" : \"pserver.hostname\"," - + "\"relationship-value\" : \"key1\"" - + "}]" - + "}"; - - Object obj = context.newDynamicEntity("Relationship"); - - DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); - - Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity); - QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); - String key = "pserver/key1"; - GraphTraversal expected = - __.start().has("aai-unique-key", key); - String resultType = "pserver"; - String containerType = ""; - - testSet(query, expected, expected, resultType, containerType); - - } - - /** - * Child query. - * - * @throws JAXBException the JAXB exception - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - */ - @Test - public void childQuery() throws JAXBException, UnsupportedEncodingException, AAIException { - String content = - "{" - + "\"related-to\" : \"lag-interface\"," - + "\"relationship-data\" : [{" - + "\"relationship-key\" : \"pserver.hostname\"," - + "\"relationship-value\" : \"key1\"" - + "}, {" - + "\"relationship-key\" : \"lag-interface.interface-name\"," - + "\"relationship-value\" : \"key2\"" - + "}]" - + "}"; - - Object obj = context.newDynamicEntity("Relationship"); - - DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); - - Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity); - QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); - - String key = "pserver/key1/lag-interface/key2"; - GraphTraversal expected = - __.start().has("aai-unique-key", key); - GraphTraversal parentExpected = - __.start().has("aai-unique-key", "pserver/key1"); - String resultType = "lag-interface"; - String containerType = ""; - - testSet(query, expected, parentExpected, resultType, containerType); - } - - /** - * Naming exceptions. - * - * @throws JAXBException the JAXB exception - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - */ - @Test - public void namingExceptions() throws JAXBException, UnsupportedEncodingException, AAIException { - String content = - "{" - + "\"related-to\" : \"cvlan-tag\"," - + "\"relationship-data\" : [{" - + "\"relationship-key\" : \"vce.vnf-id\"," - + "\"relationship-value\" : \"key1\"" - + "}, {" - + "\"relationship-key\" : \"port-group.interface-id\"," - + "\"relationship-value\" : \"key2\"" - + "},{" - + "\"relationship-key\" : \"cvlan-tag.cvlan-tag\"," - + "\"relationship-value\" : \"655\"" - + "}]" - + "}"; - - Object obj = context.newDynamicEntity("Relationship"); - - DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); - - Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity); - QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); - String key = "vce/key1/port-group/key2/cvlan-tag/655"; - GraphTraversal expected = - __.start().has("aai-unique-key", key); - GraphTraversal parentExpected = - __.start().has("aai-unique-key", "vce/key1/port-group/key2"); - String resultType = "cvlan-tag"; - String containerType = ""; - - testSet(query, expected, parentExpected, resultType, containerType); - - } - - /** - * Double key. - * - * @throws JAXBException the JAXB exception - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - */ - @Test - public void doubleKey() throws JAXBException, UnsupportedEncodingException, AAIException { - String content = - "{" - + "\"related-to\" : \"service-capability\"," - + "\"relationship-data\" : [{" - + "\"relationship-key\" : \"service-capability.service-type\"," - + "\"relationship-value\" : \"key1\"" - + " }, { " - + "\"relationship-key\" : \"service-capability.vnf-type\"," - + " \"relationship-value\" : \"key2\"" - + " }]" - + "}"; - - Object obj = context.newDynamicEntity("Relationship"); - - DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); - - Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity); - QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); - - String key = "service-capability/key1/key2"; - GraphTraversal expected = - __.start().has("aai-unique-key", key); - GraphTraversal parentExpected = - __.start().has("aai-unique-key", "service-capability/key1/key2"); - String resultType = "service-capability"; - String containerType = ""; - - testSet(query, expected, parentExpected, resultType, containerType); - - } - - /** - * Short circuit. - * - * @throws JAXBException the JAXB exception - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - */ - @Test - public void shortCircuit() throws JAXBException, UnsupportedEncodingException, AAIException { - String content = - "{" - + "\"related-to\" : \"cvlan-tag\"," - + "\"related-link\" : \"http://mock-system-name.com:8443/aai/v6/network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags/cvlan-tag/655\"," - + "\"relationship-data\" : [{" - + "\"relationship-key\" : \"vce.hostname\"," - + "\"relationship-value\" : \"key1\"" - + "}, {" - + "\"relationship-key\" : \"port-group.interface-name\"," - + "\"relationship-value\" : \"key2\"" - + "},{" - + "\"relationship-key\" : \"cvlan-tag.-name\"," - + "\"relationship-value\" : \"655\"" - + "}]" - + "}"; - - Object obj = context.newDynamicEntity("Relationship"); - - DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); - - Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity); - QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); - String key = "vce/key1/port-group/key2/cvlan-tag/655"; - GraphTraversal expected = __.start().has("aai-unique-key", key); - GraphTraversal parentExpected = __.start().has("aai-unique-key", "vce/key1/port-group/key2"); - String resultType = "cvlan-tag"; - String containerType = ""; - - testSet(query, expected, parentExpected, resultType, containerType); - - } - - /** - * Test set. - * - * @param query the query - * @param expected the expected - * @param parentExpected the parent expected - * @param resultType the result type - * @param containerType the container type - */ - public void testSet(QueryParser query, GraphTraversal expected, GraphTraversal parentExpected, String resultType, String containerType) { - assertEquals( - "gremlin query should be " + expected, - expected, - query.getQueryBuilder().getQuery()); - assertEquals( - "parent gremlin query should be " + parentExpected, - parentExpected, - query.getParentQueryBuilder().getParentQuery()); - assertEquals( - "result type should be " + resultType, - resultType, - query.getResultType()); - assertEquals( - "container type should be " + containerType, - containerType, - query.getContainerType()); - } -} diff --git a/aai-core/src/test/java/org/openecomp/aai/parsers/query/UniqueURIQueryTest.java b/aai-core/src/test/java/org/openecomp/aai/parsers/query/UniqueURIQueryTest.java deleted file mode 100644 index e1be7f25..00000000 --- a/aai-core/src/test/java/org/openecomp/aai/parsers/query/UniqueURIQueryTest.java +++ /dev/null @@ -1,194 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.parsers.query; - -import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; -import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__; -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext; -import org.junit.Ignore; -import org.junit.Test; -import org.openecomp.aai.AAISetup; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.LoaderFactory; -import org.openecomp.aai.introspection.ModelInjestor; -import org.openecomp.aai.introspection.ModelType; -import org.openecomp.aai.introspection.Version; -import org.openecomp.aai.serialization.engines.QueryStyle; -import org.openecomp.aai.serialization.engines.TitanDBEngine; -import org.openecomp.aai.serialization.engines.TransactionalGraphEngine; - -import javax.ws.rs.core.UriBuilder; -import java.io.UnsupportedEncodingException; -import java.net.URI; - -import static org.junit.Assert.assertEquals; - -@Ignore -public class UniqueURIQueryTest extends AAISetup { - - private ModelInjestor injestor = ModelInjestor.getInstance(); - private TransactionalGraphEngine dbEngine = - new TitanDBEngine(QueryStyle.GREMLIN_UNIQUE, - LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v8), - false); - private final Version version = Version.v8; - private DynamicJAXBContext context = injestor.getContextForVersion(version); - - /** - * Parent query. - * - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - */ - @Test - public void parentQuery() throws UnsupportedEncodingException, AAIException { - URI uri = UriBuilder.fromPath("cloud-infrastructure/complexes/complex/key1").build(); - String key = "complex/key1"; - QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); - GraphTraversal expected = __.start().has("aai-unique-key", key); - String parentResultType = ""; - String resultType = "complex"; - String containerType = ""; - - testSet(query, expected, expected, parentResultType, resultType, containerType); - - } - - /** - * Parent plural query. - * - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - */ - @Test - public void parentPluralQuery() throws UnsupportedEncodingException, AAIException { - URI uri = UriBuilder.fromPath("cloud-infrastructure/complexes").build(); - QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); - GraphTraversal expected = __.start().has("aai-node-type", "complex"); - String parentResultType = ""; - String resultType = "complex"; - String containerType = "complexes"; - - testSet(query, expected, expected, parentResultType, resultType, containerType); - - } - - /** - * Child query. - * - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - */ - @Test - public void childQuery() throws UnsupportedEncodingException, AAIException { - URI uri = UriBuilder.fromPath("cloud-infrastructure/complexes/complex/key1/ctag-pools/ctag-pool/key2/key3").build(); - QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); - String parentKey = "complex/key1"; - String key = parentKey + "/ctag-pool/key2/key3"; - GraphTraversal expected = __.start().has("aai-unique-key", key); - GraphTraversal parentExpected = __.start().has("aai-unique-key", parentKey); - String parentResultType = "complex"; - String resultType = "ctag-pool"; - String containerType = ""; - - testSet(query, expected, parentExpected, parentResultType, resultType, containerType); - - } - - /** - * Naming exceptions. - * - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - */ - @Test - public void namingExceptions() throws UnsupportedEncodingException, AAIException { - URI uri = UriBuilder.fromPath("network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags/cvlan-tag/655").build(); - QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); - String parentKey = "vce/key1/port-group/key2"; - String key = parentKey + "/cvlan-tag/655"; - GraphTraversal expected = __.start().has("aai-unique-key", key); - GraphTraversal parentExpected = __.start().has("aai-unique-key", parentKey); - String parentResultType = "port-group"; - String resultType = "cvlan-tag"; - String containerType = ""; - - testSet(query, expected, parentExpected, parentResultType, resultType, containerType); - - } - - /** - * Gets the all. - * - * @return the all - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - */ - @Test - public void getAll() throws UnsupportedEncodingException, AAIException { - String parentURI = "network/vces/vce/key1/port-groups/port-group/key2"; - String parentKey = "vce/key1/port-group/key2"; - URI uri = UriBuilder.fromPath(parentURI + "/cvlan-tags").build(); - QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); - GraphTraversal expected = __.start().has("aai-unique-key", parentKey).out("hasCTag").has("aai-node-type", "cvlan-tag"); - GraphTraversal parentExpected = __.start().has("aai-unique-key",parentKey); - String parentResultType = "port-group"; - String resultType = "cvlan-tag"; - String containerType = "cvlan-tags"; - - testSet(query, expected, parentExpected, parentResultType, resultType, containerType); - - } - - /** - * Test set. - * - * @param query the query - * @param expected the expected - * @param parentExpected the parent expected - * @param parentResultType the parent result type - * @param resultType the result type - * @param containerType the container type - */ - public void testSet(QueryParser query, GraphTraversal expected, GraphTraversal parentExpected, String parentResultType, String resultType, String containerType) { - assertEquals( - "gremlin query should be " + expected, - expected, - query.getQueryBuilder().getQuery()); - assertEquals( - "parent gremlin query should be " + parentExpected, - parentExpected, - query.getQueryBuilder().getParentQuery().getQuery()); - assertEquals( - "parent result type should be " + parentResultType, - parentResultType, - query.getParentResultType()); - assertEquals( - "result type should be " + resultType, - resultType, - query.getResultType()); - assertEquals( - "container type should be " + containerType, - containerType, - query.getContainerType()); - } -} diff --git a/aai-core/src/test/java/org/openecomp/aai/parsers/relationship/RelationshipToURITest.java b/aai-core/src/test/java/org/openecomp/aai/parsers/relationship/RelationshipToURITest.java deleted file mode 100644 index 092d5c66..00000000 --- a/aai-core/src/test/java/org/openecomp/aai/parsers/relationship/RelationshipToURITest.java +++ /dev/null @@ -1,224 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.parsers.relationship; - -import org.apache.commons.io.IOUtils; -import org.junit.Ignore; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.openecomp.aai.AAISetup; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.*; -import org.openecomp.aai.parsers.exceptions.AAIIdentityMapParseException; -import org.openecomp.aai.parsers.exceptions.AmbiguousMapAAIException; - -import java.io.FileInputStream; -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; - -import static org.hamcrest.Matchers.hasProperty; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; - -public class RelationshipToURITest extends AAISetup { - - private final ModelType modelType = ModelType.MOXY; - private final Version version10 = Version.v10; - private final Version version9 = Version.v9; - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Test - public void onlyLink() throws AAIException, URISyntaxException, IOException { - Loader loader = LoaderFactory.createLoaderForVersion(modelType, version10); - Introspector obj = loader.unmarshal("relationship", this.getJsonString("only-related-link.json")); - URI expected = new URI("/aai/v10/network/test-objects/test-object/key1"); - - RelationshipToURI parse = new RelationshipToURI(loader, obj); - - URI uri = parse.getUri(); - - assertEquals("related-link is equal", expected.getPath(), uri.getPath()); - } - - @Test - public void onlyData() throws AAIException, URISyntaxException, IOException { - Loader loader = LoaderFactory.createLoaderForVersion(modelType, version10); - Introspector obj = loader.unmarshal("relationship", this.getJsonString("only-relationship-data.json")); - URI expected = new URI("/network/test-objects/test-object/key1"); - - RelationshipToURI parse = new RelationshipToURI(loader, obj); - - URI uri = parse.getUri(); - - assertEquals("related-link is equal", expected, uri); - } - - @Test - public void failV10() throws AAIException, URISyntaxException, IOException { - Loader loader = LoaderFactory.createLoaderForVersion(modelType, version10); - Introspector obj = loader.unmarshal("relationship", this.getJsonString("both-failv10-successv9.json")); - URI expected = new URI("/aai/v10/network/test-objects/test-object/key1"); - - thrown.expect(AAIIdentityMapParseException.class); - thrown.expect(hasProperty("code", is("AAI_3000"))); - RelationshipToURI parse = new RelationshipToURI(loader, obj); - URI uri = parse.getUri(); - - } - - @Test - public void successV9() throws AAIException, URISyntaxException, IOException { - Loader loader = LoaderFactory.createLoaderForVersion(modelType, version9); - Introspector obj = loader.unmarshal("relationship", this.getJsonString("both-failv10-successv9.json")); - URI expected = new URI("/network/test-objects/test-object/key2"); - - RelationshipToURI parse = new RelationshipToURI(loader, obj); - URI uri = parse.getUri(); - - assertEquals("related-link is equal", expected, uri); - - - } - - @Test - public void failV9() throws AAIException, URISyntaxException, IOException { - Loader loader = LoaderFactory.createLoaderForVersion(modelType, version9); - Introspector obj = loader.unmarshal("relationship", this.getJsonString("both-successv10-failv9.json")); - URI expected = new URI("/network/test-objects/test-object/key1"); - - thrown.expect(AAIIdentityMapParseException.class); - thrown.expect(hasProperty("code", is("AAI_3000"))); - RelationshipToURI parse = new RelationshipToURI(loader, obj); - - - URI uri = parse.getUri(); - - } - - @Test - public void failNothingToParse() throws AAIException, URISyntaxException, IOException { - Loader loader = LoaderFactory.createLoaderForVersion(modelType, version10); - Introspector obj = loader.unmarshal("relationship", this.getJsonString("nothing-to-parse.json")); - URI expected = new URI("/aai/v10/network/test-objects/test-object/key1"); - - thrown.expect(AAIIdentityMapParseException.class); - thrown.expect(hasProperty("code", is("AAI_3000"))); - RelationshipToURI parse = new RelationshipToURI(loader, obj); - - URI uri = parse.getUri(); - - } - - @Test - public void successV10() throws AAIException, URISyntaxException, IOException { - Loader loader = LoaderFactory.createLoaderForVersion(modelType, version10); - Introspector obj = loader.unmarshal("relationship", this.getJsonString("both-successv10-failv9.json")); - URI expected = new URI("/aai/v10/network/test-objects/test-object/key1"); - - RelationshipToURI parse = new RelationshipToURI(loader, obj); - - - URI uri = parse.getUri(); - - assertEquals("related-link is equal", expected, uri); - - - } - - @Test - public void ambiguousRelationship() throws AAIException, URISyntaxException, IOException { - Loader loader = LoaderFactory.createLoaderForVersion(modelType, version10); - Introspector obj = loader.unmarshal("relationship", this.getJsonString("ambiguous-relationship.json")); - URI expected = new URI("/aai/v10/network/test-objects/test-object/key1"); - - thrown.expect(AmbiguousMapAAIException.class); - thrown.expect(hasProperty("code", is("AAI_6146"))); - - RelationshipToURI parse = new RelationshipToURI(loader, obj); - - URI uri = parse.getUri(); - - assertEquals("related-link is equal", expected, uri); - - - } - - @Ignore - @Test - public void moreItemsThanRequired() throws AAIException, URISyntaxException, IOException { - Loader loader = LoaderFactory.createLoaderForVersion(modelType, version10); - Introspector obj = loader.unmarshal("relationship", this.getJsonString("too-many-items-relationship.json")); - URI expected = new URI("/network/generic-vnfs/generic-vnf/key1/l-interfaces/l-interface/key2"); - - RelationshipToURI parse = new RelationshipToURI(loader, obj); - - URI uri = parse.getUri(); - - assertEquals("related-link is equal", expected.toString(), uri.toString()); - - } - - @Test - public void twoTopLevelNodes() throws AAIException, URISyntaxException, IOException { - Loader loader = LoaderFactory.createLoaderForVersion(modelType, version10); - Introspector obj = loader.unmarshal("relationship", this.getJsonString("two-top-level-relationship.json")); - URI expected = new URI("/network/generic-vnfs/generic-vnf/key1/l-interfaces/l-interface/key2"); - - thrown.expect(AmbiguousMapAAIException.class); - thrown.expect(hasProperty("code", is("AAI_6146"))); - - RelationshipToURI parse = new RelationshipToURI(loader, obj); - - URI uri = parse.getUri(); - - assertEquals("related-link is equal", expected, uri); - - } - - @Test - public void topLevelWithTwoKeys() throws AAIException, URISyntaxException, IOException { - Loader loader = LoaderFactory.createLoaderForVersion(modelType, version10); - Introspector obj = loader.unmarshal("relationship", this.getJsonString("top-level-two-keys-relationship.json")); - URI expected = new URI("/cloud-infrastructure/cloud-regions/cloud-region/key1/key2/availability-zones/availability-zone/key3"); - - RelationshipToURI parse = new RelationshipToURI(loader, obj); - - URI uri = parse.getUri(); - - assertEquals("related-link is equal", expected.toString(), uri.toString()); - - } - - - private String getJsonString(String filename) throws IOException { - - - FileInputStream is = new FileInputStream("src/test/resources/bundleconfig-local/etc/relationship/" + filename); - String s = IOUtils.toString(is, "UTF-8"); - IOUtils.closeQuietly(is); - - return s; - } -} diff --git a/aai-core/src/test/java/org/openecomp/aai/parsers/uri/URIParserTest.java b/aai-core/src/test/java/org/openecomp/aai/parsers/uri/URIParserTest.java deleted file mode 100644 index da863c1e..00000000 --- a/aai-core/src/test/java/org/openecomp/aai/parsers/uri/URIParserTest.java +++ /dev/null @@ -1,101 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.parsers.uri; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.openecomp.aai.AAISetup; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.introspection.LoaderFactory; -import org.openecomp.aai.introspection.ModelType; -import org.openecomp.aai.introspection.Version; - -import javax.ws.rs.core.UriBuilder; -import javax.xml.bind.JAXBException; -import java.io.UnsupportedEncodingException; -import java.net.URI; - -import static org.hamcrest.Matchers.hasProperty; -import static org.hamcrest.Matchers.is; - -public class URIParserTest extends AAISetup { - - private Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v8); - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - /** - * Invalid path. - * - * @throws JAXBException the JAXB exception - * @throws AAIException the AAI exception - * @throws IllegalArgumentException the illegal argument exception - * @throws UnsupportedEncodingException the unsupported encoding exception - */ - @Test - public void invalidPath() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException { - URI uri = UriBuilder.fromPath("/aai/" + loader.getVersion() + "/network/tenants/tenant/key1/vservers/vserver/key2/l-interfaces/l-interface/key3").build(); - - thrown.expect(AAIException.class); - thrown.expect(hasProperty("code", is("AAI_3000"))); - - new URIToDBKey(loader, uri); - } - - /** - * Invalid path no name space. - * - * @throws JAXBException the JAXB exception - * @throws AAIException the AAI exception - * @throws IllegalArgumentException the illegal argument exception - * @throws UnsupportedEncodingException the unsupported encoding exception - */ - @Test - public void invalidPathNoNameSpace() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException { - URI uri = UriBuilder.fromPath("/aai/" + loader.getVersion() + "/tenants/tenant/key1/vservers/vserver/key2/l-interfaces/l-interface/key3").build(); - - thrown.expect(AAIException.class); - thrown.expect(hasProperty("code", is("AAI_3000"))); - - new URIToDBKey(loader, uri); - } - - /** - * Invalid path partial. - * - * @throws JAXBException the JAXB exception - * @throws AAIException the AAI exception - * @throws IllegalArgumentException the illegal argument exception - * @throws UnsupportedEncodingException the unsupported encoding exception - */ - @Test - public void invalidPathPartial() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException { - URI uri = UriBuilder.fromPath("vservers/vserver/key2/l-interfaces/l-interface/key3").build(); - - thrown.expect(AAIException.class); - thrown.expect(hasProperty("code", is("AAI_3000"))); - - new URIToDBKey(loader, uri); - } -} diff --git a/aai-core/src/test/java/org/openecomp/aai/parsers/uri/URIToDBKeyTest.java b/aai-core/src/test/java/org/openecomp/aai/parsers/uri/URIToDBKeyTest.java deleted file mode 100644 index 626e97ab..00000000 --- a/aai-core/src/test/java/org/openecomp/aai/parsers/uri/URIToDBKeyTest.java +++ /dev/null @@ -1,185 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.parsers.uri; - -import org.junit.Ignore; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.openecomp.aai.AAISetup; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.parsers.exceptions.DoesNotStartWithValidNamespaceException; -import org.openecomp.aai.db.props.AAIProperties; -import org.openecomp.aai.introspection.*; -import org.powermock.core.classloader.annotations.PrepareForTest; - -import javax.ws.rs.core.UriBuilder; -import javax.xml.bind.JAXBException; -import java.io.UnsupportedEncodingException; -import java.net.URI; - -import static org.hamcrest.Matchers.hasProperty; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; - - - -@PrepareForTest(ModelInjestor.class) -public class URIToDBKeyTest extends AAISetup { - - private Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, AAIProperties.LATEST); - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - /** - * Uri. - * - * @throws JAXBException the JAXB exception - * @throws AAIException the AAI exception - * @throws IllegalArgumentException the illegal argument exception - * @throws UnsupportedEncodingException the unsupported encoding exception - */ - @Test - public void uri() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException { - URI uri = UriBuilder.fromPath("/aai/" + loader.getVersion() + "/cloud-infrastructure/cloud-regions/cloud-region/cloudOwner-key/cloudRegion-key/tenants/tenant/tenantId-key/vservers/vserver/vserverId-key/l-interfaces/l-interface/key3").build(); - URIToDBKey parse = new URIToDBKey(loader, uri); - Object result = parse.getResult(); - - String expected = "cloud-region/tenant/vserver/l-interface"; - - assertEquals("blah", expected, result); - - } - - /** - * Uri no version. - * - * @throws JAXBException the JAXB exception - * @throws AAIException the AAI exception - * @throws IllegalArgumentException the illegal argument exception - * @throws UnsupportedEncodingException the unsupported encoding exception - */ - @Test - public void uriNoVersion() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException { - URI uri = UriBuilder.fromPath("/cloud-infrastructure/cloud-regions/cloud-region/cloudOwner-key/cloudRegion-key/tenants/tenant/tenantId-key/vservers/vserver/vserverId-key/l-interfaces/l-interface/key3").build(); - URIToDBKey parse = new URIToDBKey(loader, uri); - Object result = parse.getResult(); - - String expected = "cloud-region/tenant/vserver/l-interface"; - - assertEquals("blah", expected, result); - - } - - - /** - * Bad URI. - * - * @throws JAXBException the JAXB exception - * @throws AAIException the AAI exception - * @throws IllegalArgumentException the illegal argument exception - * @throws UnsupportedEncodingException the unsupported encoding exception - */ - @Test - public void badURI() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException { - URI uri = UriBuilder.fromPath("/aai/" + loader.getVersion() + "/cloud-infrastructure/tenants/tenant/key1/vservers/vserver/key2/l-interadsfaces/l-interface/key3").build(); - - thrown.expect(AAIException.class); - thrown.expect(hasProperty("code", is("AAI_3001"))); - - new URIToDBKey(loader, uri); - } - - /** - * NotValid namespace. - * - * @throws JAXBException the JAXB exception - * @throws DoesNotStartWithValidNamespaceException the AAI exception - * @throws IllegalArgumentException the illegal argument exception - * @throws UnsupportedEncodingException the unsupported encoding exception - */ - @Test - public void notValidNamespace() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException { - URI uri = UriBuilder.fromPath("/cloud-region/cloud-regions/cloud-region/cloudOwner-key/cloudRegion-key/tenants/tenant/tenantId-key/vservers/vserver/vserverId-key/l-interfaces/l-interface/key3").build(); - thrown.expect(DoesNotStartWithValidNamespaceException.class); - URIToDBKey parse = new URIToDBKey(loader, uri); - } - - - /** - * No valid tokens. - * - * @throws JAXBException the JAXB exception - * @throws AAIException the AAI exception - * @throws IllegalArgumentException the illegal argument exception - * @throws UnsupportedEncodingException the unsupported encoding exception - */ - @Test - public void noValidTokens() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException { - URI uri = UriBuilder.fromPath("/aai/" + loader.getVersion() + "/cloud/blah/blah").build(); - - thrown.expect(AAIException.class); - thrown.expect(hasProperty("code", is("AAI_3000"))); - - new URIToDBKey(loader, uri); - } - - /** - * Starts with valid namespace. - * - * @throws JAXBException the JAXB exception - * @throws AAIException the AAI exception - * @throws IllegalArgumentException the illegal argument exception - * @throws UnsupportedEncodingException the unsupported encoding exception - */ - @Test - public void startsWithValidNamespace() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException { - URI uri = UriBuilder.fromPath("/aai/" + loader.getVersion() + "/cloud-infrastructure/cloud-regions/cloud-region/cloudOwner-key/cloudRegion-key/tenants/tenant/tenantId-key/vservers/vserver/vserverId-key/l-interfaces/l-interface/key3").build(); - - URIToDBKey parse = new URIToDBKey(loader, uri); - Object result = parse.getResult(); - - String expected = "cloud-region/tenant/vserver/l-interface"; - - assertEquals("blah", expected, result); - } - - /** - * Naming exceptions. - * - * @throws IllegalArgumentException the illegal argument exception - * @throws AAIException the AAI exception - * @throws UnsupportedEncodingException the unsupported encoding exception - */ - @Test - public void namingExceptions() throws IllegalArgumentException, AAIException, UnsupportedEncodingException { - URI uri = UriBuilder.fromPath("network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags/cvlan-tag/655").build(); - URIToDBKey parse = new URIToDBKey(loader, uri); - Object result = parse.getResult(); - - String expected = "vce/port-group/cvlan-tag"; - - assertEquals("blah", expected, result); - - } - -} diff --git a/aai-core/src/test/java/org/openecomp/aai/parsers/uri/URIToExtensionInformationTest.java b/aai-core/src/test/java/org/openecomp/aai/parsers/uri/URIToExtensionInformationTest.java deleted file mode 100644 index 38377f73..00000000 --- a/aai-core/src/test/java/org/openecomp/aai/parsers/uri/URIToExtensionInformationTest.java +++ /dev/null @@ -1,94 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.parsers.uri; - -import org.junit.Ignore; -import org.junit.Test; -import org.openecomp.aai.AAISetup; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.introspection.LoaderFactory; -import org.openecomp.aai.introspection.ModelType; -import org.openecomp.aai.introspection.Version; -import org.openecomp.aai.restcore.HttpMethod; - -import javax.ws.rs.core.UriBuilder; -import javax.xml.bind.JAXBException; -import java.io.UnsupportedEncodingException; -import java.net.URI; - -import static org.junit.Assert.assertEquals; - - -public class URIToExtensionInformationTest extends AAISetup { - - private Loader v8Loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v10); - - /** - * Vservers V 7. - * - * @throws JAXBException the JAXB exception - * @throws AAIException the AAI exception - * @throws IllegalArgumentException the illegal argument exception - * @throws UnsupportedEncodingException the unsupported encoding exception - */ - @Test - public void vserversV8() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException { - URI uri = UriBuilder.fromPath("/aai/" + v8Loader.getVersion() + "/cloud-infrastructure/cloud-regions/cloud-region/att-aic/AAIAIC25/tenants/tenant/key1/vservers/vserver/key2").build(); - URIToExtensionInformation parse = new URIToExtensionInformation(v8Loader, uri); - - String namespace = "cloudInfrastructure"; - String preMethodName = "DynamicAddCloudInfrastructureCloudRegionsCloudRegionTenantsTenantVserversVserverPreProc"; - String postMethodName = "DynamicAddCloudInfrastructureCloudRegionsCloudRegionTenantsTenantVserversVserverPostProc"; - String topLevel = "CloudRegion"; - testSpec(parse, HttpMethod.PUT, namespace, preMethodName, postMethodName, topLevel); - - } - - /** - * Test spec. - * - * @param info the info - * @param httpMethod the http method - * @param namespace the namespace - * @param preMethodName the pre method name - * @param postMethodName the post method name - * @param topLevel the top level - */ - private void testSpec(URIToExtensionInformation info, HttpMethod httpMethod, String namespace, String preMethodName, String postMethodName, String topLevel) { - - - String namespaceResult = info.getNamespace(); - String methodNameResult = info.getMethodName(httpMethod, true); - - assertEquals("namespace", namespace, namespaceResult); - assertEquals("preprocess method name", preMethodName, methodNameResult); - methodNameResult = info.getMethodName(httpMethod, false); - - assertEquals("postprocess method name", postMethodName, methodNameResult); - - String topLevelResult = info.getTopObject(); - - assertEquals("topLevel", topLevel, topLevelResult); - } - - -} diff --git a/aai-core/src/test/java/org/openecomp/aai/parsers/uri/URIToObjectTest.java b/aai-core/src/test/java/org/openecomp/aai/parsers/uri/URIToObjectTest.java deleted file mode 100644 index 9eb013f6..00000000 --- a/aai-core/src/test/java/org/openecomp/aai/parsers/uri/URIToObjectTest.java +++ /dev/null @@ -1,248 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.parsers.uri; - -import org.junit.Ignore; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.openecomp.aai.AAISetup; -import org.openecomp.aai.db.props.AAIProperties; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.*; -import org.openecomp.aai.introspection.exceptions.AAIUnknownObjectException; - -import javax.ws.rs.core.UriBuilder; -import javax.xml.bind.JAXBException; -import java.io.UnsupportedEncodingException; -import java.net.URI; -import java.util.HashMap; - -import static org.hamcrest.Matchers.hasProperty; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; - - - -public class URIToObjectTest extends AAISetup { - - private Version version = Version.v10; - private Version currentVersion = AAIProperties.LATEST; - private Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, version); - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - /** - * Uri. - * - * @throws JAXBException the JAXB exception - * @throws AAIException the AAI exception - * @throws IllegalArgumentException the illegal argument exception - * @throws UnsupportedEncodingException the unsupported encoding exception - */ - @Test - public void uri() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException { - URI uri = UriBuilder.fromPath("/aai/" + loader.getVersion() + "/cloud-infrastructure/cloud-regions/cloud-region/mycloudowner/mycloudregionid/tenants/tenant/key1/vservers/vserver/key2/l-interfaces/l-interface/key3").build(); - URIToObject parse = new URIToObject(loader, uri); - Introspector result = parse.getTopEntity(); - String expected = "{\"cloud-owner\":\"mycloudowner\",\"cloud-region-id\":\"mycloudregionid\",\"tenants\":{\"tenant\":[{\"tenant-id\":\"key1\",\"vservers\":{\"vserver\":[{\"vserver-id\":\"key2\",\"l-interfaces\":{\"l-interface\":[{\"interface-name\":\"key3\"}]}}]}}]}}"; - String topEntity = "cloud-region"; - String entity = "l-interface"; - - testSet(result.marshal(false), parse, expected, topEntity, entity, version); - - } - - /** - * Uri no version. - * - * @throws JAXBException the JAXB exception - * @throws AAIException the AAI exception - * @throws IllegalArgumentException the illegal argument exception - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIUnknownObjectException - */ - @Test - public void uriNoVersion() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException, AAIUnknownObjectException { - URI uri = UriBuilder.fromPath("/cloud-infrastructure/cloud-regions/cloud-region/mycloudowner/mycloudregionid/tenants/tenant/key1/vservers/vserver/key2/l-interfaces/l-interface/key3").build(); - HashMap relatedObjects = new HashMap<>(); - Introspector tenantObj = this.loader.introspectorFromName("tenant"); - tenantObj.setValue("tenant-id", "key1"); - tenantObj.setValue("tenant-name", "name1"); - relatedObjects.put(tenantObj.getObjectId(), tenantObj); - Introspector vserverObj = this.loader.introspectorFromName("vserver"); - vserverObj.setValue("vserver-id", "key2"); - vserverObj.setValue("vserver-name", "name2"); - relatedObjects.put(vserverObj.getObjectId(), vserverObj); - - URIToObject parse = new URIToObject(loader, uri, relatedObjects); - Introspector result = parse.getTopEntity(); - String expected = "{\"cloud-owner\":\"mycloudowner\",\"cloud-region-id\":\"mycloudregionid\",\"tenants\":{\"tenant\":[{\"tenant-id\":\"key1\",\"tenant-name\":\"name1\",\"vservers\":{\"vserver\":[{\"vserver-id\":\"key2\",\"vserver-name\":\"name2\",\"l-interfaces\":{\"l-interface\":[{\"interface-name\":\"key3\"}]}}]}}]}}"; - String topEntity = "cloud-region"; - String entity = "l-interface"; - - testSet(result.marshal(false), parse, expected, topEntity, entity, version); - - - } - - - /** - * Bad URI. - * - * @throws JAXBException the JAXB exception - * @throws AAIException the AAI exception - * @throws IllegalArgumentException the illegal argument exception - * @throws UnsupportedEncodingException the unsupported encoding exception - */ - @Test - public void badURI() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException { - URI uri = UriBuilder.fromPath("/aai/" + loader.getVersion() + "/cloud-infrastructure/cloud-regions/cloud-region/mycloudowner/mycloudregionid/tenants/tenant/key1/vservers/vserver/key2/l-interadsfaces/l-interface/key3").build(); - - thrown.expect(AAIException.class); - thrown.expect(hasProperty("code", is("AAI_3000"))); - - new URIToObject(loader, uri); - } - - /** - * Starts with valid namespace. - * - * @throws JAXBException the JAXB exception - * @throws AAIException the AAI exception - * @throws IllegalArgumentException the illegal argument exception - * @throws UnsupportedEncodingException the unsupported encoding exception - */ - @Test - public void startsWithValidNamespace() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException { - URI uri = UriBuilder.fromPath("/cloud-infrastructure/cloud-regions/cloud-region/mycloudowner/mycloudregionid/tenants/tenant/key1/vservers/vserver/key2/l-interfaces/l-interface/key3").build(); - URIToObject parse = new URIToObject(loader, uri); - Introspector result = parse.getTopEntity(); - String expected = "{\"cloud-owner\":\"mycloudowner\",\"cloud-region-id\":\"mycloudregionid\",\"tenants\":{\"tenant\":[{\"tenant-id\":\"key1\",\"vservers\":{\"vserver\":[{\"vserver-id\":\"key2\",\"l-interfaces\":{\"l-interface\":[{\"interface-name\":\"key3\"}]}}]}}]}}"; - String topEntity = "cloud-region"; - String entity = "l-interface"; - - testSet(result.marshal(false), parse, expected, topEntity, entity, version); - } - - /** - * Single top level. - * - * @throws JAXBException the JAXB exception - * @throws AAIException the AAI exception - * @throws IllegalArgumentException the illegal argument exception - * @throws UnsupportedEncodingException the unsupported encoding exception - */ - @Test - public void singleTopLevel() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException { - URI uri = UriBuilder.fromPath("/network/generic-vnfs/generic-vnf/key1").build(); - URIToObject parse = new URIToObject(loader, uri); - Introspector result = parse.getTopEntity(); - String expected = "{\"vnf-id\":\"key1\"}"; - - String topEntity = "generic-vnf"; - String entity = "generic-vnf"; - - testSet(result.marshal(false), parse, expected, topEntity, entity, version); - - } - - /** - * Naming exceptions. - * - * @throws JAXBException the JAXB exception - * @throws AAIException the AAI exception - * @throws IllegalArgumentException the illegal argument exception - * @throws UnsupportedEncodingException the unsupported encoding exception - */ - @Test - @Ignore - public void namingExceptions() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException { - URI uri = UriBuilder.fromPath("network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags/cvlan-tag/655").build(); - URIToObject parse = new URIToObject(loader, uri); - Introspector result = parse.getTopEntity(); - String expected = "{\"vnf-id\":\"key1\",\"port-groups\":{\"port-group\":[{\"interface-id\":\"key2\",\"cvlan-tags\":{\"cvlan-tag-entry\":[{\"cvlan-tag\":655}]}}]}}"; - String topEntity = "vce"; - String entity = "cvlan-tag"; - - testSet(result.marshal(false), parse, expected, topEntity, entity, version); - - } - - /** - * No list object. - * - * @throws IllegalArgumentException the illegal argument exception - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - */ - @Test - @Ignore - public void noListObject() throws IllegalArgumentException, UnsupportedEncodingException, AAIException { - URI uri = UriBuilder.fromPath("/aai/v6/network/vpls-pes/vpls-pe/0e6189fd-9257-49b9-a3be-d7ba980ccfc9/lag-interfaces/lag-interface/8ae5aa76-d597-4382-b219-04f266fe5e37/l-interfaces/l-interface/9e141d03-467b-437f-b4eb-b3133ec1e205/l3-interface-ipv4-address-list/8f19f0ea-a81f-488e-8d5c-9b7b53696c11").build(); - URIToObject parse = new URIToObject(loader, uri); - Introspector result = parse.getTopEntity(); - String topEntity = "vpls-pe"; - String entity = "l3-interface-ipv4-address-list"; - String expected = "{\"equipment-name\":\"0e6189fd-9257-49b9-a3be-d7ba980ccfc9\",\"lag-interfaces\":{\"lag-interface\":[{\"interface-name\":\"8ae5aa76-d597-4382-b219-04f266fe5e37\",\"l-interfaces\":{\"l-interface\":[{\"interface-name\":\"9e141d03-467b-437f-b4eb-b3133ec1e205\",\"l3-interface-ipv4-address-list\":[{\"l3-interface-ipv4-address\":\"8f19f0ea-a81f-488e-8d5c-9b7b53696c11\"}]}]}}]}}"; - testSet(result.marshal(false), parse, expected, topEntity, entity, version); - - } - - @Test - public void relativePath() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException { - URI uri = UriBuilder.fromPath("./l-interfaces/l-interface/key1").build(); - URIToObject parse = new URIToObject(loader, uri); - Introspector result = parse.getEntity(); - String expected = "{\"interface-name\":\"key1\"}"; - - String topEntity = "l-interface"; - String entity = "l-interface"; - - testSet(result.marshal(false), parse, expected, topEntity, entity, version); - - } - - /** - * Test set. - * - * @param json the json - * @param parse the parse - * @param expected the expected - * @param topEntity the top entity - * @param entity the entity - * @param version the version - */ - public void testSet(String json, URIToObject parse, String expected, String topEntity, String entity, Version version) { - assertEquals("blah", expected, json); - - assertEquals("top entity", topEntity, parse.getTopEntityName()); - - assertEquals("entity", entity, parse.getEntityName()); - - assertEquals("entity object", entity, parse.getEntity().getDbName()); - - assertEquals("parent list object", 1, parse.getParentList().size()); - - assertEquals("object version", version, parse.getObjectVersion()); - } -} diff --git a/aai-core/src/test/java/org/openecomp/aai/parsers/uri/URIToRelationshipObjectTest.java b/aai-core/src/test/java/org/openecomp/aai/parsers/uri/URIToRelationshipObjectTest.java deleted file mode 100644 index ee7b8651..00000000 --- a/aai-core/src/test/java/org/openecomp/aai/parsers/uri/URIToRelationshipObjectTest.java +++ /dev/null @@ -1,150 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.parsers.uri; - -import org.junit.Ignore; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.openecomp.aai.AAISetup; -import org.openecomp.aai.db.props.AAIProperties; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.*; - -import javax.ws.rs.core.UriBuilder; -import javax.xml.bind.JAXBException; -import java.io.UnsupportedEncodingException; -import java.net.MalformedURLException; -import java.net.URI; -import java.net.URISyntaxException; - -import static org.hamcrest.Matchers.hasProperty; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertTrue; - - -public class URIToRelationshipObjectTest extends AAISetup { - - private Version latest = Version.v10; - private Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, latest); - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - /** - * Uri. - * - * @throws JAXBException the JAXB exception - * @throws AAIException the AAI exception - * @throws IllegalArgumentException the illegal argument exception - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws URISyntaxException - * @throws MalformedURLException the malformed URL exception - */ - @Test - public void uri() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException, URISyntaxException { - - URI uri = UriBuilder.fromPath("/aai/" + loader.getVersion() + "/cloud-infrastructure/cloud-regions/cloud-region/mycloudregionowner/mycloudregionid/tenants/tenant/key1/vservers/vserver/key2/l-interfaces/l-interface/key3").build(); - URIToRelationshipObject parse = new URIToRelationshipObject(loader, uri); - Introspector result = parse.getResult(); - String expected = "\\{\"related-to\":\"l-interface\",\"related-link\":\"/aai/" + latest + "/cloud-infrastructure/cloud-regions/cloud-region/mycloudregionowner/mycloudregionid/tenants/tenant/key1/vservers/vserver/key2/l-interfaces/l-interface/key3\",\"relationship-data\":\\[\\{\"relationship-key\":\"cloud-region.cloud-owner\",\"relationship-value\":\"mycloudregionowner\"\\},\\{\"relationship-key\":\"cloud-region.cloud-region-id\",\"relationship-value\":\"mycloudregionid\"\\},\\{\"relationship-key\":\"tenant.tenant-id\",\"relationship-value\":\"key1\"\\},\\{\"relationship-key\":\"vserver.vserver-id\",\"relationship-value\":\"key2\"\\},\\{\"relationship-key\":\"l-interface.interface-name\",\"relationship-value\":\"key3\"\\}\\]\\}"; - assertTrue("blah", result.marshal(false).matches(expected)); - - } - - /** - * Uri no version. - * - * @throws JAXBException the JAXB exception - * @throws AAIException the AAI exception - * @throws IllegalArgumentException the illegal argument exception - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws URISyntaxException - * @throws MalformedURLException the malformed URL exception - */ - @Test - public void uriNoVersion() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException, URISyntaxException { - URI uri = UriBuilder.fromPath("/cloud-infrastructure/cloud-regions/cloud-region/mycloudregionowner/mycloudregionid/tenants/tenant/key1/vservers/vserver/key2/l-interfaces/l-interface/key3").build(); - URIToRelationshipObject parse = new URIToRelationshipObject(loader, uri); - Introspector result = parse.getResult(); - String expected = "\\{\"related-to\":\"l-interface\",\"related-link\":\"/aai/" + latest + "/cloud-infrastructure/cloud-regions/cloud-region/mycloudregionowner/mycloudregionid/tenants/tenant/key1/vservers/vserver/key2/l-interfaces/l-interface/key3\",\"relationship-data\":\\[\\{\"relationship-key\":\"cloud-region.cloud-owner\",\"relationship-value\":\"mycloudregionowner\"\\},\\{\"relationship-key\":\"cloud-region.cloud-region-id\",\"relationship-value\":\"mycloudregionid\"\\},\\{\"relationship-key\":\"tenant.tenant-id\",\"relationship-value\":\"key1\"\\},\\{\"relationship-key\":\"vserver.vserver-id\",\"relationship-value\":\"key2\"\\},\\{\"relationship-key\":\"l-interface.interface-name\",\"relationship-value\":\"key3\"\\}\\]\\}"; - assertTrue("blah", result.marshal(false).matches(expected)); - - - } - - /** - * Double key relationship. - * - * @throws JAXBException the JAXB exception - * @throws AAIException the AAI exception - * @throws IllegalArgumentException the illegal argument exception - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws URISyntaxException - * @throws MalformedURLException the malformed URL exception - */ - @Test - public void doubleKeyRelationship() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException, URISyntaxException { - URI uri = UriBuilder.fromPath("/aai/" + latest + "/cloud-infrastructure/complexes/complex/key1/ctag-pools/ctag-pool/key2/key3/").build(); - URIToRelationshipObject parse = new URIToRelationshipObject(loader, uri); - Introspector result = parse.getResult(); - String expected = "\\{\"related-to\":\"ctag-pool\",\"related-link\":\"/aai/" + latest + "/cloud-infrastructure/complexes/complex/key1/ctag-pools/ctag-pool/key2/key3\",\"relationship-data\":\\[\\{\"relationship-key\":\"complex.physical-location-id\",\"relationship-value\":\"key1\"\\},\\{\"relationship-key\":\"ctag-pool.target-pe\",\"relationship-value\":\"key2\"\\},\\{\"relationship-key\":\"ctag-pool.availability-zone-name\",\"relationship-value\":\"key3\"\\}\\]\\}"; - assertTrue("blah", result.marshal(false).matches(expected)); - - } - - /** - * Uri with non string key. - * - * @throws JAXBException the JAXB exception - * @throws AAIException the AAI exception - * @throws IllegalArgumentException the illegal argument exception - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws URISyntaxException - * @throws MalformedURLException the malformed URL exception - */ - @Test - public void uriWithNonStringKey() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException, URISyntaxException { - URI uri = UriBuilder.fromPath("/aai/" + latest + "/network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags/cvlan-tag/144").build(); - URIToRelationshipObject parse = new URIToRelationshipObject(loader, uri); - Introspector result = parse.getResult(); - String expected = "\\{\"related-to\":\"cvlan-tag\",\"related-link\":\"/aai/" + latest + "/network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags/cvlan-tag/144\",\"relationship-data\":\\[\\{\"relationship-key\":\"vce.vnf-id\",\"relationship-value\":\"key1\"\\},\\{\"relationship-key\":\"port-group.interface-id\",\"relationship-value\":\"key2\"\\},\\{\"relationship-key\":\"cvlan-tag.cvlan-tag\",\"relationship-value\":\"144\"\\}\\]\\}"; - assertTrue("blah", result.marshal(false).matches(expected)); - } - /** - * Bad URI. - * - * @throws JAXBException the JAXB exception - * @throws AAIException the AAI exception - * @throws IllegalArgumentException the illegal argument exception - * @throws UnsupportedEncodingException the unsupported encoding exception - */ - @Test - public void badURI() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException { - URI uri = UriBuilder.fromPath("/aai/" + loader.getVersion() + "/cloud-infrastructure/cloud-regions/cloud-region/mycloudregionowner/mycloudregionid/tenants/tenant/key1/vservers/vserver/key2/l-interadsfaces/l-interface/key3").build(); - - thrown.expect(AAIException.class); - thrown.expect(hasProperty("code", is("AAI_3000"))); - - URIToObject parse = new URIToObject(loader, uri); - - } -} diff --git a/aai-core/src/test/java/org/openecomp/aai/query/builder/SimplePathTest.java b/aai-core/src/test/java/org/openecomp/aai/query/builder/SimplePathTest.java deleted file mode 100644 index e57fb0e5..00000000 --- a/aai-core/src/test/java/org/openecomp/aai/query/builder/SimplePathTest.java +++ /dev/null @@ -1,123 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.query.builder; - -import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; -import org.apache.tinkerpop.gremlin.structure.Graph; -import org.apache.tinkerpop.gremlin.structure.T; -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph; -import org.junit.Before; -import org.junit.Test; -import org.openecomp.aai.AAISetup; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.introspection.LoaderFactory; -import org.openecomp.aai.introspection.ModelType; -import org.openecomp.aai.introspection.Version; -import org.openecomp.aai.serialization.db.EdgeRules; -import org.openecomp.aai.serialization.db.EdgeType; - -import java.util.List; - -import static org.junit.Assert.assertTrue; - -public class SimplePathTest extends AAISetup { - - public Loader loader; - - @Before - public void setup() throws Exception { - loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.getLatest()); - } - - private QueryBuilder buildTestQuery(QueryBuilder qb) throws AAIException { - return qb.createEdgeTraversal(EdgeType.TREE, "generic-vnf", "l-interface") - .until(qb.newInstance().getVerticesByProperty("aai-node-type", "generic-vnf")) - .repeat(qb.newInstance().union( - qb.newInstance().createEdgeTraversal(EdgeType.TREE, "generic-vnf", "l-interface"), - qb.newInstance().createEdgeTraversal(EdgeType.TREE, "l-interface", "generic-vnf"), - qb.newInstance().createEdgeTraversal(EdgeType.COUSIN, "l-interface", "logical-link"), - qb.newInstance().createEdgeTraversal(EdgeType.COUSIN, "logical-link", "l-interface") - ).simplePath()) - .store("x").cap("x").unfold().dedup(); - } - - private GraphTraversalSource setupGraph() throws AAIException{ - Graph graph = TinkerGraph.open(); - GraphTraversalSource g = graph.traversal(); - EdgeRules rules = EdgeRules.getInstance(); - - Vertex gvnf1 = graph.addVertex(T.label, "generic-vnf", T.id, "00", "aai-node-type", "generic-vnf", - "vnf-id", "gvnf1", "vnf-name", "genvnfname1", "nf-type", "sample-nf-type"); - - Vertex lint1 = graph.addVertex(T.label, "l-interface", T.id, "10", "aai-node-type", "l-interface", - "interface-name", "lint1", "is-port-mirrored", "true", "in-maint", "true", "is-ip-unnumbered", "false"); - - Vertex loglink1 = graph.addVertex(T.label, "logical-link", T.id, "20", "aai-node-type", "logical-link", - "link-name", "loglink1", "in-maint", "false", "link-type", "sausage"); - - Vertex lint2 = graph.addVertex(T.label, "l-interface", T.id, "11", "aai-node-type", "l-interface", - "interface-name", "lint2", "is-port-mirrored", "true", "in-maint", "true", "is-ip-unnumbered", "false"); - - Vertex loglink2 = graph.addVertex(T.label, "logical-link", T.id, "21", "aai-node-type", "logical-link", - "link-name", "loglink2", "in-maint", "false", "link-type", "sausage"); - - Vertex lint3 = graph.addVertex(T.label, "l-interface", T.id, "12", "aai-node-type", "l-interface", - "interface-name", "lint3", "is-port-mirrored", "true", "in-maint", "true", "is-ip-unnumbered", "false"); - - Vertex gvnf2 = graph.addVertex(T.label, "generic-vnf", T.id, "01", "aai-node-type", "generic-vnf", - "vnf-id", "gvnf2", "vnf-name", "genvnfname2", "nf-type", "sample-nf-type"); - - rules.addTreeEdge(g, gvnf1, lint1); - rules.addEdge(g, lint1, loglink1); - rules.addEdge(g, loglink1, lint2); - rules.addEdge(g, lint2, loglink2); - rules.addEdge(g, loglink2, lint3); - rules.addTreeEdge(g, gvnf2, lint3); - - return g; - } - - @Test - public void gremlinQueryTest() throws AAIException { - GraphTraversalSource g = setupGraph(); - List expected = g.V("01").toList(); - Vertex start = g.V("00").toList().get(0); - - GremlinTraversal qb = new GremlinTraversal<>(loader, g, start); - QueryBuilder q = buildTestQuery(qb); - List results = q.toList(); - assertTrue("results match", expected.containsAll(results) && results.containsAll(expected)); - } - - @Test - public void traversalQueryTest() throws AAIException { - GraphTraversalSource g = setupGraph(); - List expected = g.V("01").toList(); - Vertex start = g.V("00").toList().get(0); - - TraversalQuery qb = new TraversalQuery<>(loader, g, start); - QueryBuilder q = buildTestQuery(qb); - List results = q.toList(); - assertTrue("results match", expected.containsAll(results) && results.containsAll(expected)); - } -} diff --git a/aai-core/src/test/java/org/openecomp/aai/query/builder/TraversalQueryTest.java b/aai-core/src/test/java/org/openecomp/aai/query/builder/TraversalQueryTest.java deleted file mode 100644 index f8418bd1..00000000 --- a/aai-core/src/test/java/org/openecomp/aai/query/builder/TraversalQueryTest.java +++ /dev/null @@ -1,101 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.query.builder; - -import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; -import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; -import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__; -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.mockito.Mock; -import org.openecomp.aai.AAISetup; -import org.openecomp.aai.db.props.AAIProperties; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.introspection.LoaderFactory; -import org.openecomp.aai.introspection.ModelType; - -import java.io.UnsupportedEncodingException; -import java.net.URI; -import java.net.URISyntaxException; - -import static org.junit.Assert.assertEquals; - -public class TraversalQueryTest extends AAISetup { - - private Loader loader; - - @Mock - private GraphTraversalSource g; - - @Before - public void configure() throws Exception { - loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, AAIProperties.LATEST); - } - - @Test - public void unionQuery() { - TraversalQuery tQ = new TraversalQuery<>(loader, g); - TraversalQuery tQ2 = new TraversalQuery<>(loader, g); - TraversalQuery tQ3 = new TraversalQuery<>(loader, g); - tQ.union( - tQ2.getVerticesByProperty("test1", "value1"), - tQ3.getVerticesByIndexedProperty("test2", "value2")); - - GraphTraversal expected = __.start() - .union(__.has("test1", "value1"),__.has("test2", "value2")); - - assertEquals("they are equal", expected, tQ.getQuery()); - - } - - @Ignore - @Test - public void traversalClones() throws UnsupportedEncodingException, AAIException, URISyntaxException { - TraversalQuery tQ = new TraversalQuery<>(loader, g); - QueryBuilder builder = tQ.createQueryFromURI(new URI("network/test-objects/test-object/key1")).getQueryBuilder(); - GraphTraversal expected = __.start().has("vnf-id", "key1").has("aai-node-type", "test-object"); - GraphTraversal containerExpected = __.start().has("aai-node-type", "test-object"); - - assertEquals("query object", expected.toString(), builder.getQuery().toString()); - assertEquals("container query object", containerExpected.toString(), builder.getContainerQuery().getQuery().toString()); - - } - - @Ignore - @Test - public void nestedTraversalClones() throws UnsupportedEncodingException, AAIException, URISyntaxException { - - TraversalQuery tQ = new TraversalQuery<>(loader, g); - QueryBuilder builder = tQ.createQueryFromURI(new URI("network/generic-vnfs/generic-vnf/key1/l-interfaces/l-interface/key2")).getQueryBuilder(); - GraphTraversal expected = __.start().has("vnf-id", "key1").has("aai-node-type", "generic-vnf").out("hasLInterface").has(AAIProperties.NODE_TYPE, "l-interface").has("interface-name", "key2"); - GraphTraversal containerExpected = __.start().has("vnf-id", "key1").has("aai-node-type", "generic-vnf").out("hasLInterface").has(AAIProperties.NODE_TYPE, "l-interface"); - - assertEquals("query object", expected.toString(), builder.getQuery().toString()); - assertEquals("container query object", containerExpected.toString(), builder.getContainerQuery().getQuery().toString()); - - } - - - -} diff --git a/aai-core/src/test/java/org/openecomp/aai/query/builder/UntilTest.java b/aai-core/src/test/java/org/openecomp/aai/query/builder/UntilTest.java deleted file mode 100644 index b6c6025a..00000000 --- a/aai-core/src/test/java/org/openecomp/aai/query/builder/UntilTest.java +++ /dev/null @@ -1,112 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.query.builder; - -import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; -import org.apache.tinkerpop.gremlin.structure.Graph; -import org.apache.tinkerpop.gremlin.structure.T; -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph; -import org.junit.Before; -import org.junit.Test; -import org.openecomp.aai.AAISetup; -import org.openecomp.aai.db.props.AAIProperties; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.introspection.LoaderFactory; -import org.openecomp.aai.introspection.ModelType; -import org.openecomp.aai.serialization.db.EdgeRules; -import org.openecomp.aai.serialization.db.EdgeType; - -import java.util.ArrayList; -import java.util.List; - -import static org.junit.Assert.assertTrue; - -public class UntilTest extends AAISetup { - - private Loader loader; - - @Before - public void setup() throws Exception { - loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, AAIProperties.LATEST); - } - - private QueryBuilder buildTestQuery(QueryBuilder qb) throws AAIException{ - return qb.until(qb.newInstance().getVerticesByProperty("aai-node-type", "l-interface")).repeat( - qb.newInstance().union( - qb.newInstance().createEdgeTraversal(EdgeType.TREE, "cloud-region", "tenant"), - qb.newInstance().createEdgeTraversal(EdgeType.TREE, "tenant", "vserver"), - qb.newInstance().createEdgeTraversal(EdgeType.TREE, "vserver", "l-interface") - )).store("x").cap("x").unfold().dedup(); - } - - @Test - public void gremlinQueryUntilTest() throws AAIException { - Graph graph = TinkerGraph.open(); - EdgeRules rules = EdgeRules.getInstance(); - GraphTraversalSource g = graph.traversal(); - - Vertex v1 = graph.addVertex(T.id, 1, "aai-node-type", "cloud-region"); - Vertex v2 = graph.addVertex(T.id, 2, "aai-node-type", "tenant"); - Vertex v3 = graph.addVertex(T.id, 3, "aai-node-type", "vserver"); - Vertex v4 = graph.addVertex(T.id, 4, "aai-node-type", "l-interface"); - rules.addTreeEdge(g, v1, v2); - rules.addTreeEdge(g, v2, v3); - rules.addTreeEdge(g, v3, v4); - List expected = new ArrayList<>(); - expected.add(v4); - - GremlinTraversal qb = new GremlinTraversal<>(loader, g, v1); - QueryBuilder q = buildTestQuery(qb); - - List results = q.toList(); - - assertTrue("results match", expected.containsAll(results) && results.containsAll(expected)); - } - - @Test - public void traversalQueryUntilTest() throws AAIException { - Graph graph = TinkerGraph.open(); - EdgeRules rules = EdgeRules.getInstance(); - GraphTraversalSource g = graph.traversal(); - - Vertex v1 = graph.addVertex(T.id, 1, "aai-node-type", "cloud-region"); - Vertex v2 = graph.addVertex(T.id, 2, "aai-node-type", "tenant"); - Vertex v3 = graph.addVertex(T.id, 3, "aai-node-type", "vserver"); - Vertex v4 = graph.addVertex(T.id, 4, "aai-node-type", "l-interface"); - rules.addTreeEdge(g, v1, v2); - rules.addTreeEdge(g, v2, v3); - rules.addTreeEdge(g, v3, v4); - List expected = new ArrayList<>(); - expected.add(v4); - - TraversalQuery qb = new TraversalQuery<>(loader, g, v1); - QueryBuilder q = buildTestQuery(qb); - - List results = q.toList(); - - assertTrue("results match", expected.containsAll(results) && results.containsAll(expected)); - } - - - -} diff --git a/aai-core/src/test/java/org/openecomp/aai/serialization/db/DbAliasTest.java b/aai-core/src/test/java/org/openecomp/aai/serialization/db/DbAliasTest.java deleted file mode 100644 index d4793939..00000000 --- a/aai-core/src/test/java/org/openecomp/aai/serialization/db/DbAliasTest.java +++ /dev/null @@ -1,132 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.serialization.db; - -import com.thinkaurelius.titan.core.TitanFactory; -import com.thinkaurelius.titan.core.TitanGraph; -import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; -import org.apache.tinkerpop.gremlin.structure.Graph; -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.openecomp.aai.AAISetup; -import org.openecomp.aai.dbmap.DBConnectionType; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.*; -import org.openecomp.aai.parsers.query.QueryParser; -import org.openecomp.aai.schema.enums.PropertyMetadata; -import org.openecomp.aai.serialization.engines.QueryStyle; -import org.openecomp.aai.serialization.engines.TitanDBEngine; -import org.openecomp.aai.serialization.engines.TransactionalGraphEngine; - -import java.io.UnsupportedEncodingException; -import java.lang.reflect.InvocationTargetException; -import java.net.MalformedURLException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Collections; -import java.util.Map; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.when; - -public class DbAliasTest extends AAISetup { - - private TitanGraph graph; - - private final Version version = Version.v9; - private final ModelType introspectorFactoryType = ModelType.MOXY; - private final QueryStyle queryStyle = QueryStyle.TRAVERSAL; - private final DBConnectionType type = DBConnectionType.REALTIME; - private Loader loader; - private TransactionalGraphEngine dbEngine; - - @Before - public void setup() throws Exception { - graph = TitanFactory.build().set("storage.backend","inmemory").open(); - loader = LoaderFactory.createLoaderForVersion(introspectorFactoryType, version); - dbEngine = new TitanDBEngine( - queryStyle, - type, - loader); - } - - @After - public void tearDown() { - graph.tx().rollback(); - graph.close(); - } - - @Test - public void checkOnWrite() throws AAIException, UnsupportedEncodingException, URISyntaxException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, NoSuchMethodException, InterruptedException { - final String property = "persona-model-customization-id"; - String dbPropertyName = property; - TransactionalGraphEngine spy = spy(this.dbEngine); - TransactionalGraphEngine.Admin adminSpy = spy(dbEngine.asAdmin()); - Graph g = graph.newTransaction(); - GraphTraversalSource traversal = g.traversal(); - when(spy.asAdmin()).thenReturn(adminSpy); - when(adminSpy.getTraversalSource()).thenReturn(traversal); - DBSerializer serializer = new DBSerializer(version, spy, introspectorFactoryType, "AAI_TEST"); - QueryParser uriQuery = spy.getQueryBuilder().createQueryFromURI(new URI("network/generic-vnfs/generic-vnf/key1")); - Introspector obj = loader.introspectorFromName("generic-vnf"); - Vertex v = g.addVertex(); - Object id = v.id(); - obj.setValue("vnf-id", "key1"); - obj.setValue(property, "hello"); - serializer.serializeToDb(obj, v, uriQuery, "", ""); - g.tx().commit(); - v = graph.traversal().V(id).next(); - Map map = obj.getPropertyMetadata(property); - if (map.containsKey(PropertyMetadata.DB_ALIAS)) { - dbPropertyName = map.get(PropertyMetadata.DB_ALIAS); - } - - assertEquals("dbAlias is ", "model-customization-id", dbPropertyName); - assertEquals("dbAlias property exists", "hello", v.property(dbPropertyName).orElse("")); - assertEquals("model property does not", "missing", v.property(property).orElse("missing")); - - } - - @Test - public void checkOnRead() throws AAIException, UnsupportedEncodingException, URISyntaxException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, NoSuchMethodException, InterruptedException, MalformedURLException { - final String property = "persona-model-customization-id"; - - TransactionalGraphEngine spy = spy(dbEngine); - TransactionalGraphEngine.Admin adminSpy = spy(dbEngine.asAdmin()); - Vertex v = graph.traversal().addV("vnf-id", "key1", "model-customization-id", "hello").next(); - graph.tx().commit(); - Graph g = graph.newTransaction(); - GraphTraversalSource traversal = g.traversal(); - when(spy.asAdmin()).thenReturn(adminSpy); - when(adminSpy.getTraversalSource()).thenReturn(traversal); - DBSerializer serializer = new DBSerializer(version, spy, introspectorFactoryType, "AAI_TEST"); - Introspector obj = loader.introspectorFromName("generic-vnf"); - serializer.dbToObject(Collections.singletonList(v), obj, 0, true, "false"); - - assertEquals("dbAlias property exists", "hello", obj.getValue(property)); - - } - - -} diff --git a/aai-core/src/test/java/org/openecomp/aai/serialization/db/DbSerializerTest.java b/aai-core/src/test/java/org/openecomp/aai/serialization/db/DbSerializerTest.java deleted file mode 100644 index b30c9367..00000000 --- a/aai-core/src/test/java/org/openecomp/aai/serialization/db/DbSerializerTest.java +++ /dev/null @@ -1,440 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.serialization.db; - -import com.thinkaurelius.titan.core.TitanFactory; -import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; -import org.apache.tinkerpop.gremlin.structure.Edge; -import org.apache.tinkerpop.gremlin.structure.Graph; -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.openecomp.aai.AAISetup; -import org.openecomp.aai.db.props.AAIProperties; -import org.openecomp.aai.dbmap.DBConnectionType; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.introspection.LoaderFactory; -import org.openecomp.aai.introspection.ModelType; -import org.openecomp.aai.introspection.Version; -import org.openecomp.aai.serialization.engines.QueryStyle; -import org.openecomp.aai.serialization.engines.TitanDBEngine; -import org.openecomp.aai.serialization.engines.TransactionalGraphEngine; - -import static org.junit.Assert.*; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.when; - -import java.io.UnsupportedEncodingException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -public class DbSerializerTest extends AAISetup { - - //to use, set thrown.expect to whatever your test needs - //this line establishes default of expecting no exception to be thrown - @Rule - public ExpectedException thrown = ExpectedException.none(); - - protected Graph graph; - protected final EdgeRules rules = EdgeRules.getInstance(); - - private final Version version = Version.getLatest(); - private final ModelType introspectorFactoryType = ModelType.MOXY; - private final QueryStyle queryStyle = QueryStyle.TRAVERSAL; - private final DBConnectionType type = DBConnectionType.REALTIME; - private Loader loader; - private TransactionalGraphEngine dbEngine; - private TransactionalGraphEngine engine; //for tests that aren't mocking the engine - private DBSerializer dbser; - TransactionalGraphEngine spy; - TransactionalGraphEngine.Admin adminSpy; - - @Before - public void setup() throws Exception { - graph = TitanFactory.build().set("storage.backend", "inmemory").open(); - loader = LoaderFactory.createLoaderForVersion(introspectorFactoryType, version); - dbEngine = new TitanDBEngine(queryStyle, type, loader); - spy = spy(dbEngine); - adminSpy = spy(dbEngine.asAdmin()); - - createGraph(); - - engine = new TitanDBEngine(queryStyle, type, loader); - dbser = new DBSerializer(Version.getLatest(), engine, introspectorFactoryType, "AAI-TEST"); - } - - public void createGraph() throws AAIException { - /* - * This setus up the test graph, For future junits , add more vertices - * and edges - */ - - Vertex l3interipv4addresslist_1 = graph.traversal().addV("aai-node-type", "l3-interface-ipv4-address-list", - "l3-interface-ipv4-address", "l3-interface-ipv4-address-1").next(); - Vertex subnet_2 = graph.traversal().addV("aai-node-type", "subnet", "subnet-id", "subnet-id-2").next(); - Vertex l3interipv6addresslist_3 = graph.traversal().addV("aai-node-type", "l3-interface-ipv6-address-list", - "l3-interface-ipv6-address", "l3-interface-ipv6-address-3").next(); - Vertex subnet_4 = graph.traversal().addV("aai-node-type", "subnet", "subnet-id", "subnet-id-4").next(); - Vertex subnet_5 = graph.traversal().addV("aai-node-type", "subnet", "subnet-id", "subnet-id-5").next(); - Vertex l3network_6 = graph.traversal() - .addV("aai-node-type", "l3-network", "network-id", "network-id-6", "network-name", "network-name-6") - .next(); - - GraphTraversalSource g = graph.traversal(); - rules.addEdge(g, l3interipv4addresslist_1, subnet_2); - rules.addEdge(g, l3interipv6addresslist_3, subnet_4); - rules.addTreeEdge(g, subnet_5, l3network_6); - - } - - @After - public void tearDown() throws Exception { - graph.close(); - } - - @Test - public void subnetDelwithInEdgesIpv4Test() throws AAIException { - String expected_message = "Object is being reference by additional objects preventing it from being deleted. Please clean up references from the following types [l3-interface-ipv4-address-list]"; - - /* - * This subnet has in-edges with l3-ipv4 and NOT ok to delete - */ - Vertex subnet = graph.traversal().V().has("aai-node-type", "subnet").has("subnet-id", "subnet-id-2").next(); - - String exceptionMessage = testDelete(subnet); - assertEquals(expected_message, exceptionMessage); - - } - - @Test - public void subnetDelwithInEdgesIpv6Test() throws AAIException { - String expected_message = "Object is being reference by additional objects preventing it from being deleted. Please clean up references from the following types [l3-interface-ipv6-address-list]"; - - /* - * This subnet has in-edges with l3-ipv6 and NOT ok to delete - */ - Vertex subnet = graph.traversal().V().has("aai-node-type", "subnet").has("subnet-id", "subnet-id-4").next(); - String exceptionMessage = testDelete(subnet); - assertEquals(expected_message, exceptionMessage); - - } - - @Test - public void subnetDelwithInEdgesL3network() throws AAIException { - String expected_message = ""; - - /* - * This subnet has in-edges with l3-network and ok to delete - */ - Vertex subnet = graph.traversal().V().has("aai-node-type", "subnet").has("subnet-id", "subnet-id-5").next(); - - String exceptionMessage = testDelete(subnet); - assertEquals(expected_message, exceptionMessage); - - } - - public String testDelete(Vertex v) throws AAIException { - - // Graph g_tx = graph.newTransaction(); - GraphTraversalSource traversal = graph.traversal(); - when(spy.asAdmin()).thenReturn(adminSpy); - when(adminSpy.getTraversalSource()).thenReturn(traversal); - when(adminSpy.getReadOnlyTraversalSource()).thenReturn(traversal); - - String exceptionMessage = ""; - DBSerializer serializer = new DBSerializer(version, spy, introspectorFactoryType, "AAI_TEST"); - try { - serializer.delete(v, "resourceVersion", false); - } catch (AAIException exception) { - exceptionMessage = exception.getMessage(); - - } - return exceptionMessage; - - } - - @Test - public void createNewVertexTest() throws AAIException { - engine.startTransaction(); - - Introspector testObj = loader.introspectorFromName("generic-vnf"); - - Vertex testVertex = dbser.createNewVertex(testObj); - Vertex fromGraph = engine.tx().traversal().V().has("aai-node-type","generic-vnf").toList().get(0); - assertEquals(testVertex.id(), fromGraph.id()); - assertEquals("AAI-TEST", fromGraph.property(AAIProperties.SOURCE_OF_TRUTH.toString()).value()); - engine.rollback(); - } - - @Test - public void touchStandardVertexPropertiesTest() throws AAIException, InterruptedException { - engine.startTransaction(); - DBSerializer dbser2 = new DBSerializer(Version.getLatest(), engine, introspectorFactoryType, "AAI-TEST-2"); - - Graph graph = TinkerGraph.open(); - Vertex vert = graph.addVertex("aai-node-type", "generic-vnf"); - - dbser.touchStandardVertexProperties(vert, true); - String resverStart = (String)vert.property(AAIProperties.RESOURCE_VERSION.toString()).value(); - String lastModTimeStart = (String)vert.property(AAIProperties.LAST_MOD_TS.toString()).value(); - - Thread.sleep(10); //bc the resource version is set based on current time in milliseconds, - //if this test runs through too fast the value may not change - //causing the test to fail. sleeping ensures a different value - - dbser2.touchStandardVertexProperties(vert, false); - assertFalse(resverStart.equals((String)vert.property(AAIProperties.RESOURCE_VERSION.toString()).value())); - assertFalse(lastModTimeStart.equals((String)vert.property(AAIProperties.LAST_MOD_TS.toString()).value())); - assertEquals("AAI-TEST-2", (String)vert.property(AAIProperties.LAST_MOD_SOURCE_OF_TRUTH.toString()).value()); - engine.rollback(); - } - - @Test - public void verifyResourceVersion_SunnyDayTest() throws AAIException { - engine.startTransaction(); - - assertTrue(dbser.verifyResourceVersion("delete", "vnfc", "abc", "abc", "vnfcs/vnfc/vnfcId")); - engine.rollback(); - } - - @Test - public void verifyResourceVersion_CreateWithRVTest() throws AAIException { - engine.startTransaction(); - - thrown.expect(AAIException.class); - thrown.expectMessage("resource-version passed for create of generic-vnfs/generic-vnf/myid"); - try { - dbser.verifyResourceVersion("create", "generic-vnf", null, "old-res-ver", "generic-vnfs/generic-vnf/myid"); - } finally { - engine.rollback(); - } - } - - @Test - public void verifyResourceVersion_MissingRVTest() throws AAIException { - engine.startTransaction(); - - thrown.expect(AAIException.class); - thrown.expectMessage("resource-version not passed for update of generic-vnfs/generic-vnf/myid"); - try { - dbser.verifyResourceVersion("update", "generic-vnf", "current-res-ver", null, "generic-vnfs/generic-vnf/myid"); - } finally { - engine.rollback(); - } - } - - @Test - public void verifyResourceVersion_MismatchRVTest() throws AAIException { - engine.startTransaction(); - - thrown.expect(AAIException.class); - thrown.expectMessage("resource-version MISMATCH for update of generic-vnfs/generic-vnf/myid"); - try { - dbser.verifyResourceVersion("update", "generic-vnf", "current-res-ver", "old-res-ver", "generic-vnfs/generic-vnf/myid"); - } finally { - engine.rollback(); - } - } - - @Test - public void trimClassNameTest() throws AAIException { - assertEquals("GenericVnf", dbser.trimClassName("GenericVnf")); - assertEquals("GenericVnf", dbser.trimClassName("org.onap.aai.GenericVnf")); - } - - @Test - public void getURIForVertexTest() throws AAIException, URISyntaxException, UnsupportedEncodingException { - engine.startTransaction(); - - Vertex cr = engine.tx().addVertex("aai-node-type", "cloud-region", "cloud-owner", "me", "cloud-region-id", "123"); - Vertex ten = engine.tx().addVertex("aai-node-type", "tenant", "tenant-id", "453"); - EdgeRules rules = EdgeRules.getInstance(); - rules.addTreeEdge(engine.tx().traversal(), cr, ten); - - URI compare = new URI("/cloud-infrastructure/cloud-regions/cloud-region/me/123/tenants/tenant/453"); - assertEquals(compare, dbser.getURIForVertex(ten)); - - cr.property("aai-node-type").remove(); - URI compareFailure = new URI("/unknown-uri"); - assertEquals(compareFailure, dbser.getURIForVertex(ten)); - engine.rollback(); - } - - @Test - public void getVertexPropertiesTest() throws AAIException, UnsupportedEncodingException { - engine.startTransaction(); - - Vertex cr = engine.tx().addVertex("aai-node-type", "cloud-region", "cloud-owner", "me", "cloud-region-id", "123"); - - Introspector crIntro = dbser.getVertexProperties(cr); - assertEquals("cloud-region", crIntro.getDbName()); - assertEquals("me", crIntro.getValue("cloud-owner")); - assertEquals("123", crIntro.getValue("cloud-region-id")); - engine.rollback(); - } - - @Test - public void setCachedURIsTest() throws AAIException, UnsupportedEncodingException, URISyntaxException { - engine.startTransaction(); - - Vertex cr = engine.tx().addVertex("aai-node-type", "cloud-region", "cloud-owner", "me", "cloud-region-id", "123"); - Vertex ten = engine.tx().addVertex("aai-node-type", "tenant", "tenant-id", "453"); - Vertex vs = engine.tx().addVertex("aai-node-type", "vserver", "vserver-id", "vs1", - AAIProperties.AAI_URI.toString(), - "/cloud-infrastructure/cloud-regions/cloud-region/me/123/tenants/tenant/453/vservers/vserver/vs1"); - EdgeRules rules = EdgeRules.getInstance(); - rules.addTreeEdge(engine.tx().traversal(), cr, ten); - rules.addTreeEdge(engine.tx().traversal(), ten, vs); - - List vertices = new ArrayList(Arrays.asList(cr, ten, vs)); - Introspector crIn = dbser.getVertexProperties(cr); - Introspector tenIn = dbser.getVertexProperties(ten); - Introspector vsIn = dbser.getVertexProperties(vs); - List intros = new ArrayList(Arrays.asList(crIn, tenIn, vsIn)); - - dbser.setCachedURIs(vertices, intros); - - assertEquals("/cloud-infrastructure/cloud-regions/cloud-region/me/123", - (String)cr.property(AAIProperties.AAI_URI.toString()).value()); - assertEquals("/cloud-infrastructure/cloud-regions/cloud-region/me/123/tenants/tenant/453", - (String)ten.property(AAIProperties.AAI_URI.toString()).value()); - assertEquals("/cloud-infrastructure/cloud-regions/cloud-region/me/123/tenants/tenant/453/vservers/vserver/vs1", - (String)vs.property(AAIProperties.AAI_URI.toString()).value()); - engine.rollback(); - } - - @Test - public void getEdgeBetweenTest() throws AAIException { - engine.startTransaction(); - - Vertex cr = engine.tx().addVertex("aai-node-type", "cloud-region", "cloud-owner", "me", "cloud-region-id", "123"); - Vertex ten = engine.tx().addVertex("aai-node-type", "tenant", "tenant-id", "453"); - EdgeRules rules = EdgeRules.getInstance(); - rules.addTreeEdge(engine.tx().traversal(), cr, ten); - - Edge e = dbser.getEdgeBetween(EdgeType.TREE, ten, cr); - assertEquals("has", e.label()); - engine.rollback(); - } - - @Test - public void deleteEdgeTest() throws AAIException, UnsupportedEncodingException { - engine.startTransaction(); - - Vertex gvnf = engine.tx().addVertex("aai-node-type","generic-vnf","vnf-id","myvnf"); - Vertex vnfc = engine.tx().addVertex("aai-node-type","vnfc","vnfc-name","a-name"); - EdgeRules rules = EdgeRules.getInstance(); - rules.addEdge(engine.tx().traversal(), gvnf, vnfc); - - Introspector relData = loader.introspectorFromName("relationship-data"); - relData.setValue("relationship-key", "vnfc.vnfc-name"); - relData.setValue("relationship-value", "a-name"); - Introspector relationship = loader.introspectorFromName("relationship"); - relationship.setValue("related-to", "vnfc"); - relationship.setValue("related-link", "/network/vnfcs/vnfc/a-name"); - relationship.setValue("relationship-data",relData); - - assertTrue(dbser.deleteEdge(relationship, gvnf)); - - assertFalse(engine.tx().traversal().V(gvnf).both("uses").hasNext()); - assertFalse(engine.tx().traversal().V(vnfc).both("uses").hasNext()); - engine.rollback(); - } - - @Test - public void createEdgeTest() throws AAIException, UnsupportedEncodingException { - engine.startTransaction(); - - Vertex gvnf = engine.tx().addVertex("aai-node-type","generic-vnf","vnf-id","myvnf"); - Vertex vnfc = engine.tx().addVertex("aai-node-type","vnfc","vnfc-name","a-name"); - - //sunny day case - Introspector relData = loader.introspectorFromName("relationship-data"); - relData.setValue("relationship-key", "vnfc.vnfc-name"); - relData.setValue("relationship-value", "a-name"); - Introspector relationship = loader.introspectorFromName("relationship"); - relationship.setValue("related-to", "vnfc"); - relationship.setValue("related-link", "/network/vnfcs/vnfc/a-name"); - relationship.setValue("relationship-data",relData); - - assertTrue(dbser.createEdge(relationship, gvnf)); - assertTrue(engine.tx().traversal().V(gvnf).both("uses").hasNext()); - assertTrue(engine.tx().traversal().V(vnfc).both("uses").hasNext()); - - //rainy day case, edge to nonexistant object - Introspector relData2 = loader.introspectorFromName("relationship-data"); - relData2.setValue("relationship-key", "vnfc.vnfc-name"); - relData2.setValue("relationship-value", "b-name"); - Introspector relationship2 = loader.introspectorFromName("relationship"); - relationship2.setValue("related-to", "vnfc"); - relationship2.setValue("related-link", "/network/vnfcs/vnfc/b-name"); - relationship2.setValue("relationship-data",relData2); - - thrown.expect(AAIException.class); - thrown.expectMessage("Node of type vnfc. Could not find object at: /network/vnfcs/vnfc/b-name"); - try { - dbser.createEdge(relationship2, gvnf); - } finally { - engine.rollback(); - } - } - - @Test - public void serializeSingleVertexTopLevelTest() throws AAIException, UnsupportedEncodingException { - engine.startTransaction(); - - Introspector gvnf = loader.introspectorFromName("generic-vnf"); - Vertex gvnfVert = dbser.createNewVertex(gvnf); - - gvnf.setValue("vnf-id", "myvnf"); - dbser.serializeSingleVertex(gvnfVert, gvnf, "test"); - assertTrue(engine.tx().traversal().V().has("aai-node-type","generic-vnf").has("vnf-id","myvnf").hasNext()); - engine.rollback(); - } - - @Test - public void serializeSingleVertexChildTest() throws AAIException, UnsupportedEncodingException { - engine.startTransaction(); - - Vertex cr = engine.tx().addVertex("aai-node-type", "cloud-region", "cloud-owner", "me", "cloud-region-id", "123"); - Introspector tenIn = loader.introspectorFromName("tenant"); - Vertex ten = dbser.createNewVertex(tenIn); - EdgeRules rules = EdgeRules.getInstance(); - rules.addTreeEdge(engine.tx().traversal(), cr, ten); - - tenIn.setValue("tenant-id", "453"); - tenIn.setValue("tenant-name", "mytenant"); - - dbser.serializeSingleVertex(ten, tenIn, "test"); - - assertTrue(engine.tx().traversal().V().has("aai-node-type","tenant").has("tenant-id","453").has("tenant-name","mytenant").hasNext()); - engine.rollback(); - } -} \ No newline at end of file diff --git a/aai-core/src/test/java/org/openecomp/aai/serialization/db/EdgePropertyMapTest.java b/aai-core/src/test/java/org/openecomp/aai/serialization/db/EdgePropertyMapTest.java deleted file mode 100644 index fb3c0469..00000000 --- a/aai-core/src/test/java/org/openecomp/aai/serialization/db/EdgePropertyMapTest.java +++ /dev/null @@ -1,43 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.serialization.db; - -import org.junit.Test; - -import java.util.Map; - -import static org.junit.Assert.assertEquals; - -public class EdgePropertyMapTest { - - @Test - public void run() { - Map map = new EdgePropertyMap<>(); - map.put("direction", "OUT"); - map.put("test", "hello"); - map.put("isParent", "${direction}"); - map.put("SVC-INFRA", "!${direction}"); - - assertEquals("normal retrieval", "hello", map.get("test")); - assertEquals("variable retrieval", "OUT", map.get("isParent")); - assertEquals("negate variable retrieval", "IN", map.get("SVC-INFRA")); - } -} diff --git a/aai-core/src/test/java/org/openecomp/aai/serialization/db/EdgeRulesTest.java b/aai-core/src/test/java/org/openecomp/aai/serialization/db/EdgeRulesTest.java deleted file mode 100644 index 0257e6b1..00000000 --- a/aai-core/src/test/java/org/openecomp/aai/serialization/db/EdgeRulesTest.java +++ /dev/null @@ -1,237 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.serialization.db; - - -import org.apache.tinkerpop.gremlin.structure.Direction; -import org.junit.Test; -import org.openecomp.aai.AAISetup; -import static org.junit.Assert.assertEquals; - -import java.util.Map; -import java.util.Set; - -import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; -import org.apache.tinkerpop.gremlin.structure.Graph; -import org.apache.tinkerpop.gremlin.structure.T; -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph; -import org.junit.Rule; -import org.junit.rules.ExpectedException; - -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Version; -import org.openecomp.aai.serialization.db.exceptions.EdgeMultiplicityException; -import org.openecomp.aai.serialization.db.exceptions.NoEdgeRuleFoundException; - -import com.google.common.collect.Multimap; - -public class EdgeRulesTest extends AAISetup { - - //set thrown.expect to whatever a specific test needs - //this establishes a default of expecting no exceptions to be thrown - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Test - public void verifyOutDirection() throws AAIException, NoEdgeRuleFoundException { - EdgeRules rules = EdgeRules.getInstance(); - EdgeRule rule = rules.getEdgeRule(EdgeType.TREE, "cloud-region", "flavor"); - - assertEquals("out direction", rule.getDirection(), Direction.OUT); - } - - @Test - public void verifyOutFlippedDirection() throws AAIException, NoEdgeRuleFoundException { - EdgeRules rules = EdgeRules.getInstance(); - EdgeRule rule = rules.getEdgeRule(EdgeType.TREE, "flavor", "cloud-region"); - - assertEquals("in direction", rule.getDirection(), Direction.IN); - } - - @Test - public void verifyInDirection() throws AAIException, NoEdgeRuleFoundException { - EdgeRules rules = EdgeRules.getInstance(); - EdgeRule rule = rules.getEdgeRule(EdgeType.COUSIN, "model-ver", "model-element"); - - assertEquals("in direction", rule.getDirection(), Direction.IN); - } - - @Test - public void verifyInFlippedDirection() throws AAIException, NoEdgeRuleFoundException { - EdgeRules rules = EdgeRules.getInstance(); - EdgeRule rule = rules.getEdgeRule(EdgeType.COUSIN, "model-element", "model-ver"); - - assertEquals("out direction", rule.getDirection(), Direction.OUT); - } - @Test - public void verifyMultipleGet() throws AAIException { - EdgeRules rules = EdgeRules.getInstance(); - Map ruleMap = rules.getEdgeRules("model-element", "model-ver"); - assertEquals("has isA rule", "isA", ruleMap.get("isA").getLabel()); - assertEquals("has startsWith rule", "startsWith", ruleMap.get("startsWith").getLabel()); - } - - @Test - public void verifyMultipleGetSingleRule() throws AAIException { - EdgeRules rules = EdgeRules.getInstance(); - Map ruleMap = rules.getEdgeRules("availability-zone", "complex"); - assertEquals("has groupsResourcesIn rule", "groupsResourcesIn", ruleMap.get("groupsResourcesIn").getLabel()); - } - - @Test - public void verifyOldEdgeRule() throws AAIException, ClassNotFoundException, IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { - assertEquals(true, EdgeRules.getInstance().hasEdgeRule("model-element", "model-ver")); - assertEquals(true, EdgeRules.getInstance(Version.v8).hasEdgeRule("pserver", "complex")); - assertEquals(false, EdgeRules.getInstance(Version.v8).hasEdgeRule("model-element", "model-ver")); - } - - @Test - public void hasEdgeRuleVertexTest() { - Graph graph = TinkerGraph.open(); - Vertex v1 = graph.addVertex("aai-node-type", "cloud-region"); - Vertex v2 = graph.addVertex("aai-node-type", "tenant"); - assertEquals(true, EdgeRules.getInstance().hasEdgeRule(v1, v2)); - } - - @Test - public void getEdgeRuleByTypeAndVertices() throws AAIException { - Graph graph = TinkerGraph.open(); - Vertex v1 = graph.addVertex("aai-node-type", "cloud-region"); - Vertex v2 = graph.addVertex("aai-node-type", "tenant"); - EdgeRules rules = EdgeRules.getInstance(); - EdgeRule rule = rules.getEdgeRule(EdgeType.TREE, v1, v2); - assertEquals(true, "OUT".equalsIgnoreCase(rule.getContains())); - assertEquals(true, "NONE".equalsIgnoreCase(rule.getDeleteOtherV())); - assertEquals(true, MultiplicityRule.ONE2MANY.equals(rule.getMultiplicityRule())); - assertEquals(true, "IN".equalsIgnoreCase(rule.getServiceInfrastructure())); - assertEquals(true, "OUT".equalsIgnoreCase(rule.getPreventDelete())); - } - - @Test - public void addTreeEdgeTest() throws AAIException { - Graph graph = TinkerGraph.open(); - Vertex v1 = graph.addVertex(T.id, "1", "aai-node-type", "cloud-region"); - Vertex v2 = graph.addVertex(T.id, "10", "aai-node-type", "tenant"); - EdgeRules rules = EdgeRules.getInstance(); - GraphTraversalSource g = graph.traversal(); - rules.addTreeEdge(g, v1, v2); - assertEquals(true, g.V(v1).out("has").has("aai-node-type", "tenant").hasNext()); - - Vertex v3 = graph.addVertex(T.id, "2", "aai-node-type", "cloud-region"); - assertEquals(null, rules.addTreeEdgeIfPossible(g, v3, v2)); - } - - @Test - public void addCousinEdgeTest() throws AAIException { - Graph graph = TinkerGraph.open(); - Vertex v1 = graph.addVertex(T.id, "1", "aai-node-type", "flavor"); - Vertex v2 = graph.addVertex(T.id, "10", "aai-node-type", "vserver"); - EdgeRules rules = EdgeRules.getInstance(Version.getLatest()); - GraphTraversalSource g = graph.traversal(); - rules.addEdge(g, v1, v2); - assertEquals(true, g.V(v2).out("hasFlavor").has("aai-node-type", "flavor").hasNext()); - - Vertex v3 = graph.addVertex(T.id, "2", "aai-node-type", "flavor"); - assertEquals(null, rules.addEdgeIfPossible(g, v3, v2)); - } - - @Test - public void multiplicityViolationTest() throws AAIException { - thrown.expect(EdgeMultiplicityException.class); - thrown.expectMessage("multiplicity rule violated: only one edge can exist with label: uses between vf-module and volume-group"); - - Graph graph = TinkerGraph.open(); - Vertex v1 = graph.addVertex(T.id, "1", "aai-node-type", "vf-module"); - Vertex v2 = graph.addVertex(T.id, "10", "aai-node-type", "volume-group"); - EdgeRules rules = EdgeRules.getInstance(Version.getLatest()); - GraphTraversalSource g = graph.traversal(); - - rules.addEdge(g, v2, v1); - Vertex v3 = graph.addVertex(T.id, "3", "aai-node-type", "vf-module"); - rules.addEdge(g, v2, v3); - } - - @Test - public void getChildrenTest() { - EdgeRules rules = EdgeRules.getInstance("/dbedgerules/DbEdgeRules_test.json"); - Set children = rules.getChildren("foo"); - assertEquals(2, children.size()); - boolean sawBazRule = false; - boolean sawQuuxRule = false; - for (EdgeRule r : children) { - if ("isVeryHappyAbout".equals(r.getLabel())) { - sawBazRule = true; - } else if ("dancesWith".equals(r.getLabel())) { - sawQuuxRule = true; - } - } - assertEquals(true, sawBazRule && sawQuuxRule); - } - - @Test - public void getAllRulesTest() { - EdgeRules rules = EdgeRules.getInstance("/dbedgerules/DbEdgeRules_test.json"); - Multimap allRules = rules.getAllRules(); - assertEquals(3, allRules.size()); - assertEquals(true, allRules.containsKey("foo|bar")); - assertEquals(true, allRules.containsKey("foo|bar")); - assertEquals(true, allRules.containsKey("quux|foo")); - } - - @Test - public void getAllRulesMissingPropertyTest() { - EdgeRules rules = EdgeRules.getInstance("/dbedgerules/DbEdgeRules_test_broken.json"); - - thrown.expect(RuntimeException.class); - thrown.expectMessage("org.openecomp.aai.exceptions.AAIException: Rule between foo and bar is missing property delete-other-v."); - rules.getAllRules(); - } - - @Test - public void getChildrenMissingPropertyTest() { - EdgeRules rules = EdgeRules.getInstance("/dbedgerules/DbEdgeRules_test_broken.json"); - - thrown.expect(RuntimeException.class); - thrown.expectMessage("org.openecomp.aai.exceptions.AAIException: Rule between quux and foo is missing property SVC-INFRA."); - rules.getChildren("foo"); - } - - @Test - public void getEdgeRuleMissingPropertyTest() throws AAIException { - EdgeRules rules = EdgeRules.getInstance("/dbedgerules/DbEdgeRules_test_broken.json"); - - thrown.expect(RuntimeException.class); - thrown.expectMessage("org.openecomp.aai.exceptions.AAIException: Rule between quux and foo is missing property SVC-INFRA."); - rules.getEdgeRules("foo", "quux"); - } - - @Test - public void verifyAllRules() { - // This will cause every rule in the real json files to be verified - // so if any required properties are missing, the verification builds - // will catch it and incorrect rules can't get merged in. - for (Version v : Version.values()) { - EdgeRules rules = EdgeRules.getInstance(v); - rules.getAllRules(); - } - } -} diff --git a/aai-core/src/test/java/org/openecomp/aai/serialization/queryformats/QueryFormatTestHelper.java b/aai-core/src/test/java/org/openecomp/aai/serialization/queryformats/QueryFormatTestHelper.java deleted file mode 100644 index f9a511a2..00000000 --- a/aai-core/src/test/java/org/openecomp/aai/serialization/queryformats/QueryFormatTestHelper.java +++ /dev/null @@ -1,75 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.serialization.queryformats; - -import org.apache.tinkerpop.gremlin.structure.Graph; -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.apache.tinkerpop.gremlin.structure.io.IoCore; -import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; -import org.openecomp.aai.db.props.AAIProperties; -import org.openecomp.aai.serialization.queryformats.exceptions.AAIFormatVertexException; -import org.openecomp.aai.serialization.queryformats.utils.UrlBuilder; - -import java.io.IOException; -import java.lang.reflect.Field; -import java.lang.reflect.Modifier; - -import static org.mockito.Matchers.isA; -import static org.mockito.Mockito.when; - -public class QueryFormatTestHelper { - - - public static final String testResources = "src/test/resources/org/openecomp/aai/serialization/queryformats/"; - public static final String graphsonResources = "src/test/resources/org/openecomp/aai/serialization/queryformats/graphson/"; - - - public static void mockPathed(UrlBuilder mock) throws AAIFormatVertexException { - Answer answer = new Answer() { - public String answer(InvocationOnMock invocation) throws Throwable { - Vertex v = invocation.getArgumentAt(0, Vertex.class); - - return v.property(AAIProperties.AAI_URI).orElse("urimissing"); - } - }; - when(mock.pathed(isA(Vertex.class))).thenAnswer(answer); - - } - - public static Graph loadGraphson(String fileName) throws IOException { - final Graph graph = TinkerGraph.open(); - graph.io(IoCore.graphson()).readGraph(QueryFormatTestHelper.graphsonResources + fileName); - - return graph; - } - - public static void setFinalStatic(Field field, Object newValue) throws Exception { - field.setAccessible(true); - // remove final modifier from field - Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); - modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); - field.set(null, newValue); - } - -} diff --git a/aai-core/src/test/java/org/openecomp/aai/serialization/queryformats/SimpleFormatTest.java b/aai-core/src/test/java/org/openecomp/aai/serialization/queryformats/SimpleFormatTest.java deleted file mode 100644 index 766274cd..00000000 --- a/aai-core/src/test/java/org/openecomp/aai/serialization/queryformats/SimpleFormatTest.java +++ /dev/null @@ -1,163 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.serialization.queryformats; - -import com.google.gson.JsonObject; -import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; -import org.apache.tinkerpop.gremlin.process.traversal.strategy.verification.ReadOnlyStrategy; -import org.apache.tinkerpop.gremlin.structure.Graph; -import org.apache.tinkerpop.gremlin.structure.T; -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.openecomp.aai.dbmap.DBConnectionType; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.introspection.LoaderFactory; -import org.openecomp.aai.introspection.ModelType; -import org.openecomp.aai.introspection.Version; -import org.openecomp.aai.introspection.exceptions.AAIUnknownObjectException; -import org.openecomp.aai.serialization.db.DBSerializer; -import org.openecomp.aai.serialization.engines.QueryStyle; -import org.openecomp.aai.serialization.engines.TitanDBEngine; -import org.openecomp.aai.serialization.engines.TransactionalGraphEngine; -import org.openecomp.aai.serialization.queryformats.exceptions.AAIFormatVertexException; -import org.openecomp.aai.serialization.queryformats.utils.UrlBuilder; - -import java.io.UnsupportedEncodingException; - -import static org.junit.Assert.*; -import static org.mockito.Matchers.anyBoolean; -import static org.mockito.Matchers.anyInt; -import static org.mockito.Matchers.anyObject; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.*; - -public class SimpleFormatTest { - - @Mock - private UrlBuilder urlBuilder; - - private Graph graph; - private TransactionalGraphEngine dbEngine; - private Loader loader; - private DBSerializer serializer; - private RawFormat simpleFormat; - private Vertex vfModule; - private final ModelType factoryType = ModelType.MOXY; - - @Before - public void setUp() throws Exception { - - MockitoAnnotations.initMocks(this); - - graph = TinkerGraph.open(); - - vfModule = graph.addVertex( - T.label, "vf-module", - T.id, "5", - "aai-node-type", "vf-module", - "vf-module-id", "vf-module-id-val-68205", - "vf-module-name", "example-vf-module-name-val-68205", - "heat-stack-id", "example-heat-stack-id-val-68205", - "orchestration-status", "example-orchestration-status-val-68205", - "is-base-vf-module", "true", - "resource-version", "1498166571906", - "model-invariant-id", "fe8aac07-ce6c-4f9f-aa0d-b561c77da9e8", - "model-invariant-id-local", "fe8aac07-ce6c-4f9f-aa0d-b561c77da9e8", - "model-version-id", "0d23052d-8ffe-433e-a25d-da5da027bb7c", - "model-version-id-local", "0d23052d-8ffe-433e-a25d-da5da027bb7c", - "widget-model-id", "example-widget-model-id-val-68205", - "widget-model-version", "example-widget--model-version-val-68205", - "contrail-service-instance-fqdn", "example-contrail-service-instance-fqdn-val-68205" - ); - } - - @Test - public void testCreatePropertiesObjectReturnsProperProperties() throws AAIFormatVertexException, AAIException { - - createLoaderEngineSetup(); - serializer = new DBSerializer(Version.v10, dbEngine, factoryType, "Junit"); - simpleFormat = new RawFormat.Builder(loader, serializer, urlBuilder).nodesOnly(true).depth(0).modelDriven().build(); - - assertNotNull(dbEngine.tx()); - assertNotNull(dbEngine.asAdmin()); - - JsonObject json = simpleFormat.createPropertiesObject(vfModule); - - assertTrue(json.has("model-invariant-id")); - assertTrue(json.has("model-version-id")); - - assertFalse(json.has("model-invariant-id-local")); - assertFalse(json.has("model-version-id-local")); - - } - - @Ignore - @Test(expected = AAIFormatVertexException.class) - public void testCreatePropertiesObjectThrowsExceptionIfSerializationFails() throws AAIFormatVertexException, AAIException, UnsupportedEncodingException { - - serializer = mock(DBSerializer.class); - loader = mock(Loader.class); - - simpleFormat = new RawFormat.Builder(loader, serializer, urlBuilder).nodesOnly(true).depth(0).build(); - - when(serializer.dbToObject(anyObject(), anyObject(), anyInt(), anyBoolean(), anyString())) - .thenThrow(new AAIException("Test Exception")); - - simpleFormat.createPropertiesObject(vfModule); - } - - @Ignore - @Test(expected = AAIFormatVertexException.class) - public void testCreatePropertiesObjectThrowsExceptionIfUnknownObject() throws AAIFormatVertexException, AAIException, UnsupportedEncodingException { - - loader = mock(Loader.class); - serializer = mock(DBSerializer.class); - - simpleFormat = new RawFormat.Builder(loader, serializer, urlBuilder).nodesOnly(true).depth(0).build(); - - when(loader.introspectorFromName(anyString())) - .thenThrow(new AAIUnknownObjectException("Test Exception")); - - simpleFormat.createPropertiesObject(vfModule); - } - - public void createLoaderEngineSetup(){ - - if(loader == null){ - loader = LoaderFactory.createLoaderForVersion(factoryType, Version.v10); - dbEngine = spy(new TitanDBEngine(QueryStyle.TRAVERSAL, DBConnectionType.CACHED, loader)); - - TransactionalGraphEngine.Admin spyAdmin = spy(dbEngine.asAdmin()); - - when(dbEngine.tx()).thenReturn(graph); - when(dbEngine.asAdmin()).thenReturn(spyAdmin); - - when(spyAdmin.getReadOnlyTraversalSource()).thenReturn(graph.traversal(GraphTraversalSource.build().with(ReadOnlyStrategy.instance()))); - when(spyAdmin.getTraversalSource()).thenReturn(graph.traversal()); - } - } -} diff --git a/aai-core/src/test/java/org/openecomp/aai/serialization/queryformats/utils/QueryParamInjectorTest.java b/aai-core/src/test/java/org/openecomp/aai/serialization/queryformats/utils/QueryParamInjectorTest.java deleted file mode 100644 index 3eade856..00000000 --- a/aai-core/src/test/java/org/openecomp/aai/serialization/queryformats/utils/QueryParamInjectorTest.java +++ /dev/null @@ -1,59 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.serialization.queryformats.utils; - -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.serialization.db.DBSerializer; -import org.openecomp.aai.serialization.queryformats.Resource; -import org.openecomp.aai.serialization.queryformats.Resource.Builder; - -import javax.ws.rs.core.MultivaluedHashMap; -import javax.ws.rs.core.MultivaluedMap; - -import static org.junit.Assert.assertEquals; - -public class QueryParamInjectorTest { - - - @Mock private Loader loader; - @Mock private DBSerializer serializer; - @Mock private UrlBuilder urlBuilder; - - @Test - public void test() throws AAIException { - MockitoAnnotations.initMocks(this); - QueryParamInjector injector = QueryParamInjector.getInstance(); - - Builder b = new Resource.Builder(loader, serializer, urlBuilder); - MultivaluedMap params = new MultivaluedHashMap<>(); - params.putSingle("nodesOnly", "true"); - params.putSingle("depth", "10"); - params.putSingle("invalid", "1000"); - injector.injectParams(b, params); - - assertEquals("is nodes only", true, b.isNodesOnly()); - assertEquals("is depth 10", 10, b.getDepth()); - } -} diff --git a/aai-core/src/test/java/org/openecomp/aai/serialization/queryformats/utils/UrlBuilderTest.java b/aai-core/src/test/java/org/openecomp/aai/serialization/queryformats/utils/UrlBuilderTest.java deleted file mode 100644 index 605bbcd9..00000000 --- a/aai-core/src/test/java/org/openecomp/aai/serialization/queryformats/utils/UrlBuilderTest.java +++ /dev/null @@ -1,100 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.serialization.queryformats.utils; - -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.openecomp.aai.AAISetup; -import org.openecomp.aai.introspection.Version; -import org.openecomp.aai.serialization.db.DBSerializer; -import org.openecomp.aai.serialization.queryformats.exceptions.AAIFormatVertexException; -import org.openecomp.aai.util.AAIConstants; - -import java.io.UnsupportedEncodingException; -import java.net.URI; -import java.net.URISyntaxException; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.when; - -public class UrlBuilderTest extends AAISetup { - - @Mock - private DBSerializer serializer; - @Mock - private Vertex v; - - private static final String uri = "/test/uri"; - private static final Object vId = new Long(123); - private static final String protocolAndHost = "http://localhost/aai/"; - - @Before - public void before() throws UnsupportedEncodingException, URISyntaxException { - MockitoAnnotations.initMocks(this); - when(serializer.getURIForVertex(any(Vertex.class))).thenReturn(new URI(uri)); - when(v.id()).thenReturn(vId); - } - - @Test - public void v11Pathed() throws UnsupportedEncodingException, URISyntaxException, AAIFormatVertexException { - Version version = Version.v11; - UrlBuilder builder = new UrlBuilder(version, serializer, protocolAndHost); - String result = builder.pathed(v); - - assertEquals("has no protocol and host", AAIConstants.AAI_APP_ROOT + version + uri, result); - - } - - @Test - public void v11Id() throws UnsupportedEncodingException, URISyntaxException, AAIFormatVertexException { - Version version = Version.v11; - UrlBuilder builder = new UrlBuilder(version, serializer, protocolAndHost); - String result = builder.id(v); - - assertEquals("has no protocol and host", AAIConstants.AAI_APP_ROOT + version + "/resources/id/" + vId, result); - - } - - @Test - public void beforeV11Pathed() throws UnsupportedEncodingException, URISyntaxException, AAIFormatVertexException { - Version version = Version.v10; - UrlBuilder builder = new UrlBuilder(version, serializer, protocolAndHost); - String result = builder.pathed(v); - - assertEquals("has protocol and host", protocolAndHost + version + uri, result); - - } - - @Test - public void beforeV11Id() throws UnsupportedEncodingException, URISyntaxException, AAIFormatVertexException { - Version version = Version.v10; - UrlBuilder builder = new UrlBuilder(version, serializer, protocolAndHost); - String result = builder.id(v); - - assertEquals("has protocol and host", protocolAndHost + version + "/resources/id/" + vId, result); - - } - -} diff --git a/aai-core/src/test/java/org/openecomp/aai/serialization/tinkerpop/TreeBackedVertexTest.java b/aai-core/src/test/java/org/openecomp/aai/serialization/tinkerpop/TreeBackedVertexTest.java deleted file mode 100644 index c4440527..00000000 --- a/aai-core/src/test/java/org/openecomp/aai/serialization/tinkerpop/TreeBackedVertexTest.java +++ /dev/null @@ -1,152 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.serialization.tinkerpop; - -import 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.*; -import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.openecomp.aai.serialization.db.EdgeProperty; -import org.openecomp.aai.serialization.engines.query.GraphTraversalQueryEngine; - -import static org.junit.Assert.assertEquals; - -@Ignore -public class TreeBackedVertexTest { - - private Graph graph = TinkerGraph.open(); - private Object startKey = null; - private Tree tree = null; - private Tree treeDepth1 = null; - private Tree treeDepth0NodeOnly = null; - - @Before - public void configure() { - GraphTraversalSource g = graph.traversal(); - - startKey = g.addV(T.label, "vserver").as("v1").property("test", "hello") - .addV(T.label, "vserver").as("v2") - .addV(T.label, "interface").property("name", "interface 1").as("v7").addInE("hasChild", "v2").property(EdgeProperty.CONTAINS.toString(), true) - .addV(T.label, "pserver").property("name", "pserver 1").as("v4").addOutE("runsOn", "v1").property(EdgeProperty.CONTAINS.toString(), false) - .addV(T.label, "interface").property("name", "interface 2").as("v3").addInE("hasChild", "v1").property(EdgeProperty.CONTAINS.toString(), true) - .addV(T.label, "address").property("name", "address 1").addInE("hasChild", "v3").property(EdgeProperty.CONTAINS.toString(), true) - .addV(T.label, "address").property("name", "address 2").addInE("hasChild", "v3").property(EdgeProperty.CONTAINS.toString(), true) - .addV(T.label, "complex").property("name", "complex 1").addInE("locatedIn", "v4").property(EdgeProperty.CONTAINS.toString(), false) - .addV(T.label, "interface").property("name", "interface 3").addInE("hasChild", "v4").property(EdgeProperty.CONTAINS.toString(), true) - .addV(T.label, "subnet").property("name", "subnet 1").as("v5").addInE("in", "v3").property(EdgeProperty.CONTAINS.toString(), false) - .addV(T.label, "address").property("name", "address 3").as("v6").addInE("hasChild", "v5").property(EdgeProperty.CONTAINS.toString(), true) - .select("v1").next(); - - tree = new GraphTraversalQueryEngine(g).findSubGraph((Vertex)startKey); - treeDepth1 = new GraphTraversalQueryEngine(g).findSubGraph((Vertex)startKey, 1, false); - treeDepth0NodeOnly = new GraphTraversalQueryEngine(g).findSubGraph((Vertex)startKey, 0, true); - } - - @Ignore - @Test - public void oneHopViaEdges() { - - //BulkSet set = (BulkSet)result; - TreeBackedVertex v = new TreeBackedVertex((Vertex)tree.getObjectsAtDepth(1).iterator().next(), tree); - - - assertEquals("locate child", v.edges(Direction.OUT).next().inVertex().property("name").orElse(""), "interface 2"); - assertEquals("locate cousin", v.edges(Direction.IN).next().outVertex().property("name").orElse(""), "pserver 1"); - - - } - - @Ignore - @Test - public void oneHopViaVertices() { - - //BulkSet set = (BulkSet)result; - TreeBackedVertex v = new TreeBackedVertex((Vertex)tree.getObjectsAtDepth(1).iterator().next(), tree); - - - assertEquals("locate child", "interface 2", v.vertices(Direction.OUT).next().property("name").orElse("")); - assertEquals("locate cousin", "pserver 1", v.vertices(Direction.IN).next().property("name").orElse("")); - - } - - @Ignore - @Test - public void twoHopCousinViaVertices() { - - //BulkSet set = (BulkSet)result; - TreeBackedVertex v = new TreeBackedVertex((Vertex)tree.getObjectsAtDepth(1).iterator().next(), tree); - - - assertEquals("locate child", "subnet 1", v.vertices(Direction.OUT).next().vertices(Direction.OUT, "in").next().property("name").orElse("")); - - } - - @Test - public void walkVerticesRestrictedDepth() { - - //BulkSet set = (BulkSet)result; - TreeBackedVertex v = new TreeBackedVertex((Vertex)treeDepth1.getObjectsAtDepth(1).iterator().next(), treeDepth1); - - - assertEquals("nothing returned", false, v.vertices(Direction.OUT).next() - .vertices(Direction.OUT, "hasChild").hasNext()); - - } - - @Test - public void walkVertices() { - TreeBackedVertex v = new TreeBackedVertex((Vertex)tree.getObjectsAtDepth(1).iterator().next(), tree); - assertEquals("locate child", "address 2", v.vertices(Direction.OUT).next() - .vertices(Direction.OUT, "hasChild").next().property("name").orElse("")); - } - - @Test - public void walkEdges() { - TreeBackedVertex v = new TreeBackedVertex((Vertex)tree.getObjectsAtDepth(1).iterator().next(), tree); - - assertEquals("locate child", "address 2", v.edges(Direction.OUT).next().inVertex() - .edges(Direction.OUT, "hasChild").next().inVertex().property("name").orElse("")); - } - - @Test - public void noEdgesFoudWithLabelVertices() { - TreeBackedVertex v = new TreeBackedVertex((Vertex)tree.getObjectsAtDepth(1).iterator().next(), tree); - - assertEquals("missing hello label", false , v.vertices(Direction.OUT, "hello").hasNext()); - } - - @Test - public void noEdgesFoudWithLabelEdges() { - TreeBackedVertex v = new TreeBackedVertex((Vertex)tree.getObjectsAtDepth(1).iterator().next(), tree); - - assertEquals("missing hello label", false , v.edges(Direction.OUT, "hello").hasNext()); - } - - @Test - public void depthZeroNodeOnly() { - TreeBackedVertex v = new TreeBackedVertex((Vertex)treeDepth0NodeOnly.getObjectsAtDepth(1).iterator().next(), treeDepth0NodeOnly); - assertEquals("no edges returned", false, v.edges(Direction.BOTH).hasNext()); - } - -} diff --git a/aai-core/src/test/java/org/openecomp/aai/util/GenerateXsdTest.java b/aai-core/src/test/java/org/openecomp/aai/util/GenerateXsdTest.java deleted file mode 100644 index 230efaaf..00000000 --- a/aai-core/src/test/java/org/openecomp/aai/util/GenerateXsdTest.java +++ /dev/null @@ -1,54 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.util; - -import org.junit.Test; -import org.openecomp.aai.introspection.Version; - -public class GenerateXsdTest { - - @Test - public void testGenerationOfXsdAndYaml() throws Exception { - - GenerateXsd generateXsd = new GenerateXsd(); - System.setProperty("gen_version", Version.getLatest().toString()); - System.setProperty("gen_type", "XSD"); - System.setProperty("yamlresponses_url", ""); - System.setProperty("yamlresponses_label", ""); - - generateXsd.main(new String[]{}); - - System.setProperty("gen_version", Version.getLatest().toString()); - System.setProperty("gen_type", "YAML"); - - String wikiLink = System.getProperty("aai.wiki.link"); - - if(wikiLink == null){ - wikiLink = "https://wiki.onap.org/"; - } - - System.setProperty("yamlresponses_url", wikiLink); - System.setProperty("yamlresponses_label", "Response codes found in [response codes]"); - - generateXsd.main(new String[]{}); - } - -} diff --git a/aai-core/src/test/java/org/openecomp/aai/workarounds/RemoveDME2QueryParamsTest.java b/aai-core/src/test/java/org/openecomp/aai/workarounds/RemoveDME2QueryParamsTest.java deleted file mode 100644 index 51636271..00000000 --- a/aai-core/src/test/java/org/openecomp/aai/workarounds/RemoveDME2QueryParamsTest.java +++ /dev/null @@ -1,91 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.workarounds; - -import org.junit.Before; -import org.junit.Test; - -import javax.ws.rs.core.MultivaluedHashMap; -import javax.ws.rs.core.MultivaluedMap; - -import static org.junit.Assert.assertEquals; - -public class RemoveDME2QueryParamsTest { - - private MultivaluedMap hasParams; - private MultivaluedMap doesNotHaveParams; - private RemoveDME2QueryParams removeParams = new RemoveDME2QueryParams(); - - /** - * Setup. - */ - @Before - public void setup() { - hasParams = new MultivaluedHashMap<>(); - doesNotHaveParams = new MultivaluedHashMap<>(); - - hasParams.add("version", "1"); - hasParams.add("envContext", "DEV"); - hasParams.add("routeOffer", "INT1"); - hasParams.add("test1", "peppermints"); - hasParams.add("test2", "amber"); - - doesNotHaveParams.add("version", "1"); - doesNotHaveParams.add("envContext", "DEV"); - doesNotHaveParams.add("test1", "peppermints"); - doesNotHaveParams.add("test2", "amber"); - - } - - /** - * Test removal. - */ - @Test - public void testRemoval() { - - if (removeParams.shouldRemoveQueryParams(hasParams)) { - removeParams.removeQueryParams(hasParams); - } - - assertEquals("no version", false, hasParams.containsKey("version")); - assertEquals("no envContext", false, hasParams.containsKey("envContext")); - assertEquals("no routeOffer", false, hasParams.containsKey("routeOffer")); - assertEquals("has test1", true, hasParams.containsKey("test1")); - assertEquals("has test2", true, hasParams.containsKey("test2")); - - } - - /** - * Should not remove. - */ - @Test - public void shouldNotRemove() { - - if (removeParams.shouldRemoveQueryParams(doesNotHaveParams)) { - removeParams.removeQueryParams(doesNotHaveParams); - } - - assertEquals("no version", true, doesNotHaveParams.containsKey("version")); - assertEquals("no envContext", true, doesNotHaveParams.containsKey("envContext")); - assertEquals("has test1", true, doesNotHaveParams.containsKey("test1")); - assertEquals("has test2", true, doesNotHaveParams.containsKey("test2")); - } -} diff --git a/aai-core/src/test/resources/bundleconfig-local/etc/appprops/aaiconfig.properties b/aai-core/src/test/resources/bundleconfig-local/etc/appprops/aaiconfig.properties index 9532c7c1..3da02475 100644 --- a/aai-core/src/test/resources/bundleconfig-local/etc/appprops/aaiconfig.properties +++ b/aai-core/src/test/resources/bundleconfig-local/etc/appprops/aaiconfig.properties @@ -1,22 +1,24 @@ -### +# # ============LICENSE_START======================================================= -# org.openecomp.aai +# org.onap.aai # ================================================================================ -# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. +# Copyright © 2017 AT&T Intellectual Property. All rights reserved. # ================================================================================ # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# +# +# http://www.apache.org/licenses/LICENSE-2.0 +# # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============LICENSE_END========================================================= -### +# +# ECOMP is a trademark and service mark of AT&T Intellectual Property. +# aai.server.url.base=https://baseurl:8443/aai/ aai.resourceversion.enableflag=true diff --git a/aai-core/src/test/resources/bundleconfig-local/etc/appprops/titan-cached.properties b/aai-core/src/test/resources/bundleconfig-local/etc/appprops/titan-cached.properties index 2afe2234..84f56d1c 100644 --- a/aai-core/src/test/resources/bundleconfig-local/etc/appprops/titan-cached.properties +++ b/aai-core/src/test/resources/bundleconfig-local/etc/appprops/titan-cached.properties @@ -1,3 +1,25 @@ +# +# ============LICENSE_START======================================================= +# org.onap.aai +# ================================================================================ +# Copyright © 2017 AT&T Intellectual Property. All rights reserved. +# ================================================================================ +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============LICENSE_END========================================================= +# +# ECOMP is a trademark and service mark of AT&T Intellectual Property. +# + query.fast-property=true # the following parameters are not reloaded automatically and require a manual bounce storage.backend=inmemory diff --git a/aai-core/src/test/resources/bundleconfig-local/etc/appprops/titan-realtime.properties b/aai-core/src/test/resources/bundleconfig-local/etc/appprops/titan-realtime.properties index 9c5c0299..3ee65306 100644 --- a/aai-core/src/test/resources/bundleconfig-local/etc/appprops/titan-realtime.properties +++ b/aai-core/src/test/resources/bundleconfig-local/etc/appprops/titan-realtime.properties @@ -1,3 +1,25 @@ +# +# ============LICENSE_START======================================================= +# org.onap.aai +# ================================================================================ +# Copyright © 2017 AT&T Intellectual Property. All rights reserved. +# ================================================================================ +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============LICENSE_END========================================================= +# +# ECOMP is a trademark and service mark of AT&T Intellectual Property. +# + query.fast-property=true # the following parameters are not reloaded automatically and require a manual bounce storage.backend=inmemory diff --git a/aai-core/src/test/resources/bundleconfig-local/etc/oxm/aai_oxm_v10.xml b/aai-core/src/test/resources/bundleconfig-local/etc/oxm/aai_oxm_v10.xml index 2d09ff0f..d3c46600 100644 --- a/aai-core/src/test/resources/bundleconfig-local/etc/oxm/aai_oxm_v10.xml +++ b/aai-core/src/test/resources/bundleconfig-local/etc/oxm/aai_oxm_v10.xml @@ -1,24 +1,27 @@ + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + ============LICENSE_END========================================================= + + ECOMP is a trademark and service mark of AT&T Intellectual Property. + +--> diff --git a/aai-core/src/test/resources/bundleconfig-local/etc/oxm/aai_oxm_v11.xml b/aai-core/src/test/resources/bundleconfig-local/etc/oxm/aai_oxm_v11.xml index 7daf12ab..ecbfefb8 100644 --- a/aai-core/src/test/resources/bundleconfig-local/etc/oxm/aai_oxm_v11.xml +++ b/aai-core/src/test/resources/bundleconfig-local/etc/oxm/aai_oxm_v11.xml @@ -1,24 +1,27 @@ + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + ============LICENSE_END========================================================= + + ECOMP is a trademark and service mark of AT&T Intellectual Property. + +--> diff --git a/aai-core/src/test/resources/bundleconfig-local/etc/oxm/aai_oxm_v2.xml b/aai-core/src/test/resources/bundleconfig-local/etc/oxm/aai_oxm_v2.xml index c3b30b45..eba7c4b9 100644 --- a/aai-core/src/test/resources/bundleconfig-local/etc/oxm/aai_oxm_v2.xml +++ b/aai-core/src/test/resources/bundleconfig-local/etc/oxm/aai_oxm_v2.xml @@ -1,24 +1,27 @@ + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + ============LICENSE_END========================================================= + + ECOMP is a trademark and service mark of AT&T Intellectual Property. + +--> diff --git a/aai-core/src/test/resources/bundleconfig-local/etc/oxm/aai_oxm_v8.xml b/aai-core/src/test/resources/bundleconfig-local/etc/oxm/aai_oxm_v8.xml index b5a64c87..7474362f 100644 --- a/aai-core/src/test/resources/bundleconfig-local/etc/oxm/aai_oxm_v8.xml +++ b/aai-core/src/test/resources/bundleconfig-local/etc/oxm/aai_oxm_v8.xml @@ -1,24 +1,27 @@ + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + ============LICENSE_END========================================================= + + ECOMP is a trademark and service mark of AT&T Intellectual Property. + +--> diff --git a/aai-core/src/test/resources/bundleconfig-local/etc/oxm/aai_oxm_v9.xml b/aai-core/src/test/resources/bundleconfig-local/etc/oxm/aai_oxm_v9.xml index f53bd860..bfd67319 100644 --- a/aai-core/src/test/resources/bundleconfig-local/etc/oxm/aai_oxm_v9.xml +++ b/aai-core/src/test/resources/bundleconfig-local/etc/oxm/aai_oxm_v9.xml @@ -1,24 +1,27 @@ + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + ============LICENSE_END========================================================= + + ECOMP is a trademark and service mark of AT&T Intellectual Property. + +--> @@ -4247,7 +4250,7 @@ - + @@ -4277,7 +4280,7 @@ - + diff --git a/aai-core/src/test/resources/logback.xml b/aai-core/src/test/resources/logback.xml index d9627b22..959ef63f 100644 --- a/aai-core/src/test/resources/logback.xml +++ b/aai-core/src/test/resources/logback.xml @@ -1,21 +1,26 @@ + ============LICENSE_START======================================================= + org.onap.aai + ================================================================================ + Copyright © 2017 AT&T Intellectual Property. All rights reserved. + ================================================================================ + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + ============LICENSE_END========================================================= + + ECOMP is a trademark and service mark of AT&T Intellectual Property. + +--> ${module.ajsc.namespace.name} @@ -270,12 +275,12 @@ --> - + diff --git a/aai-core/src/test/resources/org/openecomp/aai/introspection/aai_oxm_v10.xml b/aai-core/src/test/resources/org/openecomp/aai/introspection/aai_oxm_v10.xml index 728e4b43..818128eb 100644 --- a/aai-core/src/test/resources/org/openecomp/aai/introspection/aai_oxm_v10.xml +++ b/aai-core/src/test/resources/org/openecomp/aai/introspection/aai_oxm_v10.xml @@ -1,23 +1,28 @@ - - + + ============LICENSE_START======================================================= + org.onap.aai + ================================================================================ + Copyright © 2017 AT&T Intellectual Property. All rights reserved. + ================================================================================ + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + ============LICENSE_END========================================================= + + ECOMP is a trademark and service mark of AT&T Intellectual Property. + +--> + @@ -25,14 +30,14 @@ - - - - - - - - + + + + + + + + @@ -42,24 +47,24 @@ - - - - + + + + - + - + @@ -68,8 +73,8 @@ - - + + @@ -87,9 +92,9 @@ - - - + + + @@ -120,7 +125,7 @@ - + @@ -143,16 +148,16 @@ - - + + - - + + @@ -162,8 +167,8 @@ - - + + @@ -174,9 +179,9 @@ - + - + @@ -184,7 +189,7 @@ - + @@ -210,7 +215,7 @@ - + @@ -229,18 +234,18 @@ - - - - - + + + + + - + @@ -295,16 +300,16 @@ - - - - - - - - - - + + + + + + + + + + @@ -320,7 +325,7 @@ - + @@ -367,7 +372,7 @@ - + @@ -381,7 +386,7 @@ - + @@ -398,8 +403,8 @@ - - + + @@ -441,7 +446,7 @@ - + @@ -492,8 +497,8 @@ - - + + @@ -508,7 +513,7 @@ - + @@ -540,7 +545,7 @@ - + @@ -556,7 +561,7 @@ - + @@ -581,8 +586,8 @@ - - + + @@ -600,7 +605,7 @@ - + @@ -649,9 +654,9 @@ - - - + + + @@ -669,7 +674,7 @@ - + @@ -738,12 +743,12 @@ - - - - - - + + + + + + @@ -759,7 +764,7 @@ - + @@ -835,7 +840,7 @@ - + @@ -888,7 +893,7 @@ - + @@ -900,7 +905,7 @@ - + @@ -963,9 +968,9 @@ - - - + + + @@ -1019,7 +1024,7 @@ - + @@ -1034,7 +1039,7 @@ - + @@ -1056,7 +1061,7 @@ - + @@ -1072,7 +1077,7 @@ - + @@ -1134,7 +1139,7 @@ - + @@ -1151,7 +1156,7 @@ - + @@ -1213,7 +1218,7 @@ - + @@ -1231,7 +1236,7 @@ - + @@ -1263,7 +1268,7 @@ - + @@ -1280,7 +1285,7 @@ - + @@ -1337,8 +1342,8 @@ - - + + @@ -1355,7 +1360,7 @@ - + @@ -1384,7 +1389,7 @@ - + @@ -1406,7 +1411,7 @@ - + @@ -1422,7 +1427,7 @@ - + @@ -1444,7 +1449,7 @@ - + @@ -1460,7 +1465,7 @@ - + @@ -1596,9 +1601,9 @@ - - - + + + @@ -1616,7 +1621,7 @@ - + @@ -1674,8 +1679,8 @@ - - + + @@ -1692,7 +1697,7 @@ - + @@ -1745,8 +1750,8 @@ - - + + @@ -1762,7 +1767,7 @@ - + @@ -1799,7 +1804,7 @@ - + @@ -1816,7 +1821,7 @@ - + @@ -1843,7 +1848,7 @@ - + @@ -1859,7 +1864,7 @@ - + @@ -1881,7 +1886,7 @@ - + @@ -1901,8 +1906,8 @@ - - + + @@ -1912,7 +1917,7 @@ - + @@ -1960,8 +1965,8 @@ - - + + @@ -1977,7 +1982,7 @@ - + @@ -2008,8 +2013,8 @@ - - + + @@ -2028,7 +2033,7 @@ - + @@ -2050,9 +2055,9 @@ - + - + @@ -2069,7 +2074,7 @@ - + @@ -2172,9 +2177,9 @@ - - - + + + @@ -2193,11 +2198,11 @@ - - - - - + + + + + @@ -2207,7 +2212,7 @@ - + @@ -2244,7 +2249,7 @@ - + @@ -2261,7 +2266,7 @@ - + @@ -2293,7 +2298,7 @@ - + @@ -2309,7 +2314,7 @@ - + @@ -2331,7 +2336,7 @@ - + @@ -2347,26 +2352,26 @@ - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + type="inventory.aai.onap.org.v10.TestObjects" /> @@ -2376,7 +2381,7 @@ - + @@ -2484,7 +2489,7 @@ - + @@ -2502,7 +2507,7 @@ - + @@ -2519,8 +2524,8 @@ - - + + @@ -2537,7 +2542,7 @@ - + @@ -2559,8 +2564,8 @@ - - + + @@ -2576,7 +2581,7 @@ - + @@ -2618,8 +2623,8 @@ - - + + @@ -2635,7 +2640,7 @@ - + @@ -2662,7 +2667,7 @@ - + @@ -2674,7 +2679,7 @@ - + @@ -2721,9 +2726,9 @@ - + - + @@ -2745,7 +2750,7 @@ - + @@ -2766,7 +2771,7 @@ - + @@ -2780,7 +2785,7 @@ - + @@ -2813,9 +2818,9 @@ - - - + + + @@ -2831,7 +2836,7 @@ - + @@ -2858,7 +2863,7 @@ - + @@ -2874,7 +2879,7 @@ - + @@ -2976,10 +2981,10 @@ - - - - + + + + @@ -2996,7 +3001,7 @@ - + @@ -3058,8 +3063,8 @@ - - + + @@ -3073,7 +3078,7 @@ - + @@ -3090,7 +3095,7 @@ - + @@ -3107,7 +3112,7 @@ - + @@ -3166,7 +3171,7 @@ - + @@ -3179,7 +3184,7 @@ - + @@ -3326,10 +3331,10 @@ - - - - + + + + @@ -3348,7 +3353,7 @@ - + @@ -3374,7 +3379,7 @@ - + @@ -3388,7 +3393,7 @@ - + @@ -3405,7 +3410,7 @@ - + @@ -3417,7 +3422,7 @@ - + @@ -3485,7 +3490,7 @@ - + @@ -3502,7 +3507,7 @@ - + @@ -3750,12 +3755,12 @@ - - - - - - + + + + + + @@ -3775,7 +3780,7 @@ - + @@ -3864,7 +3869,7 @@ - + @@ -3882,7 +3887,7 @@ - + @@ -3899,7 +3904,7 @@ - + @@ -3915,7 +3920,7 @@ - + @@ -3992,8 +3997,8 @@ - - + + @@ -4012,7 +4017,7 @@ - + @@ -4133,9 +4138,9 @@ - - - + + + @@ -4153,7 +4158,7 @@ - + @@ -4203,7 +4208,7 @@ - + @@ -4218,7 +4223,7 @@ - + @@ -4245,7 +4250,7 @@ - + @@ -4258,7 +4263,7 @@ - + @@ -4375,8 +4380,8 @@ - - + + @@ -4392,7 +4397,7 @@ - + @@ -4417,8 +4422,8 @@ - - + + @@ -4463,7 +4468,7 @@ - + @@ -4493,8 +4498,8 @@ - - + + @@ -4502,7 +4507,7 @@ - + @@ -4541,16 +4546,16 @@ - - - + + + - + @@ -4587,24 +4592,24 @@ - + - + - + - + @@ -4625,7 +4630,7 @@ - + @@ -4637,7 +4642,7 @@ - + @@ -4660,15 +4665,15 @@ - - + + - + @@ -4691,15 +4696,15 @@ - - + + - + @@ -4722,15 +4727,15 @@ - - + + - + @@ -4754,17 +4759,17 @@ - - - - + + + + - + @@ -4790,14 +4795,14 @@ - + - + @@ -4830,9 +4835,9 @@ - - - + + + @@ -4844,8 +4849,8 @@ - - + + @@ -4895,8 +4900,8 @@ - - + + @@ -4906,7 +4911,7 @@ - + @@ -4927,7 +4932,7 @@ - + @@ -4958,7 +4963,7 @@ - + @@ -4969,7 +4974,7 @@ - + @@ -4982,8 +4987,8 @@ - - + + @@ -4993,7 +4998,7 @@ - + @@ -5011,7 +5016,7 @@ - + @@ -5033,7 +5038,7 @@ - + @@ -5052,7 +5057,7 @@ - + @@ -5084,7 +5089,7 @@ - + @@ -5104,7 +5109,7 @@ - + @@ -5121,7 +5126,7 @@ - + @@ -5137,7 +5142,7 @@ - + @@ -5205,8 +5210,8 @@ - - + + @@ -5226,7 +5231,7 @@ - + @@ -5263,7 +5268,7 @@ - + @@ -5282,7 +5287,7 @@ - + @@ -5304,7 +5309,7 @@ - + @@ -5321,7 +5326,7 @@ - + @@ -5343,7 +5348,7 @@ - + @@ -5377,7 +5382,7 @@ - + @@ -5414,7 +5419,7 @@ - + @@ -5433,7 +5438,7 @@ + type="inventory.aai.onap.org.v10.TestObject" /> @@ -5771,8 +5776,8 @@ - - + + diff --git a/aai-core/src/test/resources/org/openecomp/aai/introspection/aai_oxm_v8.xml b/aai-core/src/test/resources/org/openecomp/aai/introspection/aai_oxm_v8.xml index 3ed2ea53..06dc6e03 100644 --- a/aai-core/src/test/resources/org/openecomp/aai/introspection/aai_oxm_v8.xml +++ b/aai-core/src/test/resources/org/openecomp/aai/introspection/aai_oxm_v8.xml @@ -1,25 +1,28 @@ - - + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + ============LICENSE_END========================================================= + + ECOMP is a trademark and service mark of AT&T Intellectual Property. + +--> + @@ -27,20 +30,20 @@ - - - - - - - + + + + + + + - + @@ -48,7 +51,7 @@ - + @@ -57,8 +60,8 @@ - - + + @@ -98,7 +101,7 @@ - + @@ -124,8 +127,8 @@ - - + + @@ -136,9 +139,9 @@ - + - + @@ -146,7 +149,7 @@ - + @@ -172,7 +175,7 @@ - + @@ -191,15 +194,15 @@ - - + + - + @@ -251,14 +254,14 @@ - - - - - - - - + + + + + + + + @@ -274,7 +277,7 @@ - + @@ -311,7 +314,7 @@ - + @@ -324,7 +327,7 @@ - + @@ -341,8 +344,8 @@ - - + + @@ -384,7 +387,7 @@ - + @@ -406,8 +409,8 @@ - - + + @@ -424,7 +427,7 @@ - + @@ -473,9 +476,9 @@ - - - + + + @@ -493,7 +496,7 @@ - + @@ -545,10 +548,10 @@ - - - - + + + + @@ -601,7 +604,7 @@ - + @@ -613,7 +616,7 @@ - + @@ -665,9 +668,9 @@ - - - + + + @@ -721,7 +724,7 @@ - + @@ -736,7 +739,7 @@ - + @@ -758,7 +761,7 @@ - + @@ -774,7 +777,7 @@ - + @@ -836,7 +839,7 @@ - + @@ -853,7 +856,7 @@ - + @@ -915,7 +918,7 @@ - + @@ -933,7 +936,7 @@ - + @@ -965,7 +968,7 @@ - + @@ -982,7 +985,7 @@ - + @@ -1039,8 +1042,8 @@ - - + + @@ -1057,7 +1060,7 @@ - + @@ -1086,7 +1089,7 @@ - + @@ -1184,9 +1187,9 @@ - - - + + + @@ -1204,7 +1207,7 @@ - + @@ -1251,8 +1254,8 @@ - - + + @@ -1268,7 +1271,7 @@ - + @@ -1295,8 +1298,8 @@ - - + + @@ -1312,7 +1315,7 @@ - + @@ -1339,7 +1342,7 @@ - + @@ -1355,7 +1358,7 @@ - + @@ -1365,7 +1368,7 @@ - + @@ -1393,8 +1396,8 @@ - - + + @@ -1414,7 +1417,7 @@ - + @@ -1436,9 +1439,9 @@ - + - + @@ -1454,7 +1457,7 @@ - + @@ -1536,8 +1539,8 @@ - - + + @@ -1556,9 +1559,9 @@ - - - + + + @@ -1568,12 +1571,12 @@ - - - - - - + + + + + + @@ -1583,7 +1586,7 @@ - + @@ -1665,7 +1668,7 @@ - + @@ -1682,7 +1685,7 @@ - + @@ -1741,7 +1744,7 @@ - + @@ -1753,7 +1756,7 @@ - + @@ -1874,10 +1877,10 @@ - - - - + + + + @@ -1896,7 +1899,7 @@ - + @@ -1913,7 +1916,7 @@ - + @@ -1925,7 +1928,7 @@ - + @@ -1993,7 +1996,7 @@ - + @@ -2010,7 +2013,7 @@ - + @@ -2219,10 +2222,10 @@ - - - - + + + + @@ -2242,7 +2245,7 @@ - + @@ -2305,7 +2308,7 @@ - + @@ -2321,7 +2324,7 @@ - + @@ -2399,9 +2402,9 @@ - - - + + + @@ -2418,7 +2421,7 @@ - + @@ -2465,7 +2468,7 @@ - + @@ -2480,7 +2483,7 @@ - + @@ -2506,8 +2509,8 @@ - - + + @@ -2553,7 +2556,7 @@ - + @@ -2585,7 +2588,7 @@ - + @@ -2601,7 +2604,7 @@ - + @@ -2652,16 +2655,16 @@ - - - + + + - + @@ -2699,24 +2702,24 @@ - + - + - + - + @@ -2737,14 +2740,14 @@ - + - + @@ -2767,15 +2770,15 @@ - - + + - + @@ -2798,15 +2801,15 @@ - - + + - + @@ -2829,15 +2832,15 @@ - - + + - + @@ -2861,17 +2864,17 @@ - - - - + + + + - + @@ -2897,14 +2900,14 @@ - + - + @@ -2937,8 +2940,8 @@ - - + + @@ -2949,8 +2952,8 @@ - - + + @@ -2960,7 +2963,7 @@ - + @@ -2992,7 +2995,7 @@ - + @@ -3003,7 +3006,7 @@ - + @@ -3016,8 +3019,8 @@ - - + + @@ -3027,7 +3030,7 @@ - + @@ -3045,7 +3048,7 @@ - + @@ -3062,7 +3065,7 @@ - + diff --git a/aai-core/src/test/resources/org/openecomp/aai/introspection/aai_oxm_v9.xml b/aai-core/src/test/resources/org/openecomp/aai/introspection/aai_oxm_v9.xml index 6c372083..aec9b83d 100644 --- a/aai-core/src/test/resources/org/openecomp/aai/introspection/aai_oxm_v9.xml +++ b/aai-core/src/test/resources/org/openecomp/aai/introspection/aai_oxm_v9.xml @@ -1,23 +1,28 @@ - + ============LICENSE_START======================================================= + org.onap.aai + ================================================================================ + Copyright © 2017 AT&T Intellectual Property. All rights reserved. + ================================================================================ + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + ============LICENSE_END========================================================= + + ECOMP is a trademark and service mark of AT&T Intellectual Property. + +--> + @@ -25,7 +30,7 @@ - + @@ -34,8 +39,8 @@ - - + + @@ -44,7 +49,7 @@ - + @@ -53,7 +58,7 @@ - + @@ -83,7 +88,7 @@ - + @@ -91,7 +96,7 @@ - + @@ -135,7 +140,7 @@ - + @@ -363,7 +368,7 @@ - + @@ -380,7 +385,7 @@ - + @@ -454,7 +459,7 @@ - + @@ -471,8 +476,8 @@ - - + + @@ -525,7 +530,7 @@ - + @@ -574,7 +579,7 @@ - + -- cgit 1.2.3-korg